id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,600
|
RawData.py
|
PyGithub_PyGithub/tests/RawData.py
|
############################ Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import github.NamedUser
from . import Framework
class RawData(Framework.TestCase):
jacquev6RawData = {
"disk_usage": 13812,
"private_gists": 5,
"public_repos": 21,
"subscriptions_url": "https://api.github.com/users/jacquev6/subscriptions",
"gravatar_id": "b68de5ae38616c296fa345d2b9df2225",
"hireable": False,
"id": 327146,
"followers_url": "https://api.github.com/users/jacquev6/followers",
"following_url": "https://api.github.com/users/jacquev6/following",
"collaborators": 1,
"total_private_repos": 4,
"blog": "http://vincent-jacques.net",
"followers": 22,
"location": "Paris, France",
"type": "User",
"email": "vincent@vincent-jacques.net",
"bio": "",
"gists_url": "https://api.github.com/users/jacquev6/gists{/gist_id}",
"owned_private_repos": 4,
"company": "Criteo",
"events_url": "https://api.github.com/users/jacquev6/events{/privacy}",
"html_url": "https://github.com/jacquev6",
"updated_at": "2013-03-12T22:13:32Z",
"plan": {
"collaborators": 1,
"name": "micro",
"private_repos": 5,
"space": 614400,
},
"received_events_url": "https://api.github.com/users/jacquev6/received_events",
"starred_url": "https://api.github.com/users/jacquev6/starred{/owner}{/repo}",
"public_gists": 2,
"name": "Vincent Jacques",
"organizations_url": "https://api.github.com/users/jacquev6/orgs",
"url": "https://api.github.com/users/jacquev6",
"created_at": "2010-07-09T06:10:06Z",
"avatar_url": "https://secure.gravatar.com/avatar/b68de5ae38616c296fa345d2b9df2225?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png",
"repos_url": "https://api.github.com/users/jacquev6/repos",
"following": 38,
"login": "jacquev6",
}
planRawData = {
"collaborators": 1,
"name": "micro",
"private_repos": 5,
"space": 614400,
}
def testCompletedObject(self):
user = self.g.get_user("jacquev6")
self.assertTrue(user._CompletableGithubObject__completed)
self.assertEqual(user.raw_data, RawData.jacquev6RawData)
def testNotYetCompletedObject(self):
user = self.g.get_user().get_repo("PyGithub").owner
self.assertFalse(user._CompletableGithubObject__completed)
self.assertEqual(user.raw_data, RawData.jacquev6RawData)
self.assertTrue(user._CompletableGithubObject__completed)
def testNonCompletableObject(self):
plan = self.g.get_user().plan
self.assertEqual(plan.raw_data, RawData.planRawData)
def testCreateObjectFromRawData(self):
user = self.g.create_from_raw_data(github.NamedUser.NamedUser, RawData.jacquev6RawData)
self.assertEqual(user._CompletableGithubObject__completed, True)
self.assertEqual(user.name, "Vincent Jacques")
| 5,482
|
Python
|
.py
| 97
| 50.309278
| 183
| 0.548735
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,601
|
Branch.py
|
PyGithub_PyGithub/tests/Branch.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Kyle Hornberg <khornberg@users.noreply.github.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import github
from . import Framework
class Branch(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_user().get_repo("PyGithub")
self.branch = self.repo.get_branch("topic/RewriteWithGeneratedCode")
self.protected_branch = self.repo.get_branch("integrations")
self.organization_branch = self.g.get_repo("PyGithub/PyGithub", lazy=True).get_branch("master")
def testAttributes(self):
self.assertEqual(self.branch.name, "topic/RewriteWithGeneratedCode")
self.assertEqual(self.branch.commit.sha, "1292bf0e22c796e91cc3d6e24b544aece8c21f2a")
self.assertEqual(
self.branch.protection_url,
"https://api.github.com/repos/jacquev6/PyGithub/branches/topic/RewriteWithGeneratedCode/protection",
)
self.assertFalse(self.branch.protected)
self.assertEqual(repr(self.branch), 'Branch(name="topic/RewriteWithGeneratedCode")')
def testEditProtection(self):
self.protected_branch.edit_protection(
strict=True,
require_code_owner_reviews=True,
required_approving_review_count=2,
require_last_push_approval=True,
)
branch_protection = self.protected_branch.get_protection()
self.assertTrue(branch_protection.required_status_checks.strict)
self.assertEqual(branch_protection.required_status_checks.contexts, [])
self.assertTrue(branch_protection.enforce_admins)
self.assertFalse(branch_protection.required_linear_history)
self.assertFalse(branch_protection.allow_deletions)
self.assertFalse(branch_protection.required_pull_request_reviews.dismiss_stale_reviews)
self.assertTrue(branch_protection.required_pull_request_reviews.require_code_owner_reviews)
self.assertEqual(
branch_protection.required_pull_request_reviews.required_approving_review_count,
2,
)
self.assertTrue(branch_protection.required_pull_request_reviews.require_last_push_approval)
def testEditProtectionDismissalUsersWithUserOwnedBranch(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.protected_branch.edit_protection(dismissal_users=["jacquev6"])
self.assertEqual(raisedexp.exception.status, 422)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#update-branch-protection",
"message": "Validation Failed",
"errors": ["Only organization repositories can have users and team restrictions"],
},
)
def testEditProtectionPushRestrictionsWithUserOwnedBranch(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.protected_branch.edit_protection(user_push_restrictions=["jacquev6"], team_push_restrictions=[])
self.assertEqual(raisedexp.exception.status, 422)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#update-branch-protection",
"message": "Validation Failed",
"errors": ["Only organization repositories can have users and team restrictions"],
},
)
def testEditProtectionPushRestrictionsAndDismissalUser(self):
self.organization_branch.edit_protection(dismissal_users=["jacquev6"], user_push_restrictions=["jacquev6"])
branch_protection = self.organization_branch.get_protection()
self.assertListKeyEqual(
branch_protection.required_pull_request_reviews.dismissal_users,
lambda u: u.login,
["jacquev6"],
)
self.assertListKeyEqual(
branch_protection.required_pull_request_reviews.dismissal_teams,
lambda u: u.slug,
[],
)
self.assertListKeyEqual(
branch_protection.get_user_push_restrictions(),
lambda u: u.login,
["jacquev6"],
)
self.assertListKeyEqual(branch_protection.get_team_push_restrictions(), lambda u: u.slug, [])
def testRemoveProtection(self):
self.assertTrue(self.protected_branch.protected)
self.protected_branch.remove_protection()
protected_branch = self.repo.get_branch("integrations")
self.assertFalse(protected_branch.protected)
with self.assertRaises(github.GithubException) as raisedexp:
protected_branch.get_protection()
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#get-branch-protection",
"message": "Branch not protected",
},
)
def testEditRequiredStatusChecks(self):
self.protected_branch.edit_required_status_checks(strict=True)
required_status_checks = self.protected_branch.get_required_status_checks()
self.assertTrue(required_status_checks.strict)
self.assertEqual(required_status_checks.contexts, ["foo/bar"])
def testRemoveRequiredStatusChecks(self):
self.protected_branch.remove_required_status_checks()
with self.assertRaises(github.GithubException) as raisedexp:
self.protected_branch.get_required_status_checks()
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch",
"message": "Required status checks not enabled",
},
)
def testEditRequiredPullRequestReviews(self):
self.protected_branch.edit_required_pull_request_reviews(
dismiss_stale_reviews=True,
required_approving_review_count=2,
)
required_pull_request_reviews = self.protected_branch.get_required_pull_request_reviews()
self.assertTrue(required_pull_request_reviews.dismiss_stale_reviews)
self.assertTrue(required_pull_request_reviews.require_code_owner_reviews)
self.assertEqual(required_pull_request_reviews.required_approving_review_count, 2)
def testEditRequiredPullRequestReviewsWithTooLargeApprovingReviewCount(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.protected_branch.edit_required_pull_request_reviews(required_approving_review_count=9)
self.assertEqual(raisedexp.exception.status, 422)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch",
"message": "Invalid request.\n\n9 must be less than or equal to 6.",
},
)
def testEditRequiredPullRequestReviewsWithUserBranchAndDismissalUsers(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.protected_branch.edit_required_pull_request_reviews(dismissal_users=["jacquev6"])
self.assertEqual(raisedexp.exception.status, 422)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch",
"message": "Dismissal restrictions are supported only for repositories owned by an organization.",
},
)
def testRemoveRequiredPullRequestReviews(self):
self.protected_branch.remove_required_pull_request_reviews()
required_pull_request_reviews = self.protected_branch.get_required_pull_request_reviews()
self.assertFalse(required_pull_request_reviews.dismiss_stale_reviews)
self.assertFalse(required_pull_request_reviews.require_code_owner_reviews)
self.assertEqual(required_pull_request_reviews.required_approving_review_count, 1)
self.assertFalse(required_pull_request_reviews.require_last_push_approval)
def testAdminEnforcement(self):
self.protected_branch.remove_admin_enforcement()
self.assertFalse(self.protected_branch.get_admin_enforcement())
self.protected_branch.set_admin_enforcement()
self.assertTrue(self.protected_branch.get_admin_enforcement())
def testAllowDeletions(self):
self.protected_branch.set_allow_deletions()
self.assertTrue(self.protected_branch.get_allow_deletions())
self.protected_branch.remove_allow_deletions()
self.assertFalse(self.protected_branch.get_allow_deletions())
def testAddUserPushRestrictions(self):
self.organization_branch.add_user_push_restrictions("sfdye")
self.assertListKeyEqual(
self.organization_branch.get_user_push_restrictions(),
lambda u: u.login,
["jacquev6", "sfdye"],
)
def testReplaceUserPushRestrictions(self):
self.assertListKeyEqual(
self.organization_branch.get_user_push_restrictions(),
lambda u: u.login,
["jacquev6"],
)
self.organization_branch.replace_user_push_restrictions("sfdye")
self.assertListKeyEqual(
self.organization_branch.get_user_push_restrictions(),
lambda u: u.login,
["sfdye"],
)
def testRemoveUserPushRestrictions(self):
self.organization_branch.remove_user_push_restrictions("jacquev6")
self.assertListKeyEqual(
self.organization_branch.get_user_push_restrictions(),
lambda u: u.login,
["sfdye"],
)
def testAddTeamPushRestrictions(self):
self.organization_branch.add_team_push_restrictions("pygithub-owners")
self.assertListKeyEqual(
self.organization_branch.get_team_push_restrictions(),
lambda t: t.slug,
["pygithub-owners"],
)
def testReplaceTeamPushRestrictions(self):
self.assertListKeyEqual(
self.organization_branch.get_team_push_restrictions(),
lambda t: t.slug,
["pygithub-owners"],
)
self.organization_branch.replace_team_push_restrictions("org-team")
self.assertListKeyEqual(
self.organization_branch.get_team_push_restrictions(),
lambda t: t.slug,
["org-team"],
)
def testRemoveTeamPushRestrictions(self):
self.organization_branch.remove_team_push_restrictions("org-team")
self.assertListKeyEqual(
self.organization_branch.get_team_push_restrictions(),
lambda t: t.slug,
["pygithub-owners"],
)
def testRemovePushRestrictions(self):
self.organization_branch.remove_push_restrictions()
with self.assertRaises(github.GithubException) as raisedexp:
list(self.organization_branch.get_user_push_restrictions())
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://developer.github.com/v3/repos/branches/#list-team-restrictions-of-protected-branch",
"message": "Push restrictions not enabled",
},
)
def testGetRequiredSignatures(self):
required_signature = self.protected_branch.get_required_signatures()
assert required_signature
def testRemoveRequiredSignatures(self):
self.protected_branch.remove_required_signatures()
def testAddRequiredSignatures(self):
self.protected_branch.add_required_signatures()
| 15,064
|
Python
|
.py
| 271
| 46.571956
| 146
| 0.636708
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,602
|
PoolSize.py
|
PyGithub_PyGithub/tests/PoolSize.py
|
############################ Copyrights and license ############################
# #
# Copyright 2021 Amador Pahim <apahim@redhat.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import github
from . import Framework
REPO_NAME = "PyGithub/PyGithub"
class PoolSize(Framework.TestCase):
def setUp(self):
Framework.setPoolSize(20)
super().setUp()
def testReturnsRepoAfterSettingPoolSize(self):
repository = self.g.get_repo(REPO_NAME)
self.assertIsInstance(repository, github.Repository.Repository)
self.assertEqual(repository.full_name, REPO_NAME)
def testReturnsRepoAfterSettingPoolSizeHttp(self):
g = github.Github(
auth=self.login,
base_url="http://my.enterprise.com",
pool_size=20,
)
repository = g.get_repo(REPO_NAME)
self.assertIsInstance(repository, github.Repository.Repository)
self.assertEqual(repository.full_name, REPO_NAME)
| 2,572
|
Python
|
.py
| 42
| 57.02381
| 80
| 0.466904
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,603
|
GithubObject.py
|
PyGithub_PyGithub/tests/GithubObject.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Christoph Reiter <reiter.christoph@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Nicolas Schweitzer <nicolas.schweitzer@datadoghq.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import unittest
from datetime import datetime, timedelta, timezone
from . import Framework
gho = Framework.github.GithubObject
class GithubObject(unittest.TestCase):
def testMakeDatetimeAttribute(self):
for value, expected in [
(None, None),
(
"2021-01-23T12:34:56Z",
datetime(2021, 1, 23, 12, 34, 56, tzinfo=timezone.utc),
),
(
"2021-01-23T12:34:56+00:00",
datetime(2021, 1, 23, 12, 34, 56, tzinfo=timezone.utc),
),
(
"2021-01-23T12:34:56+01:00",
datetime(2021, 1, 23, 12, 34, 56, tzinfo=timezone(timedelta(hours=1))),
),
(
"2021-01-23T12:34:56-06:30",
datetime(
2021,
1,
23,
12,
34,
56,
tzinfo=timezone(timedelta(hours=-6, minutes=-30)),
),
),
]:
actual = gho.GithubObject._makeDatetimeAttribute(value)
self.assertEqual(gho._ValuedAttribute, type(actual), value)
self.assertEqual(expected, actual.value, value)
def testMakeHttpDatetimeAttribute(self):
for value, expected in [
(None, None),
# https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1
(
"Mon, 11 Sep 2023 14:07:29 GMT",
datetime(2023, 9, 11, 14, 7, 29, tzinfo=timezone.utc),
),
# obsolete formats:
(
"Monday, 11-Sep-23 14:07:29 GMT",
datetime(2023, 9, 11, 14, 7, 29, tzinfo=timezone.utc),
),
(
"Mon Sep 11 14:07:29 2023",
datetime(2023, 9, 11, 14, 7, 29, tzinfo=timezone.utc),
),
]:
actual = gho.GithubObject._makeHttpDatetimeAttribute(value)
self.assertEqual(gho._ValuedAttribute, type(actual), value)
self.assertEqual(expected, actual.value, value)
def testMakeHttpDatetimeAttributeBadValues(self):
for value in ["not a timestamp", 1234]:
actual = gho.GithubObject._makeHttpDatetimeAttribute(value)
with self.assertRaises(Framework.github.BadAttributeException):
actual.value
def testMakeDatetimeAttributeBadValues(self):
for value in ["not a timestamp", 1234]:
actual = gho.GithubObject._makeDatetimeAttribute(value)
self.assertEqual(gho._BadAttribute, type(actual))
with self.assertRaises(Framework.github.BadAttributeException) as e:
value = actual.value
self.assertEqual(value, e.exception.actual_value)
self.assertEqual(str, e.exception.expected_type)
if isinstance(value, str):
self.assertIsNotNone(e.exception.transformation_exception)
else:
self.assertIsNone(e.exception.transformation_exception)
def testMakeTimestampAttribute(self):
actual = gho.GithubObject._makeTimestampAttribute(None)
self.assertEqual(gho._ValuedAttribute, type(actual))
self.assertIsNone(actual.value)
actual = gho.GithubObject._makeTimestampAttribute(1611405296)
self.assertEqual(gho._ValuedAttribute, type(actual))
self.assertEqual(datetime(2021, 1, 23, 12, 34, 56, tzinfo=timezone.utc), actual.value)
def testMakeTimetsampAttributeBadValues(self):
for value in ["1611405296", 1234.567]:
actual = gho.GithubObject._makeTimestampAttribute(value)
self.assertEqual(gho._BadAttribute, type(actual))
with self.assertRaises(Framework.github.BadAttributeException) as e:
value = actual.value
self.assertEqual(value, e.exception.actual_value)
self.assertEqual(int, e.exception.expected_type)
self.assertIsNone(e.exception.transformation_exception)
| 6,012
|
Python
|
.py
| 114
| 42.359649
| 94
| 0.526763
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,604
|
NamedUser.py
|
PyGithub_PyGithub/tests/NamedUser.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Bruce Richardson <itsbruce@workshy.org> #
# Copyright 2018 Riccardo Pittau <elfosardo@users.noreply.github.com> #
# Copyright 2018 namc <namratachaudhary@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Surya Teja <94suryateja@gmail.com> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Daniel Haas <thisisdhaas@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from datetime import datetime, timezone
from . import Framework
class NamedUser(Framework.TestCase):
def setUp(self):
super().setUp()
self.user = self.g.get_user("jacquev6")
def testAttributesOfOtherUser(self):
self.user = self.g.get_user("nvie")
self.assertEqual(
self.user.avatar_url,
"https://secure.gravatar.com/avatar/c5a7f21b46df698f3db31c37ed0cf55a?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
)
self.assertEqual(self.user.bio, None)
self.assertEqual(self.user.blog, "http://nvie.com")
self.assertEqual(self.user.collaborators, None)
self.assertEqual(self.user.company, "3rd Cloud")
self.assertEqual(
self.user.created_at,
datetime(2009, 5, 12, 21, 19, 38, tzinfo=timezone.utc),
)
self.assertEqual(self.user.disk_usage, None)
self.assertEqual(self.user.email, "vincent@3rdcloud.com")
self.assertEqual(self.user.followers, 296)
self.assertEqual(self.user.following, 41)
self.assertEqual(self.user.gravatar_id, "c5a7f21b46df698f3db31c37ed0cf55a")
self.assertFalse(self.user.hireable)
self.assertEqual(self.user.html_url, "https://github.com/nvie")
self.assertEqual(self.user.id, 83844)
self.assertEqual(self.user.location, "Netherlands")
self.assertEqual(self.user.login, "nvie")
self.assertEqual(self.user.name, "Vincent Driessen")
self.assertEqual(self.user.owned_private_repos, None)
self.assertEqual(self.user.plan, None)
self.assertEqual(self.user.private_gists, None)
self.assertEqual(self.user.public_gists, 16)
self.assertEqual(self.user.public_repos, 61)
self.assertEqual(self.user.suspended_at, None)
self.assertEqual(self.user.total_private_repos, None)
self.assertEqual(self.user.twitter_username, "nvie")
self.assertEqual(self.user.type, "User")
self.assertEqual(self.user.url, "https://api.github.com/users/nvie")
self.assertEqual(self.user.node_id, "MDQ6VXNlcjgzODQ0")
self.assertEqual(repr(self.user), 'NamedUser(login="nvie")')
def testAttributesOfSelf(self):
self.assertEqual(
self.user.avatar_url,
"https://secure.gravatar.com/avatar/b68de5ae38616c296fa345d2b9df2225?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
)
self.assertEqual(self.user.bio, "")
self.assertEqual(self.user.blog, "http://vincent-jacques.net")
self.assertEqual(self.user.collaborators, 0)
self.assertEqual(self.user.company, "Criteo")
self.assertEqual(
self.user.created_at,
datetime(2010, 7, 9, 6, 10, 6, tzinfo=timezone.utc),
)
self.assertEqual(self.user.disk_usage, 17080)
self.assertEqual(self.user.email, "vincent@vincent-jacques.net")
self.assertEqual(self.user.followers, 13)
self.assertEqual(self.user.following, 24)
self.assertEqual(self.user.gravatar_id, "b68de5ae38616c296fa345d2b9df2225")
self.assertFalse(self.user.hireable)
self.assertEqual(self.user.html_url, "https://github.com/jacquev6")
self.assertEqual(self.user.id, 327146)
self.assertEqual(self.user.location, "Paris, France")
self.assertEqual(self.user.login, "jacquev6")
self.assertEqual(self.user.name, "Vincent Jacques")
self.assertEqual(self.user.owned_private_repos, 5)
self.assertEqual(self.user.plan.name, "micro")
self.assertEqual(self.user.plan.collaborators, 1)
self.assertEqual(self.user.plan.space, 614400)
self.assertEqual(self.user.plan.private_repos, 5)
self.assertEqual(self.user.private_gists, 5)
self.assertEqual(self.user.public_gists, 2)
self.assertEqual(self.user.public_repos, 11)
self.assertEqual(
self.user.suspended_at,
datetime(2013, 8, 10, 7, 11, 7, tzinfo=timezone.utc),
)
self.assertEqual(self.user.total_private_repos, 5)
self.assertIsNone(self.user.twitter_username)
self.assertEqual(self.user.type, "User")
self.assertEqual(self.user.url, "https://api.github.com/users/jacquev6")
self.assertEqual(self.user.node_id, "MDQ6VXNlcjMyNzE0Ng==")
self.assertEqual(repr(self.user), 'NamedUser(login="jacquev6")')
self.assertEqual(repr(self.user.plan), 'Plan(name="micro")')
def testGetGists(self):
self.assertListKeyEqual(
self.user.get_gists(),
lambda g: g.description,
[
"Gist created by PyGithub",
"FairThreadPoolPool.cpp",
"How to error 500 Github API v3, as requested by Rick (GitHub Staff)",
"Cadfael: order of episodes in French DVD edition",
],
)
self.assertListKeyEqual(
self.user.get_gists(since=datetime(2012, 3, 1, 17, 0, 0)),
lambda g: g.description,
["Gist created by PyGithub", "FairThreadPoolPool.cpp"],
)
def testGetFollowers(self):
self.assertListKeyEqual(
self.user.get_followers(),
lambda f: f.login,
[
"jnorthrup",
"brugidou",
"regisb",
"walidk",
"afzalkhan",
"sdanzan",
"vineus",
"gturri",
"fjardon",
"cjuniet",
"jardon-u",
"kamaradclimber",
"L42y",
],
)
def testGetFollowing(self):
self.assertListKeyEqual(
self.user.get_following(),
lambda f: f.login,
[
"nvie",
"schacon",
"jamis",
"chad",
"unclebob",
"dabrahams",
"jnorthrup",
"brugidou",
"regisb",
"walidk",
"tanzilli",
"fjardon",
"r3c",
"sdanzan",
"vineus",
"cjuniet",
"gturri",
"ant9000",
"asquini",
"claudyus",
"jardon-u",
"s-bernard",
"kamaradclimber",
"Lyloa",
],
)
def testHasInFollowing(self):
nvie = self.g.get_user("nvie")
self.assertTrue(self.user.has_in_following(nvie))
def testGetOrgs(self):
self.assertListKeyEqual(self.user.get_orgs(), lambda o: o.login, ["BeaverSoftware"])
def testGetOrganizationMembership(self):
o = self.user.get_orgs()
membership = self.user.get_organization_membership(o[0])
self.assertEqual(
repr(membership),
'Membership(url="https://api.github.com/orgs/BeaverSoftware/memberships/jacquev6")',
)
self.assertEqual(self.user.login, membership.user.login)
self.assertEqual(membership.state, "active")
self.assertEqual(membership.role, "member")
self.assertEqual(
membership.url,
"https://api.github.com/orgs/BeaverSoftware/memberships/jacquev6",
)
self.assertEqual(membership.organization.login, "BeaverSoftware")
self.assertEqual(membership.organization_url, "https://api.github.com/orgs/BeaverSoftware")
def testGetOrganizationMembershipNotMember(self):
from github import UnknownObjectException
self.assertRaises(
UnknownObjectException,
self.user.get_organization_membership,
"BeaverSoftware",
)
def testGetRepo(self):
self.assertEqual(
self.user.get_repo("PyGithub").description,
"Python library implementing the full Github API v3",
)
def testGetRepos(self):
self.assertListKeyEqual(
self.user.get_repos(),
lambda r: r.name,
[
"TestPyGithub",
"django",
"PyGithub",
"developer.github.com",
"acme-public-website",
"C4Planner",
"DrawTurksHead",
"DrawSyntax",
"QuadProgMm",
"Boost.HierarchicalEnum",
"ViDE",
],
)
def testGetReposWithAllArgs(self):
self.assertListKeyEqual(
self.user.get_repos(type="owner", sort="created", direction="asc"),
lambda r: r.name,
[
"DrawTurksHead",
"vincent-jacques.net",
"IpMap",
"MockMockMock",
"ActionTree",
"InteractiveCommandLine",
"RecursiveDocument",
"MarblesCollide",
"jacquev6.github.io",
"LowVoltage",
],
)
def testGetWatched(self):
self.assertListKeyEqual(
self.user.get_watched(),
lambda r: r.name,
[
"git",
"boost.php",
"capistrano",
"boost.perl",
"git-subtree",
"git-hg",
"homebrew",
"celtic_knot",
"twisted-intro",
"markup",
"hub",
"gitflow",
"murder",
"boto",
"agit",
"d3",
"pygit2",
"git-pulls",
"django_mathlatex",
"scrumblr",
"developer.github.com",
"python-github3",
"PlantUML",
"bootstrap",
"drawnby",
"django-socketio",
"django-realtime",
"playground",
"BozoCrack",
"FatherBeaver",
"PyGithub",
"django",
"django",
"TestPyGithub",
],
)
def testGetStarred(self):
self.assertListKeyEqual(
self.user.get_starred(),
lambda r: r.name,
[
"git",
"boost.php",
"capistrano",
"boost.perl",
"git-subtree",
"git-hg",
"homebrew",
"celtic_knot",
"twisted-intro",
"markup",
"hub",
"gitflow",
"murder",
"boto",
"agit",
"d3",
"pygit2",
"git-pulls",
"django_mathlatex",
"scrumblr",
"developer.github.com",
"python-github3",
"PlantUML",
"bootstrap",
"drawnby",
"django-socketio",
"django-realtime",
"playground",
"BozoCrack",
"FatherBeaver",
"amaunet",
"django",
"django",
"moviePlanning",
"folly",
],
)
def testGetSubscriptions(self):
self.assertListKeyEqual(
self.user.get_subscriptions(),
lambda r: r.name,
[
"ViDE",
"Boost.HierarchicalEnum",
"QuadProgMm",
"DrawSyntax",
"DrawTurksHead",
"PrivateStuff",
"vincent-jacques.net",
"Hacking",
"C4Planner",
"developer.github.com",
"PyGithub",
"PyGithub",
"django",
"CinePlanning",
"PyGithub",
"PyGithub",
"PyGithub",
"IpMap",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
],
)
def testGetEvents(self):
self.assertListKeyBegin(
self.user.get_events(),
lambda e: e.type,
["GistEvent", "IssueCommentEvent", "PushEvent", "IssuesEvent"],
)
def testGetPublicEvents(self):
self.assertListKeyBegin(
self.user.get_public_events(),
lambda e: e.type,
["PushEvent", "CreateEvent", "GistEvent", "IssuesEvent"],
)
def testGetPublicReceivedEvents(self):
self.assertListKeyBegin(
self.user.get_public_received_events(),
lambda e: e.type,
[
"IssueCommentEvent",
"IssueCommentEvent",
"IssueCommentEvent",
"IssueCommentEvent",
],
)
def testGetReceivedEvents(self):
self.assertListKeyBegin(
self.user.get_received_events(),
lambda e: e.type,
[
"IssueCommentEvent",
"IssueCommentEvent",
"IssueCommentEvent",
"IssueCommentEvent",
],
)
def testGetKeys(self):
self.assertListKeyEqual(
self.user.get_keys(),
lambda k: k.id,
[3557894, 3791954, 3937333, 4051357, 4051492],
)
def testUserEquality(self):
u1 = self.g.get_user("nvie")
u2 = self.g.get_user("nvie")
self.assertTrue(u1 == u2)
self.assertEqual(u1, u2)
self.assertEqual(u1.__hash__(), u2.__hash__())
| 17,209
|
Python
|
.py
| 426
| 28.49061
| 168
| 0.508444
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,605
|
PullRequest2408.py
|
PyGithub_PyGithub/tests/PullRequest2408.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Matthew Neal <meneal@matthews-mbp.raleigh.ibm.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 Sam Corbett <sam.corbett@cloudsoftcorp.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Olof-Joachim Frahm (欧雅福) <olof@macrolet.net> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Anuj Bansal <bansalanuj1996@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Mikhail f. Shiryaev <mr.felixoid@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class PullRequest2408(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("ReDASers/Phishing-Detection")
def test_get_workflow_runs(self):
runs = self.repo.get_workflow_runs(head_sha="7aab33f4294ba5141f17bed0aeb1a929f7afc155")
self.assertEqual(720994709, runs[0].id)
runs = self.repo.get_workflow_runs(exclude_pull_requests=True)
self.assertEqual(3519037359, runs[0].id)
| 3,575
|
Python
|
.py
| 48
| 72.083333
| 95
| 0.500284
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,606
|
Reaction.py
|
PyGithub_PyGithub/tests/Reaction.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Nicolas Agustín Torres <nicolastrres@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from datetime import datetime, timezone
from . import Framework
class Reaction(Framework.TestCase):
def setUp(self):
super().setUp()
self.reactions = self.g.get_user("PyGithub").get_repo("PyGithub").get_issue(28).get_reactions()
def testAttributes(self):
self.assertEqual(self.reactions[0].content, "+1")
self.assertEqual(
self.reactions[0].created_at,
datetime(2017, 12, 5, 1, 59, 33, tzinfo=timezone.utc),
)
self.assertEqual(self.reactions[0].id, 16916340)
self.assertEqual(self.reactions[0].user.login, "nicolastrres")
self.assertEqual(
self.reactions[0].__repr__(),
'Reaction(user=NamedUser(login="nicolastrres"), id=16916340)',
)
def testDelete(self):
self.reactions[0].delete()
| 3,591
|
Python
|
.py
| 54
| 62.777778
| 103
| 0.493768
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,607
|
CheckSuite.py
|
PyGithub_PyGithub/tests/CheckSuite.py
|
############################ Copyrights and license ############################
# #
# Copyright 2020 Dhruv Manilawala <dhruvmanila@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from datetime import datetime, timezone
from . import Framework
class CheckSuite(Framework.TestCase):
def setUp(self):
super().setUp()
self.check_suite_id = 1004503837
self.test_check_suite_id = 1366665055
self.test_repo = self.g.get_repo("dhruvmanila/pygithub-testing")
self.test_check_suite = self.test_repo.get_check_suite(self.test_check_suite_id)
self.repo = self.g.get_repo("wrecker/PySample")
self.check_suite = self.repo.get_check_suite(self.check_suite_id)
self.check_suite_ref = "fd09d934bcce792176d6b79d6d0387e938b62b7a"
self.commit = self.repo.get_commit("fd09d934bcce792176d6b79d6d0387e938b62b7a")
def testAttributes(self):
cs = self.check_suite
self.assertEqual(cs.after, "fd09d934bcce792176d6b79d6d0387e938b62b7a")
self.assertEqual(cs.app.slug, "github-actions")
self.assertEqual(cs.before, "9ee0caba8648aa0b8b5fc68ebc37c3c1162aa283")
self.assertEqual(
cs.check_runs_url,
"https://api.github.com/repos/wrecker/PySample/check-suites/1004503837/check-runs",
)
self.assertEqual(cs.conclusion, "success")
self.assertEqual(cs.created_at, datetime(2020, 8, 4, 5, 6, 54, tzinfo=timezone.utc))
self.assertEqual(cs.head_branch, "wrecker-patch-1")
self.assertEqual(cs.head_commit.sha, "fd09d934bcce792176d6b79d6d0387e938b62b7a")
self.assertEqual(cs.head_sha, "fd09d934bcce792176d6b79d6d0387e938b62b7a")
self.assertEqual(cs.id, self.check_suite_id)
self.assertEqual(cs.latest_check_runs_count, 2)
self.assertEqual(cs.id, self.check_suite_id)
self.assertEqual(len(cs.pull_requests), 1)
self.assertEqual(cs.pull_requests[0].id, 462527907)
self.assertEqual(cs.repository.url, "https://api.github.com/repos/wrecker/PySample")
self.assertEqual(cs.status, "completed")
self.assertEqual(cs.updated_at, datetime(2020, 8, 4, 5, 7, 40, tzinfo=timezone.utc))
self.assertEqual(
cs.url,
"https://api.github.com/repos/wrecker/PySample/check-suites/1004503837",
)
def testGetCheckSuitesForRef(self):
check_suites = self.commit.get_check_suites()
self.assertEqual(check_suites.totalCount, 6)
self.assertListEqual(
[cs.id for cs in check_suites],
[1004503392, 1004503393, 1004503395, 1004503397, 1004503837, 1004503857],
)
def testGetCheckSuitesForRefFilterByAppId(self):
check_suites = self.commit.get_check_suites(app_id=29110)
self.assertEqual(check_suites.totalCount, 1)
self.assertListEqual([cs.id for cs in check_suites], [1004503392])
def testGetCheckSuitesForRefFilterByCheckName(self):
check_suites = self.commit.get_check_suites(check_name="Alex")
self.assertEqual(check_suites.totalCount, 1)
self.assertListEqual([cs.id for cs in check_suites], [1004503395])
def testCheckSuiteRerequest(self):
cs = self.repo.get_check_suite(1004503395)
status = cs.rerequest()
self.assertTrue(status)
def testGetCheckRuns(self):
check_runs = self.test_check_suite.get_check_runs()
self.assertEqual(check_runs.totalCount, 8)
self.assertListEqual(
[cr.id for cr in check_runs],
[
1278952206,
1279259090,
1280450752,
1280914700,
1296027873,
1296028076,
1296029378,
1296029552,
],
)
def testGetCheckRunsFilterByCheckName(self):
check_runs = self.test_check_suite.get_check_runs(check_name="Testing")
self.assertEqual(check_runs.totalCount, 1)
self.assertEqual([cr.id for cr in check_runs], [1278952206])
def testGetCheckRunsFilterByStatus(self):
check_runs = self.test_check_suite.get_check_runs(status="completed")
self.assertEqual(check_runs.totalCount, 8)
self.assertListEqual(
[cr.id for cr in check_runs],
[
1278952206,
1279259090,
1280450752,
1280914700,
1296027873,
1296028076,
1296029378,
1296029552,
],
)
def testGetCheckRunsFilterByFilter(self):
check_runs = self.test_check_suite.get_check_runs(filter="all")
self.assertEqual(check_runs.totalCount, 8)
self.assertListEqual(
[cr.id for cr in check_runs],
[
1278952206,
1279259090,
1280450752,
1280914700,
1296027873,
1296028076,
1296029378,
1296029552,
],
)
def testCreateCheckSuite(self):
sha = "e5868bd5a9ccdd65c9c979250e11105f4c88faf4"
check_suite = self.test_repo.create_check_suite(head_sha=sha)
self.assertEqual(check_suite.head_sha, sha)
self.assertEqual(check_suite.status, "queued")
self.assertIsNone(check_suite.conclusion)
def testUpdateCheckSuitesPreferences(self):
data = [{"app_id": 85429, "setting": False}]
repo_preferences = self.test_repo.update_check_suites_preferences(data)
setting = None
for app in repo_preferences.preferences["auto_trigger_checks"]:
if app["app_id"] == data[0]["app_id"]:
setting = app["setting"]
self.assertFalse(setting)
self.assertEqual(repo_preferences.repository.full_name, "dhruvmanila/pygithub-testing")
data = [{"app_id": 85429, "setting": True}]
repo_preferences = self.test_repo.update_check_suites_preferences(data)
for app in repo_preferences.preferences["auto_trigger_checks"]:
if app["app_id"] == data[0]["app_id"]:
setting = app["setting"]
self.assertTrue(setting)
| 7,970
|
Python
|
.py
| 155
| 42.245161
| 95
| 0.577949
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,608
|
Issue214.py
|
PyGithub_PyGithub/tests/Issue214.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 David Farr <david.farr@sap.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class Issue214(Framework.TestCase): # https://github.com/jacquev6/PyGithub/issues/214
def setUp(self):
super().setUp()
self.repo = self.g.get_user().get_repo("PyGithub")
self.issue = self.repo.get_issue(1)
def testAssignees(self):
self.assertTrue(self.repo.has_in_assignees("farrd"))
self.assertFalse(self.repo.has_in_assignees("fake"))
def testCollaborators(self):
self.assertTrue(self.repo.has_in_collaborators("farrd"))
self.assertFalse(self.repo.has_in_collaborators("fake"))
self.assertFalse(self.repo.has_in_collaborators("marcmenges"))
self.repo.add_to_collaborators("marcmenges")
self.assertTrue(self.repo.has_in_collaborators("marcmenges"))
self.repo.remove_from_collaborators("marcmenges")
self.assertFalse(self.repo.has_in_collaborators("marcmenges"))
def testEditIssue(self):
self.assertEqual(self.issue.assignee, None)
self.issue.edit(assignee="farrd")
self.assertEqual(self.issue.assignee.login, "farrd")
self.issue.edit(assignee=None)
self.assertEqual(self.issue.assignee, None)
def testCreateIssue(self):
issue = self.repo.create_issue("Issue created by PyGithub", assignee="farrd")
self.assertEqual(issue.assignee.login, "farrd")
def testGetIssues(self):
issues = self.repo.get_issues(assignee="farrd")
for issue in issues:
self.assertEqual(issue.assignee.login, "farrd")
| 4,128
|
Python
|
.py
| 62
| 62.080645
| 86
| 0.530225
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,609
|
AuthenticatedUser.py
|
PyGithub_PyGithub/tests/AuthenticatedUser.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Balázs Rostás <rostas.balazs@gmail.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2018 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2018 Bruce Richardson <itsbruce@workshy.org> #
# Copyright 2018 Jacopo Notarstefano <jacopo.notarstefano@gmail.com> #
# Copyright 2018 Riccardo Pittau <elfosardo@users.noreply.github.com> #
# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Surya Teja <94suryateja@gmail.com> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Anuj Bansal <bansalanuj1996@gmail.com> #
# Copyright 2020 Glenn McDonald <testworksau@users.noreply.github.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 MeggyCal <MeggyCal@users.noreply.github.com> #
# Copyright 2021 秋葉 <ambiguous404@gmail.com> #
# Copyright 2022 KimSia Sim <245021+simkimsia@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Chris Wells <ping@cwlls.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com>#
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from datetime import datetime, timezone
import github
from . import Framework
class AuthenticatedUser(Framework.TestCase):
def setUp(self):
super().setUp()
self.user = self.g.get_user()
def testAttributes(self):
self.assertEqual(
self.user.avatar_url,
"https://secure.gravatar.com/avatar/b68de5ae38616c296fa345d2b9df2225?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
)
self.assertEqual(self.user.bio, "")
self.assertEqual(self.user.blog, "http://vincent-jacques.net")
self.assertEqual(self.user.collaborators, 0)
self.assertEqual(self.user.company, "Criteo")
self.assertEqual(
self.user.created_at,
datetime(2010, 7, 9, 6, 10, 6, tzinfo=timezone.utc),
)
self.assertEqual(self.user.disk_usage, 16692)
self.assertEqual(self.user.email, "vincent@vincent-jacques.net")
self.assertEqual(self.user.followers, 13)
self.assertEqual(self.user.following, 24)
self.assertEqual(self.user.gravatar_id, "b68de5ae38616c296fa345d2b9df2225")
self.assertFalse(self.user.hireable)
self.assertEqual(self.user.html_url, "https://github.com/jacquev6")
self.assertEqual(self.user.id, 327146)
self.assertEqual(self.user.location, "Paris, France")
self.assertEqual(self.user.login, "jacquev6")
self.assertEqual(self.user.name, "Vincent Jacques")
self.assertEqual(self.user.owned_private_repos, 5)
self.assertEqual(self.user.plan.name, "micro")
self.assertEqual(self.user.plan.collaborators, 1)
self.assertEqual(self.user.plan.space, 614400)
self.assertEqual(self.user.plan.private_repos, 5)
self.assertEqual(self.user.private_gists, 5)
self.assertEqual(self.user.public_gists, 1)
self.assertEqual(self.user.public_repos, 10)
self.assertEqual(self.user.total_private_repos, 5)
self.assertEqual(self.user.type, "User")
self.assertEqual(self.user.url, "https://api.github.com/users/jacquev6")
self.assertEqual(self.user.node_id, "MDQ6VXNlcjMyNzE0Ng==")
self.assertEqual(repr(self.user), 'AuthenticatedUser(login="jacquev6")')
self.assertTrue(self.user.two_factor_authentication)
def testEditWithoutArguments(self):
self.user.edit()
def testEditWithAllArguments(self):
self.user.edit(
"Name edited by PyGithub",
"Email edited by PyGithub",
"Blog edited by PyGithub",
"Company edited by PyGithub",
"Location edited by PyGithub",
True,
"Bio edited by PyGithub",
)
self.assertEqual(self.user.name, "Name edited by PyGithub")
self.assertEqual(self.user.email, "Email edited by PyGithub")
self.assertEqual(self.user.blog, "Blog edited by PyGithub")
self.assertEqual(self.user.company, "Company edited by PyGithub")
self.assertEqual(self.user.location, "Location edited by PyGithub")
self.assertTrue(self.user.hireable)
self.assertEqual(self.user.bio, "Bio edited by PyGithub")
def testEmails(self):
emails = self.user.get_emails()
self.assertEqual(
[item.email for item in emails],
["vincent@vincent-jacques.net", "github.com@vincent-jacques.net"],
)
self.assertTrue(emails[0].primary)
self.assertTrue(emails[0].verified)
self.assertEqual(emails[0].visibility, "private")
self.user.add_to_emails("1@foobar.com", "2@foobar.com")
self.assertEqual(
[item.email for item in self.user.get_emails()],
[
"vincent@vincent-jacques.net",
"1@foobar.com",
"2@foobar.com",
"github.com@vincent-jacques.net",
],
)
self.user.remove_from_emails("1@foobar.com", "2@foobar.com")
self.assertEqual(
[item.email for item in self.user.get_emails()],
["vincent@vincent-jacques.net", "github.com@vincent-jacques.net"],
)
def testFollowing(self):
nvie = self.g.get_user("nvie")
self.assertListKeyEqual(
self.user.get_following(),
lambda u: u.login,
[
"schacon",
"jamis",
"chad",
"unclebob",
"dabrahams",
"jnorthrup",
"brugidou",
"regisb",
"walidk",
"tanzilli",
"fjardon",
"r3c",
"sdanzan",
"vineus",
"cjuniet",
"gturri",
"ant9000",
"asquini",
"claudyus",
"jardon-u",
"s-bernard",
"kamaradclimber",
"Lyloa",
"nvie",
],
)
self.assertTrue(self.user.has_in_following(nvie))
self.user.remove_from_following(nvie)
self.assertFalse(self.user.has_in_following(nvie))
self.user.add_to_following(nvie)
self.assertTrue(self.user.has_in_following(nvie))
self.assertListKeyEqual(
self.user.get_followers(),
lambda u: u.login,
[
"jnorthrup",
"brugidou",
"regisb",
"walidk",
"afzalkhan",
"sdanzan",
"vineus",
"gturri",
"fjardon",
"cjuniet",
"jardon-u",
"kamaradclimber",
"L42y",
],
)
def testWatching(self):
gitflow = self.g.get_user("nvie").get_repo("gitflow")
self.assertListKeyEqual(
self.user.get_watched(),
lambda r: r.name,
[
"git",
"boost.php",
"capistrano",
"boost.perl",
"git-subtree",
"git-hg",
"homebrew",
"celtic_knot",
"twisted-intro",
"markup",
"hub",
"gitflow",
"murder",
"boto",
"agit",
"d3",
"pygit2",
"git-pulls",
"django_mathlatex",
"scrumblr",
"developer.github.com",
"python-github3",
"PlantUML",
"bootstrap",
"drawnby",
"django-socketio",
"django-realtime",
"playground",
"BozoCrack",
"FatherBeaver",
"PyGithub",
"django",
"django",
"TestPyGithub",
],
)
self.assertTrue(self.user.has_in_watched(gitflow))
self.user.remove_from_watched(gitflow)
self.assertFalse(self.user.has_in_watched(gitflow))
self.user.add_to_watched(gitflow)
self.assertTrue(self.user.has_in_watched(gitflow))
def testStarring(self):
gitflow = self.g.get_user("nvie").get_repo("gitflow")
self.assertListKeyEqual(
self.user.get_starred(),
lambda r: r.name,
[
"git",
"boost.php",
"capistrano",
"boost.perl",
"git-subtree",
"git-hg",
"homebrew",
"celtic_knot",
"twisted-intro",
"markup",
"hub",
"gitflow",
"murder",
"boto",
"agit",
"d3",
"pygit2",
"git-pulls",
"django_mathlatex",
"scrumblr",
"developer.github.com",
"python-github3",
"PlantUML",
"bootstrap",
"drawnby",
"django-socketio",
"django-realtime",
"playground",
"BozoCrack",
"FatherBeaver",
"amaunet",
"django",
"django",
"moviePlanning",
"folly",
],
)
self.assertTrue(self.user.has_in_starred(gitflow))
self.user.remove_from_starred(gitflow)
self.assertFalse(self.user.has_in_starred(gitflow))
self.user.add_to_starred(gitflow)
self.assertTrue(self.user.has_in_starred(gitflow))
def testSubscriptions(self):
gitflow = self.g.get_user("nvie").get_repo("gitflow")
self.assertListKeyEqual(
self.user.get_subscriptions(),
lambda r: r.name,
[
"gitflow",
"ViDE",
"Boost.HierarchicalEnum",
"QuadProgMm",
"DrawSyntax",
"DrawTurksHead",
"PrivateStuff",
"vincent-jacques.net",
"Hacking",
"C4Planner",
"developer.github.com",
"PyGithub",
"PyGithub",
"django",
"CinePlanning",
"PyGithub",
"PyGithub",
"PyGithub",
"IpMap",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
"PyGithub",
],
)
self.assertTrue(self.user.has_in_subscriptions(gitflow))
self.user.remove_from_subscriptions(gitflow)
self.assertFalse(self.user.has_in_subscriptions(gitflow))
self.user.add_to_subscriptions(gitflow)
self.assertTrue(self.user.has_in_subscriptions(gitflow))
def testGetAuthorizations(self):
self.assertListKeyEqual(self.user.get_authorizations(), lambda a: a.id, [372294])
def testCreateRepository(self):
repo = self.user.create_repo(name="TestPyGithub")
self.assertEqual(repo.url, "https://api.github.com/repos/jacquev6/TestPyGithub")
def testCreateProject(self):
project = self.user.create_project(name="TestPyGithub", body="This is the body")
self.assertEqual(project.url, "https://api.github.com/projects/4084610")
def testCreateRepositoryWithAllArguments(self):
repo = self.user.create_repo(
name="TestPyGithub",
description="Repo created by PyGithub",
homepage="http://foobar.com",
private=False,
has_issues=False,
has_projects=False,
has_wiki=False,
has_discussions=False,
has_downloads=False,
allow_squash_merge=False,
allow_merge_commit=False,
allow_rebase_merge=True,
delete_branch_on_merge=False,
)
self.assertEqual(repo.url, "https://api.github.com/repos/jacquev6/TestPyGithub")
def testCreateRepositoryWithAutoInit(self):
repo = self.user.create_repo(name="TestPyGithub", auto_init=True, gitignore_template="Python")
self.assertEqual(repo.url, "https://api.github.com/repos/jacquev6/TestPyGithub")
def testCreateAuthorizationWithoutArguments(self):
authorization = self.user.create_authorization()
self.assertEqual(authorization.id, 372259)
def testCreateAuthorizationWithAllArguments(self):
authorization = self.user.create_authorization(
["repo"], "Note created by PyGithub", "http://vincent-jacques.net/PyGithub"
)
self.assertEqual(authorization.id, 372294)
def testCreateAuthorizationWithClientIdAndSecret(self):
# I don't have a client_id and client_secret so the ReplayData for this test is forged
authorization = self.user.create_authorization(
client_id="01234567890123456789",
client_secret="0123456789012345678901234567890123456789",
)
self.assertEqual(authorization.id, 372294)
def testCreateGist(self):
gist = self.user.create_gist(
True,
{"foobar.txt": github.InputFileContent("File created by PyGithub")},
"Gist created by PyGithub",
)
self.assertEqual(gist.description, "Gist created by PyGithub")
self.assertEqual(list(gist.files.keys()), ["foobar.txt"])
self.assertEqual(gist.files["foobar.txt"].content, "File created by PyGithub")
def testCreateGistWithoutDescription(self):
gist = self.user.create_gist(True, {"foobar.txt": github.InputFileContent("File created by PyGithub")})
self.assertEqual(gist.description, None)
self.assertEqual(list(gist.files.keys()), ["foobar.txt"])
self.assertEqual(gist.files["foobar.txt"].content, "File created by PyGithub")
def testCreateKey(self):
key = self.user.create_key(
"Key added through PyGithub",
"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA2Mm0RjTNAYFfSCtUpO54usdseroUSIYg5KX4JoseTpqyiB/hqewjYLAdUq/tNIQzrkoEJWSyZrQt0ma7/YCyMYuNGd3DU6q6ZAyBeY3E9RyCiKjO3aTL2VKQGFvBVVmGdxGVSCITRphAcsKc/PF35/fg9XP9S0anMXcEFtdfMHz41SSw+XtE+Vc+6cX9FuI5qUfLGbkv8L1v3g4uw9VXlzq4GfTA+1S7D6mcoGHopAIXFlVr+2RfDKdSURMcB22z41fljO1MW4+zUS/4FyUTpL991es5fcwKXYoiE+x06VJeJJ1Krwx+DZj45uweV6cHXt2JwJEI9fWB6WyBlDejWw== vincent@IDEE",
)
self.assertEqual(key.id, 2626650)
def testGetEvents(self):
self.assertListKeyBegin(
self.user.get_events(),
lambda e: e.type,
["PushEvent", "IssuesEvent", "IssueCommentEvent", "PushEvent"],
)
def testGetOrganizationEvents(self):
self.assertListKeyBegin(
self.user.get_organization_events(self.g.get_organization("BeaverSoftware")),
lambda e: e.type,
["CreateEvent", "CreateEvent", "PushEvent", "PushEvent"],
)
def testGetGists(self):
self.assertListKeyEqual(
self.user.get_gists(),
lambda g: g.id,
[
"2793505",
"2793179",
"11cb445f8197e17d303d",
"1942384",
"dcb7de17e8a52b74541d",
],
)
self.assertListKeyEqual(
self.user.get_gists(since=datetime(2012, 3, 1, 23, 0, 0)),
lambda g: g.id,
["2793505", "2793179", "11cb445f8197e17d303d"],
)
def testGetStarredGists(self):
self.assertListKeyEqual(
self.user.get_starred_gists(),
lambda g: g.id,
["1942384", "dcb7de17e8a52b74541d"],
)
def testGetIssues(self):
self.assertListKeyEqual(
self.user.get_issues(),
lambda i: (i.id, i.repository.name),
[
(4639931, "PyGithub"),
(4452000, "PyGithub"),
(4356743, "PyGithub"),
(3716033, "PyGithub"),
(3715946, "PyGithub"),
(3643837, "PyGithub"),
(3628022, "PyGithub"),
(3624595, "PyGithub"),
(3624570, "PyGithub"),
(3624561, "PyGithub"),
(3624556, "PyGithub"),
(3619973, "PyGithub"),
(3527266, "PyGithub"),
(3527245, "PyGithub"),
(3527231, "PyGithub"),
],
)
def testGetIssuesWithAllArguments(self):
requestedByUser = self.user.get_repo("PyGithub").get_label("Requested by user")
issues = self.user.get_issues(
"assigned",
"closed",
[requestedByUser],
"comments",
"asc",
datetime(2012, 5, 28, 23, 0, 0),
)
self.assertListKeyEqual(
issues,
lambda i: i.id,
[
6816576,
8495415,
6889934,
8339699,
8075253,
8033963,
9089893,
9489725,
11746141,
5152384,
5177381,
5783131,
6454054,
6641076,
6653907,
7331214,
9489813,
9776615,
10360280,
4356743,
6583381,
6751469,
8189836,
10758585,
12097154,
12867103,
5191621,
5256315,
6363719,
9209408,
6912733,
9948505,
11503771,
10922412,
11844658,
12566144,
6353712,
9323084,
10379143,
5387373,
12179668,
6911794,
11731917,
6807542,
6780606,
],
)
def testGetUserIssues(self):
self.assertListKeyEqual(
self.user.get_user_issues(),
lambda i: i.id,
[
14447880,
13505356,
12541184,
10586808,
6741461,
6741457,
6727331,
5641572,
],
)
def testGetUserIssuesWithAllArguments(self):
requestedByUser = self.user.get_repo("PyGithub").get_label("Requested by user")
issues = self.user.get_user_issues(
"assigned",
"closed",
[requestedByUser],
"comments",
"asc",
datetime(2012, 5, 28, 23, 0, 0),
)
self.assertListKeyEqual(
issues,
lambda i: i.id,
[
6816576,
8495415,
6889934,
8339699,
8075253,
8033963,
9089893,
9489725,
11746141,
5152384,
5177381,
5783131,
6454054,
6641076,
6653907,
7331214,
9489813,
9776615,
10360280,
4356743,
6583381,
6751469,
8189836,
10758585,
12097154,
12867103,
5191621,
5256315,
6363719,
9209408,
6912733,
9948505,
11503771,
10922412,
11844658,
12566144,
6353712,
9323084,
10379143,
5387373,
12179668,
6911794,
11731917,
6807542,
6780606,
],
)
def testGetKeys(self):
self.assertListKeyEqual(
self.user.get_keys(),
lambda k: k.title,
["vincent@home", "vincent@gandi", "vincent@aws", "vincent@macbook"],
)
def testGetOrgs(self):
self.assertListKeyEqual(self.user.get_orgs(), lambda o: o.login, ["BeaverSoftware"])
def testGetRepos(self):
self.assertListKeyEqual(
self.user.get_repos(),
lambda r: r.name,
[
"TestPyGithub",
"django",
"PyGithub",
"developer.github.com",
"acme-public-website",
"C4Planner",
"Hacking",
"vincent-jacques.net",
"Contests",
"Candidates",
"Tests",
"DrawTurksHead",
"DrawSyntax",
"QuadProgMm",
"Boost.HierarchicalEnum",
"ViDE",
],
)
def testGetReposWithArguments(self):
self.assertListKeyEqual(
self.user.get_repos("all", "owner", "public", "full_name", "desc"),
lambda r: r.name,
[
"ViDE",
"QuadProgMm",
"PyGithub",
"DrawTurksHead",
"DrawSyntax",
"django",
"developer.github.com",
"C4Planner",
"Boost.HierarchicalEnum",
"acme-public-website",
],
)
def testCreateFork(self):
repo = self.user.create_fork(self.g.get_user("nvie").get_repo("gitflow"))
self.assertEqual(repo.source.full_name, "nvie/gitflow")
def testCreateRepoFromTemplate(self):
template_repo = self.g.get_repo("actions/hello-world-docker-action")
repo = self.user.create_repo_from_template("hello-world-docker-action-new", template_repo)
self.assertEqual(
repo.url,
"https://api.github.com/repos/jacquev6/hello-world-docker-action-new",
)
self.assertFalse(repo.is_template)
def testCreateRepoFromTemplateWithAllArguments(self):
template_repo = self.g.get_repo("actions/hello-world-docker-action")
description = "My repo from template"
private = True
repo = self.user.create_repo_from_template(
"hello-world-docker-action-new",
template_repo,
description=description,
include_all_branches=True,
private=private,
)
self.assertEqual(repo.description, description)
self.assertTrue(repo.private)
def testGetNotification(self):
notification = self.user.get_notification("8406712")
self.assertEqual(notification.id, "8406712")
self.assertEqual(notification.unread, False)
self.assertEqual(notification.reason, "author")
self.assertEqual(notification.subject.title, "Feature/coveralls")
self.assertEqual(notification.subject.type, "PullRequest")
self.assertEqual(notification.repository.id, 8432784)
self.assertEqual(
notification.updated_at,
datetime(2013, 3, 15, 5, 43, 11, tzinfo=timezone.utc),
)
self.assertEqual(notification.url, None)
self.assertEqual(notification.subject.url, None)
self.assertEqual(notification.subject.latest_comment_url, None)
self.assertEqual(
repr(notification),
'Notification(subject=NotificationSubject(title="Feature/coveralls"), id="8406712")',
)
self.assertEqual(repr(notification.subject), 'NotificationSubject(title="Feature/coveralls")')
def testGetNotifications(self):
self.assertListKeyEqual(self.user.get_notifications(participating=True), lambda n: n.id, ["8406712"])
def testGetNotificationsWithOtherArguments(self):
self.assertListKeyEqual(self.user.get_notifications(all=True), lambda n: n.id, [])
def testMarkNotificationsAsRead(self):
self.user.mark_notifications_as_read(datetime(2018, 10, 18, 18, 20, 0o1, 0))
def testGetTeams(self):
self.assertListKeyEqual(
self.user.get_teams(),
lambda t: t.name,
[
"Owners",
"Honoraries",
"Honoraries",
"Honoraries",
"Honoraries",
"Honoraries",
"Honoraries",
"Honoraries",
"Honoraries",
"Honoraries",
],
)
def testAcceptInvitation(self):
self.assertEqual(self.user.accept_invitation(4294886), None)
def testGetInvitations(self):
invitation = self.user.get_invitations()[0]
self.assertEqual(repr(invitation), "Invitation(id=17285388)")
self.assertEqual(invitation.id, 17285388)
self.assertEqual(invitation.permissions, "write")
created_at = datetime(2019, 6, 27, 11, 47, tzinfo=timezone.utc)
self.assertEqual(invitation.created_at, created_at)
self.assertEqual(
invitation.url,
"https://api.github.com/user/repository_invitations/17285388",
)
self.assertEqual(invitation.html_url, "https://github.com/jacquev6/PyGithub/invitations")
self.assertEqual(invitation.repository.name, "PyGithub")
self.assertEqual(invitation.invitee.login, "foobar-test1")
self.assertEqual(invitation.inviter.login, "jacquev6")
def testCreateMigration(self):
self.assertTrue(isinstance(self.user.create_migration(["sample-repo"]), github.Migration.Migration))
def testGetMigrations(self):
self.assertEqual(self.user.get_migrations().totalCount, 46)
def testInstallations(self):
installations = self.user.get_installations()
self.assertEqual(installations[0].id, 123456)
self.assertEqual(installations[0].app_id, 10101)
self.assertEqual(installations[0].target_id, 3344556)
self.assertEqual(installations[0].target_type, "User")
self.assertEqual(installations.totalCount, 1)
| 29,718
|
Python
|
.py
| 734
| 28.325613
| 408
| 0.530715
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,610
|
PullRequest.py
|
PyGithub_PyGithub/tests/PullRequest.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 @tmshn <tmshn@r.recruit.co.jp> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 MarcoFalke <falke.marco@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 MarcoFalke <falke.marco@gmail.com> #
# Copyright 2019 Mark Browning <mark@cerebras.net> #
# Copyright 2019 Pavan Kunisetty <nagapavan@users.noreply.github.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Tim Gates <tim.gates@iress.com> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Florent Clarret <florent.clarret@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Heitor Polidoro <14806300+heitorpolidoro@users.noreply.github.com>#
# Copyright 2023 Heitor Polidoro <heitor.polidoro@gmail.com> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 vanya20074 <vanya20074@gmail.com> #
# Copyright 2024 Austin Sasko <austintyler0239@yahoo.com> #
# Copyright 2024 Den Stroebel <stroebs@users.noreply.github.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from datetime import datetime, timezone
import pytest
import github
from . import Framework
class PullRequest(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("PyGithub/PyGithub")
self.pull = self.repo.get_pull(31)
marco_repo = self.g.get_repo("MarcoFalke/PyGithub", lazy=True)
self.pullIssue256Closed = marco_repo.get_pull(1)
self.pullIssue256Merged = marco_repo.get_pull(2)
self.pullIssue256Conflict = marco_repo.get_pull(3)
self.pullIssue256Uncached = marco_repo.get_pull(4)
flo_repo = self.g.get_repo("FlorentClarret/PyGithub")
self.pullMaintainerCanModify = flo_repo.get_pull(2)
self.delete_restore_repo = self.g.get_repo("austinsasko/PyGithub")
self.delete_restore_pull = self.delete_restore_repo.get_pull(21)
def testAttributesIssue256(self):
self.assertEqual(
self.pullIssue256Closed.closed_at,
datetime(2018, 5, 22, 14, 50, 43, tzinfo=timezone.utc),
)
self.assertEqual(
self.pullIssue256Merged.closed_at,
datetime(2018, 5, 22, 14, 53, 13, tzinfo=timezone.utc),
)
self.assertEqual(self.pullIssue256Conflict.closed_at, None)
self.assertEqual(self.pullIssue256Uncached.closed_at, None)
self.assertEqual(self.pullIssue256Closed.state, "closed")
self.assertEqual(self.pullIssue256Merged.state, "closed")
self.assertEqual(self.pullIssue256Conflict.state, "open")
self.assertEqual(self.pullIssue256Uncached.state, "open")
self.assertFalse(self.pullIssue256Closed.merged)
self.assertTrue(self.pullIssue256Merged.merged)
self.assertFalse(self.pullIssue256Conflict.merged)
self.assertFalse(self.pullIssue256Uncached.merged)
self.assertEqual(self.pullIssue256Closed.mergeable, None)
self.assertEqual(self.pullIssue256Merged.mergeable, None)
self.assertTrue(self.pullIssue256Conflict.mergeable)
self.assertEqual(self.pullIssue256Uncached.mergeable, None)
self.assertEqual(self.pullIssue256Closed.mergeable_state, "unknown")
self.assertEqual(self.pullIssue256Merged.mergeable_state, "unknown")
self.assertEqual(self.pullIssue256Conflict.mergeable_state, "clean")
self.assertEqual(self.pullIssue256Uncached.mergeable_state, "unknown")
def testAttributes(self):
self.assertEqual(self.pull.additions, 511)
self.assertEqual(self.pull.assignee.login, "jacquev6")
self.assertListKeyEqual(self.pull.assignees, lambda a: a.login, ["jacquev6"])
self.assertEqual(self.pull.base.label, "PyGithub:topic/RewriteWithGeneratedCode")
self.assertEqual(self.pull.base.sha, "ed866fc43833802ab553e5ff8581c81bb00dd433")
self.assertEqual(self.pull.base.user.login, "PyGithub")
self.assertEqual(self.pull.base.ref, "topic/RewriteWithGeneratedCode")
self.assertEqual(self.pull.base.repo.full_name, "PyGithub/PyGithub")
self.assertEqual(self.pull.body, "Body edited by PyGithub\n")
self.assertEqual(self.pull.changed_files, 45)
self.assertEqual(
self.pull.closed_at,
datetime(2012, 5, 27, 10, 29, 7, tzinfo=timezone.utc),
)
self.assertEqual(self.pull.comments, 1)
self.assertEqual(self.pull.commits, 3)
self.assertEqual(
self.pull.created_at,
datetime(2012, 5, 27, 9, 25, 36, tzinfo=timezone.utc),
)
self.assertEqual(self.pull.deletions, 384)
self.assertEqual(self.pull.diff_url, "https://github.com/PyGithub/PyGithub/pull/31.diff")
self.assertEqual(self.pull.head.ref, "master")
self.assertEqual(self.pull.html_url, "https://github.com/PyGithub/PyGithub/pull/31")
self.assertEqual(self.pull.id, 1436215)
self.assertEqual(
self.pull.issue_url,
"https://api.github.com/repos/PyGithub/PyGithub/issues/31",
)
self.assertListKeyEqual(self.pull.labels, lambda a: a.name, [])
self.assertFalse(self.pull.mergeable)
self.assertFalse(self.pull.rebaseable)
self.assertTrue(self.pull.merged)
self.assertEqual(
self.pull.merged_at,
datetime(2012, 5, 27, 10, 29, 7, tzinfo=timezone.utc),
)
self.assertEqual(self.pull.merged_by.login, "jacquev6")
self.assertEqual(self.pull.number, 31)
self.assertEqual(self.pull.patch_url, "https://github.com/PyGithub/PyGithub/pull/31.patch")
self.assertEqual(self.pull.review_comments, 2)
self.assertEqual(self.pull.state, "closed")
self.assertEqual(self.pull.title, "Title edited by PyGithub")
self.assertEqual(
self.pull.updated_at,
datetime(2018, 6, 25, 12, 54, 43, tzinfo=timezone.utc),
)
self.assertEqual(self.pull.url, "https://api.github.com/repos/PyGithub/PyGithub/pulls/31")
self.assertEqual(self.pull.user.login, "jacquev6")
self.assertEqual(self.pull.draft, False)
self.assertEqual(self.pull.maintainer_can_modify, False)
self.assertEqual(
repr(self.pull),
'PullRequest(title="Title edited by PyGithub", number=31)',
)
self.assertEqual(
repr(self.pull.base),
'PullRequestPart(sha="ed866fc43833802ab553e5ff8581c81bb00dd433")',
)
self.assertTrue(self.pullIssue256Conflict.rebaseable)
def testCreateComment(self):
commit = self.repo.get_commit("8a4f306d4b223682dd19410d4a9150636ebe4206")
comment = self.pull.create_comment("Comment created by PyGithub", commit, "src/github/Issue.py", 5)
self.assertEqual(comment.id, 886298)
def testCreateReviewCommentInReplyTo(self):
commit = self.repo.get_commit("8a4f306d4b223682dd19410d4a9150636ebe4206")
comment = self.pull.create_review_comment(
"Comment created by PyGithub",
commit,
"src/github/Issue.py",
5,
in_reply_to=42,
)
self.assertEqual(comment.id, 886298)
def testCreateReviewCommentSubjectType(self):
commit = self.repo.get_commit("8a4f306d4b223682dd19410d4a9150636ebe4206")
comment = self.pull.create_review_comment(
"Comment created by PyGithub",
commit,
"src/github/Issue.py",
5,
subject_type="file",
)
self.assertEqual(comment.id, 886298)
def testCreateMultilineReviewComment(self):
commit = self.repo.get_commit("8a4f306d4b223682dd19410d4a9150636ebe4206")
comment = self.pull.create_review_comment(
"Comment created by PyGithub",
commit,
"src/github/Issue.py",
10,
start_line=5,
)
self.assertEqual(comment.id, 886298)
def testCreateMultilineReviewCommentAsSuggestion(self):
commit = self.repo.get_commit("8a4f306d4b223682dd19410d4a9150636ebe4206")
comment = self.pull.create_review_comment(
"Comment created by PyGithub",
commit,
"src/github/Issue.py",
10,
start_line=5,
as_suggestion=True,
)
self.assertEqual(comment.id, 886298)
self.assertEqual(comment.body, "```suggestion\nComment created by PyGithub\n```")
def testCreateMultilineReviewCommentChoosingSide(self):
commit = self.repo.get_commit("8a4f306d4b223682dd19410d4a9150636ebe4206")
comment = self.pull.create_review_comment(
"Comment created by PyGithub",
commit,
"src/github/Issue.py",
10,
start_line=5,
side="RIGHT",
start_side="RIGHT",
)
self.assertEqual(comment.id, 886298)
def testGetComments(self):
epoch = datetime(1970, 1, 1, 0, 0)
comments = self.pull.get_comments(sort="updated", direction="desc", since=epoch)
self.assertListKeyEqual(comments, lambda c: c.id, [197784357, 1580134])
def testCreateIssueComment(self):
comment = self.pull.create_issue_comment("Issue comment created by PyGithub")
self.assertEqual(comment.id, 8387331)
def testGetIssueComments(self):
self.assertListKeyEqual(self.pull.get_issue_comments(), lambda c: c.id, [8387331])
def testGetIssueComment(self):
comment = self.pull.get_issue_comment(8387331)
self.assertEqual(comment.body, "Issue comment created by PyGithub")
def testGetIssueEvents(self):
self.assertListKeyEqual(
self.pull.get_issue_events(),
lambda e: e.id,
[16349963, 16350729, 16350730, 16350731, 28469043, 98136335],
)
def testGetReviewComments(self):
epoch = datetime(1970, 1, 1, 0, 0)
comments = self.pull.get_review_comments(sort="updated", direction="desc", since=epoch)
self.assertListKeyEqual(comments, lambda c: c.id, [197784357, 1580134])
self.assertListKeyEqual(comments, lambda c: c.pull_request_review_id, [131593233, None])
def testReviewRequests(self):
self.pull.create_review_request(reviewers="sfdye", team_reviewers="pygithub-owners")
review_requests = self.pull.get_review_requests()
self.assertListKeyEqual(review_requests[0], lambda c: c.login, ["sfdye"])
self.assertListKeyEqual(review_requests[1], lambda c: c.slug, ["pygithub-owners"])
self.pull.delete_review_request(reviewers="sfdye")
review_requests = self.pull.get_review_requests()
self.assertEqual(list(review_requests[0]), [])
self.assertListKeyEqual(review_requests[1], lambda c: c.slug, ["pygithub-owners"])
def testEditWithoutArguments(self):
self.pull.edit()
def testEditWithAllArguments(self):
self.pullMaintainerCanModify.edit(
"Title edited by PyGithub",
"Body edited by PyGithub",
"open",
"master",
True,
)
self.assertEqual(self.pullMaintainerCanModify.title, "Title edited by PyGithub")
self.assertEqual(self.pullMaintainerCanModify.body, "Body edited by PyGithub")
self.assertEqual(self.pullMaintainerCanModify.state, "open")
self.assertEqual(self.pullMaintainerCanModify.base.ref, "master")
self.assertTrue(self.pullMaintainerCanModify.maintainer_can_modify)
def testGetCommits(self):
self.assertListKeyEqual(
self.pull.get_commits(),
lambda c: c.sha,
[
"4aadfff21cdd2d2566b0e4bd7309c233b5f4ae23",
"93dcae5cf207de376c91d0599226e7c7563e1d16",
"8a4f306d4b223682dd19410d4a9150636ebe4206",
],
)
def testGetFiles(self):
self.assertListKeyEqual(
self.pull.get_files(),
lambda f: f.filename,
[
"codegen/templates/GithubObject.py",
"src/github/AuthenticatedUser.py",
"src/github/Authorization.py",
"src/github/Branch.py",
"src/github/Commit.py",
"src/github/CommitComment.py",
"src/github/CommitFile.py",
"src/github/CommitStats.py",
"src/github/Download.py",
"src/github/Event.py",
"src/github/Gist.py",
"src/github/GistComment.py",
"src/github/GistHistoryState.py",
"src/github/GitAuthor.py",
"src/github/GitBlob.py",
"src/github/GitCommit.py",
"src/github/GitObject.py",
"src/github/GitRef.py",
"src/github/GitTag.py",
"src/github/GitTree.py",
"src/github/GitTreeElement.py",
"src/github/Hook.py",
"src/github/Issue.py",
"src/github/IssueComment.py",
"src/github/IssueEvent.py",
"src/github/Label.py",
"src/github/Milestone.py",
"src/github/NamedUser.py",
"src/github/Organization.py",
"src/github/Permissions.py",
"src/github/Plan.py",
"src/github/PullRequest.py",
"src/github/PullRequestComment.py",
"src/github/PullRequestFile.py",
"src/github/Repository.py",
"src/github/RepositoryKey.py",
"src/github/Tag.py",
"src/github/Team.py",
"src/github/UserKey.py",
"test/Issue.py",
"test/IssueEvent.py",
"test/ReplayData/Issue.testAddAndRemoveLabels.txt",
"test/ReplayData/Issue.testDeleteAndSetLabels.txt",
"test/ReplayData/Issue.testGetLabels.txt",
"test/ReplayData/IssueEvent.setUp.txt",
],
)
def testGetLabels(self):
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["wip", "refactoring"])
def testAddAndRemoveLabels(self):
wip = self.repo.get_label("wip")
refactoring = self.repo.get_label("refactoring")
self.assertListKeyEqual(
self.pull.get_labels(),
lambda lb: lb.name,
["wip", "refactoring", "improvement"],
)
self.pull.remove_from_labels(wip)
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["refactoring", "improvement"])
self.pull.remove_from_labels(refactoring)
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["improvement"])
self.pull.add_to_labels(wip, refactoring)
self.assertListKeyEqual(
self.pull.get_labels(),
lambda lb: lb.name,
["wip", "refactoring", "improvement"],
)
def testAddAndRemoveLabelsWithStringArguments(self):
wip = "wip"
refactoring = "refactoring"
self.assertListKeyEqual(
self.pull.get_labels(),
lambda lb: lb.name,
["wip", "refactoring", "improvement"],
)
self.pull.remove_from_labels(wip)
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["refactoring", "improvement"])
self.pull.remove_from_labels(refactoring)
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["improvement"])
self.pull.add_to_labels(wip, refactoring)
self.assertListKeyEqual(
self.pull.get_labels(),
lambda lb: lb.name,
["wip", "refactoring", "improvement"],
)
def testDeleteAndSetLabels(self):
wip = self.repo.get_label("wip")
refactoring = self.repo.get_label("refactoring")
self.assertListKeyEqual(
self.pull.get_labels(),
lambda lb: lb.name,
["wip", "refactoring", "improvement"],
)
self.pull.delete_labels()
self.assertListKeyEqual(self.pull.get_labels(), None, [])
self.pull.set_labels(wip, refactoring)
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["wip", "refactoring"])
def testDeleteAndSetLabelsWithStringArguments(self):
wip = "wip"
refactoring = "refactoring"
self.assertListKeyEqual(
self.pull.get_labels(),
lambda lb: lb.name,
["wip", "refactoring", "improvement"],
)
self.pull.delete_labels()
self.assertListKeyEqual(self.pull.get_labels(), None, [])
self.pull.set_labels(wip, refactoring)
self.assertListKeyEqual(self.pull.get_labels(), lambda lb: lb.name, ["wip", "refactoring"])
def testMerge(self):
self.assertFalse(self.pull.is_merged())
status = self.pull.merge()
self.assertEqual(status.sha, "688208b1a5a074871d0e9376119556897439697d")
self.assertTrue(status.merged)
self.assertEqual(status.message, "Pull Request successfully merged")
self.assertTrue(self.pull.is_merged())
self.assertEqual(
repr(status),
'PullRequestMergeStatus(sha="688208b1a5a074871d0e9376119556897439697d", merged=True)',
)
def testMergeWithCommitMessage(self):
self.repo.get_pull(39).merge("Custom commit message created by PyGithub")
def testAddAndRemoveAssignees(self):
user1 = "jayfk"
user2 = self.g.get_user("jzelinskie")
self.assertListKeyEqual(self.pull.assignees, lambda a: a.login, ["jacquev6"])
url = self.pull.url
self.pull.add_to_assignees(user1, user2)
self.assertListKeyEqual(
self.pull.assignees,
lambda a: a.login,
["jacquev6", "stuglaser", "jayfk", "jzelinskie"],
)
self.assertEqual(self.pull.url, url)
self.pull.remove_from_assignees(user1, user2)
self.assertListKeyEqual(self.pull.assignees, lambda a: a.login, ["jacquev6", "stuglaser"])
self.assertEqual(self.pull.url, url)
def testUpdateBranch(self):
self.assertTrue(self.pull.update_branch("addaebea821105cf6600441f05ff2b413ab21a36"))
self.assertTrue(self.pull.update_branch())
def testDeleteOnMerge(self):
self.assertTrue(self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref))
self.assertFalse(self.delete_restore_pull.is_merged())
status = self.delete_restore_pull.merge(delete_branch=True)
self.assertTrue(status.merged)
self.assertTrue(self.delete_restore_pull.is_merged())
with self.assertRaises(github.GithubException) as raisedexp:
self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://docs.github.com/rest/reference/repos#get-a-branch",
"message": "Branch not found",
},
)
def testRestoreBranch(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref)
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://docs.github.com/rest/reference/repos#get-a-branch",
"message": "Branch not found",
},
)
self.assertTrue(self.delete_restore_pull.restore_branch())
self.assertTrue(self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref))
def testDeleteBranch(self):
self.assertTrue(self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref))
self.delete_restore_pull.delete_branch(force=False)
with self.assertRaises(github.GithubException) as raisedexp:
self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref)
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://docs.github.com/rest/reference/repos#get-a-branch",
"message": "Branch not found",
},
)
def testForceDeleteBranch(self):
self.assertTrue(self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref))
self.assertEqual(self.delete_restore_pull.delete_branch(force=True), None)
with self.assertRaises(github.GithubException) as raisedexp:
self.delete_restore_repo.get_branch(self.delete_restore_pull.head.ref)
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(
raisedexp.exception.data,
{
"documentation_url": "https://docs.github.com/rest/reference/repos#get-a-branch",
"message": "Branch not found",
},
)
def testEnableAutomerge(self):
# To reproduce this, the PR repository need to have the "Allow auto-merge" option enabled
response = self.pull.enable_automerge(
merge_method="SQUASH",
author_email="foo@example.com",
client_mutation_id="1234",
commit_body="body of the commit",
commit_headline="The commit headline",
expected_head_oid="0283d46537193f1fed7d46859f15c5304b9836f9",
)
assert response == {
"data": {
"enablePullRequestAutoMerge": {
"actor": {
"avatarUrl": "https://avatars.githubusercontent.com/u/14806300?u=786f9f8ef8782d45381b01580f7f7783cf9c7e37&v=4",
"login": "heitorpolidoro",
"resourcePath": "/heitorpolidoro",
"url": "https://github.com/heitorpolidoro",
},
"clientMutationId": None,
}
}
}
def testEnableAutomergeDefaultValues(self):
# To reproduce this, the PR repository need to have the "Allow auto-merge" option enabled
# The default values are:
# - merge_method = "MERGE"
self.pull.enable_automerge()
def testEnableAutomergeNotValidMergeMethod(self):
with pytest.raises(AssertionError):
self.pull.enable_automerge(merge_method="INVALID")
def testEnableAutomergeError(self):
# To reproduce this, the PR repository need to have the "Allow auto-merge" option disabled
with pytest.raises(github.GithubException) as error:
self.pull.enable_automerge()
assert error.value.status == 400
assert error.value.data == {
"data": {"enablePullRequestAutoMerge": None},
"errors": [
{
"locations": [{"column": 81, "line": 1}],
"message": "Pull request Auto merge is not allowed for this repository",
"path": ["enablePullRequestAutoMerge"],
"type": "UNPROCESSABLE",
}
],
}
def testDisableAutomerge(self):
response = self.pull.disable_automerge()
assert response == {
"data": {
"disablePullRequestAutoMerge": {
"actor": {
"avatarUrl": "https://avatars.githubusercontent.com/u/14806300?u=786f9f8ef8782d45381b01580f7f7783cf9c7e37&v=4",
"login": "heitorpolidoro",
"resourcePath": "/heitorpolidoro",
"url": "https://github.com/heitorpolidoro",
},
"clientMutationId": None,
}
}
}
| 26,664
|
Python
|
.py
| 529
| 40.098299
| 135
| 0.607422
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,611
|
Issue2030.py
|
PyGithub_PyGithub/tests/Issue2030.py
|
############################ Copyrights and license ############################
# #
# Copyright 2021 karthik-kadajji <60779081+karthik-kadajji@users.noreply.github.com>#
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class Organization(Framework.TestCase):
def testIssue2030CreateProject(self):
super().setUp()
project = "ultratendency"
self.user = self.g.get_user("karthik-kadajji-t")
self.org = self.g.get_organization("testkarthik")
self.org.create_project(project)
project = self.org.get_projects()[0].name
self.assertEqual("ultratendency", project)
| 2,212
|
Python
|
.py
| 32
| 66.125
| 85
| 0.441636
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,612
|
OrganizationHasInMembers.py
|
PyGithub_PyGithub/tests/OrganizationHasInMembers.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Matthew Neal <meneal@matthews-mbp.raleigh.ibm.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 Sam Corbett <sam.corbett@cloudsoftcorp.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class OrganizationHasInMembers(Framework.TestCase):
def setUp(self):
super().setUp()
self.user = self.g.get_user("meneal")
self.org = self.g.get_organization("RobotWithFeelings")
self.has_in_members = self.org.has_in_members(self.user)
def testHasInMembers(self):
self.assertTrue(self.has_in_members)
| 3,055
|
Python
|
.py
| 42
| 70.5
| 85
| 0.4779
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,613
|
Label.py
|
PyGithub_PyGithub/tests/Label.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Mateusz Loskot <mateusz@loskot.net> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class Label(Framework.TestCase):
def setUp(self):
super().setUp()
self.label = self.g.get_user().get_repo("PyGithub").get_label("Bug")
def testAttributes(self):
self.assertEqual(self.label.color, "e10c02")
self.assertEqual(self.label.name, "Bug")
self.assertIsNone(self.label.description)
self.assertEqual(self.label.url, "https://api.github.com/repos/jacquev6/PyGithub/labels/Bug")
self.assertEqual(repr(self.label), 'Label(name="Bug")')
def testEdit(self):
self.label.edit("LabelEditedByPyGithub", "0000ff", "Description of LabelEditedByPyGithub")
self.assertEqual(self.label.color, "0000ff")
self.assertEqual(self.label.description, "Description of LabelEditedByPyGithub")
self.assertEqual(self.label.name, "LabelEditedByPyGithub")
self.assertEqual(
self.label.url,
"https://api.github.com/repos/jacquev6/PyGithub/labels/LabelEditedByPyGithub",
)
def testDelete(self):
self.label.delete()
| 3,914
|
Python
|
.py
| 57
| 64.894737
| 101
| 0.512334
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,614
|
conf.py
|
PyGithub_PyGithub/doc/conf.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Morgan Goose <morgan.goose@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Liuyang Wan <tsfdye@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from __future__ import annotations
import datetime
import glob
import os
import re
import sys
from typing import Iterable
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(".."))
from importlib.metadata import version # noqa: E402
setupVersion = version("pygithub")
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ["sphinx.ext.autodoc", "sphinx.ext.coverage", "sphinx.ext.mathjax"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "PyGithub"
copyright = "%d, Vincent Jacques" % datetime.date.today().year
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = setupVersion
# The full version, including alpha/beta/rc tags.
release = setupVersion
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "PyGithubdoc"
# -- Options for LaTeX output --------------------------------------------------
# latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
# }
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
("index", "PyGithub.tex", "PyGithub Documentation", "Vincent Jacques", "manual"),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [("index", "pygithub", "PyGithub Documentation", ["Vincent Jacques"], 1)]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
"index",
"PyGithub",
"PyGithub Documentation",
"Vincent Jacques",
"PyGithub",
"One line description of project.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
autodoc_default_flags = ["members"]
autodoc_member_order = "bysource"
autoclass_content = "both"
githubObjectTypes = {
variation
for object_type in ["GithubObject", "CompletableGithubObject", "NonCompletableGithubObject"]
for variation in [object_type, "GithubObject." + object_type, "github.GithubObject." + object_type]
}
githubObjectClasses: dict[str, str] = {}
def collect_classes(types: set[str]) -> Iterable[tuple[str, str]]:
def get_base_classes(class_definition: str) -> Iterable[str]:
if "(" in class_definition and ")" in class_definition:
for base in class_definition[class_definition.index("(") + 1 : class_definition.index(")")].split(","):
yield base.strip()
else:
return []
for filename in sorted(glob.glob("../github/*.py")):
module = f"github.{filename[10:-3]}"
with open(filename) as r:
for line in r.readlines():
if line.startswith("class ") and any([base in types for base in get_base_classes(line)]):
class_name = re.match(r"class (\w+)[:(]", line).group(1)
if class_name not in types:
yield class_name, f"{module}"
# get all classes derived from GithubObject classes directly
classes = list(collect_classes(githubObjectTypes))
while classes:
githubObjectClasses.update(classes)
# get all classes derived from detected classes
githubObjectTypes.update(
{
variation
for object_type in [cls for cls, _ in classes]
for variation in [object_type, "GithubObject." + object_type, "github.GithubObject." + object_type]
}
)
classes = list(collect_classes(set(githubObjectTypes)))
with open("github_objects.rst", "w") as f:
f.write("Github objects\n")
f.write("==============\n")
f.write("\n")
f.write(".. autoclass:: github.GithubObject.GithubObject()\n")
f.write("\n")
f.write(".. toctree::\n")
for githubObjectClass in sorted(githubObjectClasses.keys()):
f.write(" github_objects/" + githubObjectClass + "\n")
for githubObjectClass, module in githubObjectClasses.items():
with open("github_objects/" + githubObjectClass + ".rst", "w") as f:
f.write(githubObjectClass + "\n")
f.write("=" * len(githubObjectClass) + "\n")
f.write("\n")
f.write(".. autoclass:: " + module + "." + githubObjectClass + "()\n")
methods = dict()
githubObjectClasses.update([("MainClass", "github.MainClass")])
githubObjectClasses.update([("GithubIntegration", "github.GithubIntegration")])
for githubObjectClass, module in githubObjectClasses.items():
with open("../" + module.replace(".", "/") + ".py") as f:
method = None
isProperty = False
for line in f:
line = line.rstrip()
if line == " @property":
isProperty = True
if line.startswith(" def "):
if not isProperty:
method = line.split("(")[0][8:]
if method in [
"_initAttributes",
"_useAttributes",
"__init__",
"__create_pull_1",
"__create_pull_2",
"__create_pull",
"_hub",
"__get_FIX_REPO_GET_GIT_REF",
"__set_FIX_REPO_GET_GIT_REF",
"__get_per_page",
"__set_per_page",
"create_from_raw_data",
"dump",
"load",
]:
method = None
isProperty = False
if line.startswith(" :calls: `"):
for callee in line[16:].split(" or "):
verb, url = callee[1:].split(" ")[0:2]
if url not in methods:
methods[url] = dict()
if verb not in methods[url]:
methods[url][verb] = set()
methods[url][verb].add(":meth:`" + module + "." + githubObjectClass + "." + method + "`")
method = None
methods["/markdown/raw"] = dict()
methods["/markdown/raw"]["POST"] = ["Not implemented, see ``/markdown``"]
methods["/rate_limit"] = dict()
methods["/rate_limit"]["GET"] = ["Not implemented, see `Github.rate_limiting`"]
with open("apis.rst", "w") as apis:
apis.write("APIs\n")
apis.write("====\n")
apis.write("\n")
for url, verbs in sorted(methods.items()):
apis.write("* ``" + url + "``\n")
apis.write("\n")
for verb in ["GET", "PATCH", "POST", "PUT", "DELETE"]:
if verb in verbs:
apis.write(" * " + verb + ": " + " or ".join(sorted(verbs[verb])) + "\n")
apis.write("\n")
| 15,305
|
Python
|
.py
| 316
| 43.462025
| 115
| 0.609926
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,615
|
add_attribute.py
|
PyGithub_PyGithub/scripts/add_attribute.py
|
#!/usr/bin/env python
############################ Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Thialfihar <thi@thialfihar.org> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Yossarian King <yggy@blackbirdinteractive.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Isac Souza <isouza@daitan.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2021 karsten-wagner <39054096+karsten-wagner@users.noreply.github.com>#
# Copyright 2022 Gabriele Oliaro <ict@gabrieleoliaro.it> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Jacky Lam <jacky.lam@r2studiohk.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from __future__ import annotations
import os.path
import sys
className, attributeName, attributeType = sys.argv[1:4]
if len(sys.argv) > 4:
attributeClassType = sys.argv[4]
else:
attributeClassType = ""
types = {
"string": (
"str",
None,
'self._makeStringAttribute(attributes["' + attributeName + '"])',
"str",
),
"int": (
"int",
None,
'self._makeIntAttribute(attributes["' + attributeName + '"])',
"int",
),
"bool": (
"bool",
None,
'self._makeBoolAttribute(attributes["' + attributeName + '"])',
"bool",
),
"datetime": (
"datetime",
"str",
'self._makeDatetimeAttribute(attributes["' + attributeName + '"])',
"datetime",
),
"dict": (
"dict[" + attributeClassType + "]",
None,
'self._makeDictAttribute(attributes["' + attributeName + '"])',
"dict[" + attributeClassType + "]",
),
"class": (
":class:`" + attributeClassType + "`",
None,
"self._makeClassAttribute(" + attributeClassType + ', attributes["' + attributeName + '"])',
attributeClassType,
),
}
attributeDocType, attributeAssertType, attributeValue, attributeClassType = types[attributeType]
if attributeType == "class":
# Wrap in quotes to avoid an explicit import requirement which can cause circular import errors
attributeClassType = f"'{attributeClassType}'"
fileName = os.path.join("github", className + ".py")
def add_as_class_property(lines: list[str]) -> list[str]:
newLines = []
i = 0
added = False
isCompletable = True
isProperty = False
while not added:
line = lines[i].rstrip()
i += 1
if line.startswith("class "):
if "NonCompletableGithubObject" in line:
isCompletable = False
elif line == " @property":
isProperty = True
elif line.startswith(" def "):
attrName = line[8:-7]
# Properties will be inserted after __repr__, but before any other function.
if (not attrName.startswith("__repr__") and not attrName.startswith("_initAttributes")) and (
attrName == "_identity" or attrName > attributeName or not isProperty
):
if not isProperty:
newLines.append(" @property")
newLines.append(" def " + attributeName + "(self) -> " + attributeClassType + ":")
if isCompletable:
newLines.append(" self._completeIfNotSet(self._" + attributeName + ")")
newLines.append(" return self._" + attributeName + ".value")
newLines.append("")
if isProperty:
newLines.append(" @property")
added = True
isProperty = False
newLines.append(line)
while i < len(lines):
line = lines[i].rstrip()
i += 1
newLines.append(line)
return newLines
def add_to_initAttributes(lines: list[str]) -> list[str]:
newLines = []
added = False
i = 0
inInit = False
while not added:
line = lines[i].rstrip()
i += 1
if line.strip().startswith("def _initAttributes(self)"):
inInit = True
if inInit:
if not line or line.endswith(" = github.GithubObject.NotSet") or line.endswith(" = NotSet"):
if line:
attrName = line[14:-29]
if not line or attrName > attributeName:
newLines.append(f" self._{attributeName}: Attribute[{attributeClassType}] = NotSet")
added = True
newLines.append(line)
while i < len(lines):
line = lines[i].rstrip()
i += 1
newLines.append(line)
return newLines
def add_to_useAttributes(lines: list[str]) -> list[str]:
i = 0
newLines = []
added = False
inUse = False
while not added:
try:
line = lines[i].rstrip()
except IndexError:
line = ""
i += 1
if line.strip().startswith("def _useAttributes(self, attributes:"):
inUse = True
if inUse:
if not line or line.endswith(" in attributes: # pragma no branch"):
if line:
attrName = line[12:-36]
if not line or attrName > attributeName:
newLines.append(' if "' + attributeName + '" in attributes: # pragma no branch')
if attributeAssertType:
newLines.append(
' assert attributes["'
+ attributeName
+ '"] is None or isinstance(attributes["'
+ attributeName
+ '"], '
+ attributeAssertType
+ '), attributes["'
+ attributeName
+ '"]'
)
newLines.append(f" self._{attributeName} = {attributeValue}")
added = True
newLines.append(line)
while i < len(lines):
line = lines[i].rstrip()
i += 1
newLines.append(line)
return newLines
with open(fileName) as f:
source = f.readlines()
source = add_as_class_property(source)
source = add_to_initAttributes(source)
source = add_to_useAttributes(source)
with open(fileName, "w", newline="\n") as f:
f.write("\n".join(source) + "\n")
| 8,790
|
Python
|
.py
| 196
| 36.346939
| 111
| 0.504785
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,616
|
fix_headers.py
|
PyGithub_PyGithub/scripts/fix_headers.py
|
#!/usr/bin/env python
############################ Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import os
import subprocess
eightySharps = "#" * 80
def generateLicenseSection(filename):
yield "############################ Copyrights and license ############################"
yield "# #"
for year, name in sorted(listContributors(filename)):
line = "# Copyright " + year + " " + name
line += (79 - len(line)) * " " + "#"
yield line
yield "# #"
yield "# This file is part of PyGithub. #"
yield "# http://pygithub.readthedocs.io/ #"
yield "# #"
yield "# PyGithub is free software: you can redistribute it and/or modify it under #"
yield "# the terms of the GNU Lesser General Public License as published by the Free #"
yield "# Software Foundation, either version 3 of the License, or (at your option) #"
yield "# any later version. #"
yield "# #"
yield "# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #"
yield "# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #"
yield "# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #"
yield "# details. #"
yield "# #"
yield "# You should have received a copy of the GNU Lesser General Public License #"
yield "# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #"
yield "# #"
yield "################################################################################"
def listContributors(filename):
contributors = set()
result = subprocess.check_output(
["git", "log", "--follow", "--format=format:%ad %an <%ae>", "--date=short", "--", filename],
text=True,
)
for line in result.split("\n"):
year = line[0:4]
name = line[11:]
contributors.add((year, name))
return contributors
def extractBodyLines(lines):
bodyLines = []
seenEndOfHeader = False
for line in lines:
if len(line) > 0 and line[0] != "#":
seenEndOfHeader = True
if seenEndOfHeader:
bodyLines.append(line)
# else:
# print "HEAD:", line
if line == eightySharps:
seenEndOfHeader = True
# print "BODY:", "\nBODY: ".join(bodyLines)
return bodyLines
class PythonHeader:
def fix(self, filename, lines):
isExecutable = len(lines) > 0 and lines[0].startswith("#!")
newLines = []
if isExecutable:
newLines.append("#!/usr/bin/env python")
for line in generateLicenseSection(filename):
newLines.append(line)
bodyLines = extractBodyLines(lines)
if len(bodyLines) > 0 and bodyLines[0] != "":
newLines.append("")
if "import " not in bodyLines[0] and bodyLines[0] != '"""' and not bodyLines[0].startswith("##########"):
newLines.append("")
newLines += bodyLines
return newLines
class StandardHeader:
def fix(self, filename, lines):
newLines = []
for line in generateLicenseSection(filename):
newLines.append(line)
bodyLines = extractBodyLines(lines)
if len(bodyLines) > 0 and bodyLines[0] != "":
newLines.append("")
newLines += bodyLines
return newLines
def findHeadersAndFiles():
for root, dirs, files in os.walk(".", topdown=True):
for dir in list(dirs):
if dir.startswith("."):
dirs.remove(dir)
for excluded in ["developer.github.com", "build", "venv", "PyGithub.egg-info", "requirements", "pre-commit"]:
if excluded in dirs:
dirs.remove(excluded)
for filename in files:
fullname = os.path.join(root, filename)
if filename == "GithubCredentials.py":
pass
elif filename.endswith(".py"):
yield (PythonHeader(), fullname)
elif filename in ["COPYING", "COPYING.LESSER", "MAINTAINERS"]:
pass
elif filename.endswith(".rst") or filename.endswith(".md"):
pass
elif filename == ".gitignore":
yield (StandardHeader(), fullname)
elif "ReplayData" in fullname:
pass
elif fullname.endswith(".pyi"):
pass
elif fullname.endswith(".pyc"):
pass
else:
print(f"Don't know what to do with {filename} in {root}")
def main():
for header, filename in findHeadersAndFiles():
print("Analyzing", filename)
with open(filename, encoding="utf-8") as f:
lines = list(line.rstrip() for line in f)
newLines = header.fix(filename, lines)
if newLines != lines:
print(" => actually modifying", filename)
with open(filename, "w", encoding="utf-8") as f:
for line in newLines:
f.write(line + "\n")
if __name__ == "__main__":
main()
| 8,192
|
Python
|
.py
| 151
| 46.86755
| 117
| 0.476589
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,617
|
setup.py
|
jfinkels_flask-restless/setup.py
|
# setup.py - packaging and distribution configuration for Flask-Restless
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Flask-Restless is a `Flask`_ extension that provides simple
generation of ReSTful APIs that satisfy the `JSON API`_ specification
given database models defined using `SQLAlchemy`_ (or
`Flask-SQLAlchemy`_).
For more information, see the `documentation`_, `pypi`_, or the `source
code`_ repository.
.. _Flask: http://flask.pocoo.org
.. _SQLAlchemy: https://sqlalchemy.org
.. _Flask-SQLAlchemy: https://pypi.python.org/pypi/Flask-SQLAlchemy
.. _JSON API: http://jsonapi.org
.. _documentation: https://flask-restless.readthedocs.org
.. _pypi: https://pypi.python.org/pypi/Flask-Restless
.. _source code: https://github.com/jfinkels/flask-restless
"""
import codecs
import os.path
import re
from setuptools import setup, find_packages
#: A regular expression capturing the version number from Python code.
VERSION_RE = r"^__version__ = ['\"]([^'\"]*)['\"]"
# TODO We require Flask version 1.0 or greater if we want Flask to recognize
# the JSON API mimetype as a form of JSON and therefore automatically be able
# to deserialize JSON to Python via the Request.get_json() method. On the other
# hand, we could keep the 0.10 requirement and simply rely on the ``force``
# keyword argument of that method, which also works around the limitations in
# MSIE8 and MSIE9...
#: The installation requirements for Flask-Restless. Flask-SQLAlchemy is not
#: required, so the user must install it explicitly.
REQUIREMENTS = ['flask>=0.10', 'sqlalchemy>=0.8', 'python-dateutil>2.2']
#: The absolute path to this file.
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""Reads the entire contents of the file whose path is given as `parts`."""
with codecs.open(os.path.join(HERE, *parts), 'r') as f:
return f.read()
def find_version(*file_path):
"""Returns the version number appearing in the file in the given file
path.
Each positional argument indicates a member of the path.
"""
version_file = read(*file_path)
version_match = re.search(VERSION_RE, version_file, re.MULTILINE)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
setup(
author='Jeffrey Finkelstein',
author_email='jeffrey.finkelstein@gmail.com',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
('License :: OSI Approved :: '
'GNU Affero General Public License v3 or later (AGPLv3+)'),
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Database :: Front-Ends',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
description=('Flask extension for generating a JSON API interface for'
' SQLAlchemy models'),
download_url='https://pypi.python.org/pypi/Flask-Restless',
install_requires=REQUIREMENTS,
include_package_data=True,
keywords=['ReST', 'API', 'Flask'],
license='GNU AGPLv3+ or BSD',
long_description=__doc__,
name='Flask-Restless',
platforms='any',
packages=find_packages(exclude=['tests', 'tests.*']),
test_suite='tests',
tests_require=['unittest2'],
url='https://github.com/jfinkels/flask-restless',
version=find_version('flask_restless', '__init__.py'),
zip_safe=False
)
| 4,267
|
Python
|
.py
| 96
| 40.229167
| 79
| 0.696583
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,618
|
manager.py
|
jfinkels_flask-restless/flask_restless/manager.py
|
# manager.py - class that creates endpoints compliant JSON API
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Provides the main class with which users of Flask-Restless interact.
The :class:`APIManager` class allow users to create ReSTful APIs for
their SQLAlchemy models.
"""
from collections import defaultdict
from collections import namedtuple
from uuid import uuid1
import sys
from sqlalchemy.inspection import inspect
from flask import Blueprint
from flask import url_for as flask_url_for
from .helpers import collection_name
from .helpers import model_for
from .helpers import primary_key_for
from .helpers import serializer_for
from .helpers import url_for
from .serialization import DefaultSerializer
from .serialization import DefaultDeserializer
from .views import API
from .views import FunctionAPI
from .views import RelationshipAPI
from .views import SchemaView
#: The names of HTTP methods that allow fetching information.
READONLY_METHODS = frozenset(('GET', ))
#: The names of HTTP methods that allow creating, updating, or deleting
#: information.
WRITEONLY_METHODS = frozenset(('PATCH', 'POST', 'DELETE'))
#: The set of all recognized HTTP methods.
ALL_METHODS = READONLY_METHODS | WRITEONLY_METHODS
#: The default URL prefix for APIs created by instance of :class:`APIManager`.
DEFAULT_URL_PREFIX = '/api'
if sys.version_info < (3, ):
STRING_TYPES = (str, unicode) # noqa
else:
STRING_TYPES = (str, )
#: A triple that stores the SQLAlchemy session and the universal pre- and post-
#: processors to be applied to any API created for a particular Flask
#: application.
#:
#: These tuples are used by :class:`APIManager` to store information about
#: Flask applications registered using :meth:`APIManager.init_app`.
# RestlessInfo = namedtuple('RestlessInfo', ['session',
# 'universal_preprocessors',
# 'universal_postprocessors'])
#: A tuple that stores information about a created API.
#:
#: The elements are, in order,
#:
#: - `collection_name`, the name by which a collection of instances of
#: the model exposed by this API is known,
#: - `blueprint_name`, the name of the blueprint that contains this API,
#: - `serializer`, the subclass of :class:`Serializer` provided for the
#: model exposed by this API.
#: - `primary_key`, the primary key used by the model
#:
APIInfo = namedtuple('APIInfo', ['collection_name', 'blueprint_name',
'serializer', 'primary_key'])
class IllegalArgumentError(Exception):
"""This exception is raised when a calling function has provided illegal
arguments to a function or method.
"""
pass
class APIManager(object):
"""Provides a method for creating a public ReSTful JSON API with respect
to a given :class:`~flask.Flask` application object.
The :class:`~flask.Flask` object can either be specified in the
constructor, or after instantiation time by calling the
:meth:`init_app` method.
`app` is the :class:`~flask.Flask` object containing the user's
Flask application.
`session` is the :class:`~sqlalchemy.orm.session.Session` object in
which changes to the database will be made.
`flask_sqlalchemy_db` is the :class:`~flask_sqlalchemy.SQLAlchemy`
object with which `app` has been registered and which contains the
database models for which API endpoints will be created.
If `flask_sqlalchemy_db` is not ``None``, `session` will be ignored.
For example, to use this class with models defined in pure SQLAlchemy::
from flask import Flask
from flask_restless import APIManager
from sqlalchemy import create_engine
from sqlalchemy.orm.session import sessionmaker
engine = create_engine('sqlite:////tmp/mydb.sqlite')
Session = sessionmaker(bind=engine)
mysession = Session()
app = Flask(__name__)
apimanager = APIManager(app, session=mysession)
and with models defined with Flask-SQLAlchemy::
from flask import Flask
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLALchemy(app)
apimanager = APIManager(app, flask_sqlalchemy_db=db)
`url_prefix` is the URL prefix at which each API created by this
instance will be accessible. For example, if this is set to
``'foo'``, then this method creates endpoints of the form
``/foo/<collection_name>`` when :meth:`create_api` is called. If the
`url_prefix` is set in the :meth:`create_api`, the URL prefix set in
the constructor will be ignored for that endpoint.
`postprocessors` and `preprocessors` must be dictionaries as
described in the section :doc:`processors`. These preprocessors and
postprocessors will be applied to all requests to and responses from
APIs created using this APIManager object. The preprocessors and
postprocessors given in these keyword arguments will be prepended to
the list of processors given for each individual model when using
the :meth:`create_api_blueprint` method (more specifically, the
functions listed here will be executed before any functions
specified in the :meth:`create_api_blueprint` method). For more
information on using preprocessors and postprocessors, see
:doc:`processors`.
"""
#: The format of the name of the API view for a given model.
#:
#: This format string expects the name of a model to be provided when
#: formatting.
APINAME_FORMAT = '{0}api'
def __init__(self, app=None, session=None, flask_sqlalchemy_db=None,
preprocessors=None, postprocessors=None, url_prefix=None):
if session is None and flask_sqlalchemy_db is None:
msg = 'must specify either `flask_sqlalchemy_db` or `session`'
raise ValueError(msg)
self.app = app
# Stash this instance so that it can be examined later by the global
# `url_for`, `model_for`, and `collection_name` functions.
#
# TODO This is a bit of poor code style because it requires the
# APIManager to know about these global functions that use it.
url_for.register(self)
model_for.register(self)
collection_name.register(self)
serializer_for.register(self)
primary_key_for.register(self)
#: A mapping whose keys are models for which this object has
#: created an API via the :meth:`create_api_blueprint` method
#: and whose values are the corresponding collection names for
#: those models.
self.created_apis_for = {}
# TODO In Python 2.7, this can just be
#
# self.models = self.created_apis_for.viewkeys()
#
# and in Python 3+,
#
# self.models = self.created_apis_for.keys()
#
# Since we need to support Python 2.6, we need to manually keep
# `self.models` updated on each addition to
# `self.created_apis_for`.
#: The set of models for which an API has been created.
#:
#: This set matches the set of keys of :attr:`.created_apis_for`
#: exactly.
self.models = set()
#: List of blueprints created by :meth:`create_api` to be registered
#: to the app when calling :meth:`init_app`.
self.blueprints = []
# If a Flask-SQLAlchemy object is provided, prefer the session
# from that object.
if flask_sqlalchemy_db is not None:
session = flask_sqlalchemy_db.session
# pre = preprocessors or {}
# post = postprocessors or {}
# self.restless_info = RestlessInfo(session, pre, post)
self.pre = preprocessors or {}
self.post = postprocessors or {}
self.session = session
#: The default URL prefix for APIs created by this manager.
#:
#: This can be overriden by the `url_prefix` keyword argument in the
#: :meth:`create_api` method.
self.url_prefix = url_prefix
# if self.app is not None:
# self.init_app(self.app)
@staticmethod
def api_name(collection_name):
"""Returns the name of the :class:`API` instance exposing models of the
specified type of collection.
`collection_name` must be a string.
"""
return APIManager.APINAME_FORMAT.format(collection_name)
def _create_schema(self):
"""Create a blueprint with an endpoint that exposes the API schema.
This method returns an instance of :class:`flask.Blueprint` that
has a single route at the top-level that exposes the URLs for
each created API; for example, `GET /api` yields a response that
indicates
.. sourcecode:: json
{
"person": "http://example.com/api/person",
"article": "http://example.com/api/person"
}
The view provided by this blueprint depends on the value of
:attr:`.models`, so changes to :attr:`.models` will be reflected
in the response.
"""
# It is important that `self.models` is being passed as
# reference here, since it will be updated each time
# `create_api` is called (in the setting where APIManager is
# provided with a Flask object at instantiation time).
schema_view = SchemaView.as_view('schemaview', self.models)
url_prefix = self.url_prefix or DEFAULT_URL_PREFIX
# The name of this blueprint must be unique, so in order to
# accomodate the situation where we have multiple APIManager
# instances calling `init_app` on a single Flask instance, we
# append the ID of this APIManager object to the name of the
# blueprint.
name = 'manager{0}.schema'.format(id(self))
blueprint = Blueprint(name, __name__, url_prefix=url_prefix)
blueprint.add_url_rule('', view_func=schema_view)
return blueprint
def model_for(self, collection_name):
"""Returns the SQLAlchemy model class whose type is given by the
specified collection name.
`collection_name` is a string containing the collection name as
provided to the ``collection_name`` keyword argument to
:meth:`create_api_blueprint`.
The collection name should correspond to a model on which
:meth:`create_api_blueprint` has been invoked previously. If it doesn't
this method raises :exc:`ValueError`.
This method is the inverse of :meth:`collection_name`::
>>> from mymodels import Person
>>> manager.create_api(Person, collection_name='people')
>>> manager.collection_name(manager.model_for('people'))
'people'
>>> manager.model_for(manager.collection_name(Person))
<class 'mymodels.Person'>
"""
# Reverse the dictionary.
#
# TODO In Python 3 this should be a dict comprehension.
models = dict((info.collection_name, model)
for model, info in self.created_apis_for.items())
try:
return models[collection_name]
except KeyError:
raise ValueError('Collection name {0} unknown. Be sure to set the'
' `collection_name` keyword argument when calling'
' `create_api()`.'.format(collection_name))
def url_for(self, model, **kw):
"""Returns the URL for the specified model, similar to
:func:`flask.url_for`.
`model` is a SQLAlchemy model class. This must be a model on
which :meth:`create_api_blueprint` has been invoked previously,
otherwise a :exc:`KeyError` is raised.
This method only returns URLs for endpoints created by this
:class:`APIManager`.
The remaining keyword arguments are passed directly on to
:func:`flask.url_for`.
.. _Flask request context: http://flask.pocoo.org/docs/0.10/reqcontext/
"""
collection_name = self.created_apis_for[model].collection_name
blueprint_name = self.created_apis_for[model].blueprint_name
api_name = APIManager.api_name(collection_name)
parts = [blueprint_name, api_name]
# If we are looking for a relationship URL, the view name ends with
# '.relationships'.
if 'relationship' in kw and kw.pop('relationship'):
parts.append('relationships')
url = flask_url_for('.'.join(parts), **kw)
# if _absolute_url:
# url = urljoin(request.url_root, url)
return url
def collection_name(self, model):
"""Returns the collection name for the specified model, as specified by
the ``collection_name`` keyword argument to
:meth:`create_api_blueprint`.
`model` is a SQLAlchemy model class. This must be a model on
which :meth:`create_api_blueprint` has been invoked previously,
otherwise a :exc:`KeyError` is raised.
This method only returns URLs for endpoints created by this
:class:`APIManager`.
"""
return self.created_apis_for[model].collection_name
def serializer_for(self, model):
"""Returns the serializer for the specified model, as specified
by the `serializer` keyword argument to
:meth:`create_api_blueprint`.
`model` is a SQLAlchemy model class. This must be a model on
which :meth:`create_api_blueprint` has been invoked previously,
otherwise a :exc:`KeyError` is raised.
This method only returns URLs for endpoints created by this
:class:`APIManager`.
"""
return self.created_apis_for[model].serializer
def primary_key_for(self, model):
"""Returns the primary key for the specified model, as specified
by the `primary_key` keyword argument to
:meth:`create_api_blueprint`.
`model` is a SQLAlchemy model class. This must be a model on
which :meth:`create_api_blueprint` has been invoked previously,
otherwise a :exc:`KeyError` is raised.
"""
return self.created_apis_for[model].primary_key
def init_app(self, app):
"""Registers any created APIs on the given Flask application.
This function should only be called if no Flask application was
provided in the `app` keyword argument to the constructor of
this class.
When this function is invoked, any blueprint created by a
previous invocation of :meth:`create_api` will be registered on
`app` by calling the :meth:`~flask.Flask.register_blueprint`
method.
To use this method with pure SQLAlchemy, for example::
from flask import Flask
from flask_restless import APIManager
from sqlalchemy import create_engine
from sqlalchemy.orm.session import sessionmaker
engine = create_engine('sqlite:////tmp/mydb.sqlite')
Session = sessionmaker(bind=engine)
mysession = Session()
# Here create model classes, for example User, Comment, etc.
...
# Create the API manager and create the APIs.
apimanager = APIManager(session=mysession)
apimanager.create_api(User)
apimanager.create_api(Comment)
# Later, call `init_app` to register the blueprints for the
# APIs created earlier.
app = Flask(__name__)
apimanager.init_app(app)
and with models defined with Flask-SQLAlchemy::
from flask import Flask
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
db = SQLALchemy(app)
# Here create model classes, for example User, Comment, etc.
...
# Create the API manager and create the APIs.
apimanager = APIManager(flask_sqlalchemy_db=db)
apimanager.create_api(User)
apimanager.create_api(Comment)
# Later, call `init_app` to register the blueprints for the
# APIs created earlier.
app = Flask(__name__)
apimanager.init_app(app)
"""
# Register any queued blueprints on the given application.
for blueprint in self.blueprints:
app.register_blueprint(blueprint)
# Create a view for the top-level endpoint that returns the schema.
blueprint = self._create_schema()
app.register_blueprint(blueprint)
def create_api_blueprint(self, name, model, methods=READONLY_METHODS,
url_prefix=None, collection_name=None,
allow_functions=False, only=None, exclude=None,
additional_attributes=None,
validation_exceptions=None, page_size=10,
max_page_size=100, preprocessors=None,
postprocessors=None, primary_key=None,
serializer_class=None, deserializer_class=None,
includes=None, allow_to_many_replacement=False,
allow_delete_from_to_many_relationships=False,
allow_client_generated_ids=False):
"""Creates and returns a ReSTful API interface as a blueprint, but does
not register it on any :class:`flask.Flask` application.
The endpoints for the API for ``model`` will be available at
``<url_prefix>/<collection_name>``. If `collection_name` is
``None``, the lowercase name of the provided model class will be
used instead, as accessed by ``model.__table__.name``. (If any
black magic was performed on ``model.__table__``, this will be
reflected in the endpoint URL.) For more information, see
:ref:`collectionname`.
This function must be called at most once for each model for which you
wish to create a ReSTful API. Its behavior (for now) is undefined if
called more than once.
This function returns the :class:`flask.Blueprint` object that handles
the endpoints for the model. The returned :class:`~flask.Blueprint` has
*not* been registered with the :class:`~flask.Flask` application
object specified in the constructor of this class, so you will need
to register it yourself to make it available on the application. If you
don't need access to the :class:`~flask.Blueprint` object, use
:meth:`create_api_blueprint` instead, which handles registration
automatically.
`name` is the name of the blueprint that will be created.
`model` is the SQLAlchemy model class for which a ReSTful interface
will be created.
`app` is the :class:`~flask.Flask` object on which we expect the
blueprint created in this method to be eventually registered. If
not specified, the Flask application specified in the
constructor of this class is used.
`methods` is a list of strings specifying the HTTP methods that
will be made available on the ReSTful API for the specified
model.
* If ``'GET'`` is in the list, :http:method:`get` requests will
be allowed at endpoints for collections of resources,
resources, to-many and to-one relations of resources, and
particular members of a to-many relation. Furthermore,
relationship information will be accessible. For more
information, see :doc:`fetching`.
* If ``'POST'`` is in the list, :http:method:`post` requests
will be allowed at endpoints for collections of resources. For
more information, see :doc:`creating`.
* If ``'DELETE'`` is in the list, :http:method:`delete` requests
will be allowed at endpoints for individual resources. For
more information, see :doc:`deleting`.
* If ``'PATCH'`` is in the list, :http:method:`patch` requests
will be allowed at endpoints for individual
resources. Replacing a to-many relationship when issuing a
request to update a resource can be enabled by setting
``allow_to_many_replacement`` to ``True``.
Furthermore, to-one relationships can be updated at
the relationship endpoints under an individual resource via
:http:method:`patch` requests. This also allows you to add to
a to-many relationship via the :http:method:`post` method,
delete from a to-many relationship via the
:http:method:`delete` method (if
``allow_delete_from_to_many_relationships`` is set to
``True``), and replace a to-many relationship via the
:http:method:`patch` method (if ``allow_to_many_replacement``
is set to ``True``). For more information, see :doc:`updating`
and :doc:`updatingrelationships`.
The default set of methods provides a read-only interface (that is,
only :http:method:`get` requests are allowed).
`url_prefix` is the URL prefix at which this API will be
accessible. For example, if this is set to ``'/foo'``, then this
method creates endpoints of the form
``/foo/<collection_name>``. If not set, the default URL prefix
specified in the constructor of this class will be used. If that
was not set either, the default ``'/api'`` will be used.
`collection_name` is the name of the collection specified by the
given model class to be used in the URL for the ReSTful API
created. If this is not specified, the lowercase name of the
model will be used. For example, if this is set to ``'foo'``,
then this method creates endpoints of the form ``/api/foo``,
``/api/foo/<id>``, etc.
If `allow_functions` is ``True``, then :http:method:`get`
requests to ``/api/eval/<collection_name>`` will return the
result of evaluating SQL functions specified in the body of the
request. For information on the request format, see
:doc:`functionevaluation`. This is ``False`` by default.
.. warning::
If ``allow_functions`` is ``True``, you must not create an
API for a model whose name is ``'eval'``.
If `only` is not ``None``, it must be a list of columns and/or
relationships of the specified `model`, given either as strings or as
the attributes themselves. If it is a list, only these fields will
appear in the resource object representation of an instance of `model`.
In other words, `only` is a whitelist of fields. The ``id`` and
``type`` elements of the resource object will always be present
regardless of the value of this argument. If `only` contains a string
that does not name a column in `model`, it will be ignored.
If `additional_attributes` is a list of strings, these
attributes of the model will appear in the JSON representation
of an instance of the model. This is useful if your model has an
attribute that is not a SQLAlchemy column but you want it to be
exposed. If any of the attributes does not exist on the model, a
:exc:`AttributeError` is raised.
If `exclude` is not ``None``, it must be a list of columns and/or
relationships of the specified `model`, given either as strings or as
the attributes themselves. If it is a list, all fields **except** these
will appear in the resource object representation of an instance of
`model`. In other words, `exclude` is a blacklist of fields. The ``id``
and ``type`` elements of the resource object will always be present
regardless of the value of this argument. If `exclude` contains a
string that does not name a column in `model`, it will be ignored.
If either `only` or `exclude` is not ``None``, exactly one of them must
be specified; if both are not ``None``, then this function will raise a
:exc:`IllegalArgumentError`.
See :doc:`sparse` for more information on specifying which fields will
be included in the resource object representation.
`validation_exceptions` is the tuple of possible exceptions raised by
validation of your database models. If this is specified, validation
errors will be captured and forwarded to the client in the format
described by the JSON API specification. For more information on how to
use validation, see :ref:`validation`.
`page_size` must be a positive integer that represents the default page
size for responses that consist of a collection of resources. Requests
made by clients may override this default by specifying ``page_size``
as a query parameter. `max_page_size` must be a positive integer that
represents the maximum page size that a client can request. Even if a
client specifies that greater than `max_page_size` should be returned,
at most `max_page_size` results will be returned. For more information,
see :doc:`pagination`.
`serializer_class` and `deserializer_class` are custom
serializer and deserializer classes. The former must be a
subclass of :class:`DefaultSerializer` and the latter a subclass
of :class:`DefaultDeserializer`. For more information on using
these, see :doc:`serialization`.
`preprocessors` is a dictionary mapping strings to lists of
functions. Each key represents a type of endpoint (for example,
``'GET_RESOURCE'`` or ``'GET_COLLECTION'``). Each value is a list of
functions, each of which will be called before any other code is
executed when this API receives the corresponding HTTP request. The
functions will be called in the order given here. The `postprocessors`
keyword argument is essentially the same, except the given functions
are called after all other code. For more information on preprocessors
and postprocessors, see :doc:`processors`.
`primary_key` is a string specifying the name of the column of `model`
to use as the primary key for the purposes of creating URLs. If the
`model` has exactly one primary key, there is no need to provide a
value for this. If `model` has two or more primary keys, you must
specify which one to use. For more information, see :ref:`primarykey`.
`includes` must be a list of strings specifying which related resources
will be included in a compound document by default when fetching a
resource object representation of an instance of `model`. Each element
of `includes` is the name of a field of `model` (that is, either an
attribute or a relationship). For more information, see
:doc:`includes`.
If `allow_to_many_replacement` is ``True`` and this API allows
:http:method:`patch` requests, the server will allow two types
of requests. First, it allows the client to replace the entire
collection of resources in a to-many relationship when updating
an individual instance of the model. Second, it allows the
client to replace the entire to-many relationship when making a
:http:method:`patch` request to a to-many relationship endpoint.
This is ``False`` by default. For more information, see
:doc:`updating` and :doc:`updatingrelationships`.
If `allow_delete_from_to_many_relationships` is ``True`` and
this API allows :http:method:`patch` requests, the server will
allow the client to delete resources from any to-many
relationship of the model. This is ``False`` by default. For
more information, see :doc:`updatingrelationships`.
If `allow_client_generated_ids` is ``True`` and this API allows
:http:method:`post` requests, the server will allow the client to
specify the ID for the resource to create. JSON API recommends that
this be a UUID. This is ``False`` by default. For more information, see
:doc:`creating`.
"""
# Perform some sanity checks on the provided keyword arguments.
if only is not None and exclude is not None:
msg = 'Cannot simultaneously specify both `only` and `exclude`'
raise IllegalArgumentError(msg)
if collection_name == '':
msg = 'Collection name must be nonempty'
raise IllegalArgumentError(msg)
if collection_name is None:
# If the model is polymorphic in a single table inheritance
# scenario, this should *not* be the tablename, but perhaps
# the polymorphic identity?
mapper = inspect(model)
if mapper.polymorphic_identity is not None:
collection_name = mapper.polymorphic_identity
else:
collection_name = model.__table__.name
# convert all method names to upper case
methods = frozenset((m.upper() for m in methods))
# the name of the API, for use in creating the view and the blueprint
apiname = APIManager.api_name(collection_name)
# Prepend the universal preprocessors and postprocessors specified in
# the constructor of this class.
preprocessors_ = defaultdict(list)
postprocessors_ = defaultdict(list)
preprocessors_.update(preprocessors or {})
postprocessors_.update(postprocessors or {})
for key, value in self.pre.items():
preprocessors_[key] = value + preprocessors_[key]
for key, value in self.post.items():
postprocessors_[key] = value + postprocessors_[key]
# Validate that all the additional attributes exist on the model.
if additional_attributes is not None:
for attr in additional_attributes:
if isinstance(attr, STRING_TYPES) and not hasattr(model, attr):
msg = 'no attribute "{0}" on model {1}'.format(attr, model)
raise AttributeError(msg)
if (additional_attributes is not None and exclude is not None and
any(attr in exclude for attr in additional_attributes)):
msg = ('Cannot exclude attributes listed in the'
' `additional_attributes` keyword argument')
raise IllegalArgumentError(msg)
# Create a default serializer and deserializer if none have been
# provided.
if serializer_class is None:
serializer_class = DefaultSerializer
if deserializer_class is None:
deserializer_class = DefaultDeserializer
# Instantiate the serializer and deserializer.
attrs = additional_attributes
serializer = serializer_class(only=only, exclude=exclude,
additional_attributes=attrs)
acgi = allow_client_generated_ids
deserializer = deserializer_class(self.session, model,
allow_client_generated_ids=acgi)
# Create the view function for the API for this model.
#
# Rename some variables with long names for the sake of brevity.
atmr = allow_to_many_replacement
api_view = API.as_view(apiname, self.session, model,
preprocessors=preprocessors_,
postprocessors=postprocessors_,
primary_key=primary_key,
validation_exceptions=validation_exceptions,
allow_to_many_replacement=atmr,
page_size=page_size,
max_page_size=max_page_size,
serializer=serializer,
deserializer=deserializer,
includes=includes)
# add the URL rules to the blueprint: the first is for methods on the
# collection only, the second is for methods which may or may not
# specify an instance, the third is for methods which must specify an
# instance
# TODO what should the second argument here be?
# TODO should the url_prefix be specified here or in register_blueprint
if url_prefix is not None:
prefix = url_prefix
elif self.url_prefix is not None:
prefix = self.url_prefix
else:
prefix = DEFAULT_URL_PREFIX
blueprint = Blueprint(name, __name__, url_prefix=prefix)
add_rule = blueprint.add_url_rule
# The URLs that will be routed below.
collection_url = '/{0}'.format(collection_name)
resource_url = '{0}/<resource_id>'.format(collection_url)
related_resource_url = '{0}/<relation_name>'.format(resource_url)
to_many_resource_url = \
'{0}/<related_resource_id>'.format(related_resource_url)
relationship_url = \
'{0}/relationships/<relation_name>'.format(resource_url)
# Create relationship URL endpoints.
#
# Due to a limitation in Flask's routing (which is actually
# Werkzeug's routing), this needs to be declared *before* the
# rest of the API views. Otherwise, requests like
# :http:get:`/api/articles/1/relationships/author` interpret the
# word `relationships` as the name of a relation of an article
# object.
relationship_api_name = '{0}.relationships'.format(apiname)
rapi_view = RelationshipAPI.as_view
adftmr = allow_delete_from_to_many_relationships
relationship_api_view = \
rapi_view(relationship_api_name, self.session, model,
# Keyword arguments for APIBase.__init__()
preprocessors=preprocessors_,
postprocessors=postprocessors_,
primary_key=primary_key,
validation_exceptions=validation_exceptions,
allow_to_many_replacement=allow_to_many_replacement,
# Keyword arguments RelationshipAPI.__init__()
allow_delete_from_to_many_relationships=adftmr)
# When PATCH is allowed, certain non-PATCH requests are allowed
# on relationship URLs.
relationship_methods = READONLY_METHODS & methods
if 'PATCH' in methods:
relationship_methods |= WRITEONLY_METHODS
add_rule(relationship_url, methods=relationship_methods,
view_func=relationship_api_view)
# The URL for accessing the entire collection. (POST is special because
# the :meth:`API.post` method doesn't have any arguments.)
#
# For example, /api/people.
collection_methods = frozenset(('POST', )) & methods
add_rule(collection_url, view_func=api_view,
methods=collection_methods)
collection_methods = frozenset(('GET', )) & methods
collection_defaults = dict(resource_id=None, relation_name=None,
related_resource_id=None)
add_rule(collection_url, view_func=api_view,
methods=collection_methods, defaults=collection_defaults)
# The URL for accessing a single resource. (DELETE and PATCH are
# special because the :meth:`API.delete` and :meth:`API.patch` methods
# don't have the `relationname` and `relationinstid` arguments.)
#
# For example, /api/people/1.
resource_methods = frozenset(('DELETE', 'PATCH')) & methods
add_rule(resource_url, view_func=api_view, methods=resource_methods)
resource_methods = READONLY_METHODS & methods
resource_defaults = dict(relation_name=None, related_resource_id=None)
add_rule(resource_url, view_func=api_view, methods=resource_methods,
defaults=resource_defaults)
# The URL for accessing a related resource, which may be a to-many or a
# to-one relationship.
#
# For example, /api/people/1/articles.
related_resource_methods = READONLY_METHODS & methods
related_resource_defaults = dict(related_resource_id=None)
add_rule(related_resource_url, view_func=api_view,
methods=related_resource_methods,
defaults=related_resource_defaults)
# The URL for accessing a to-many related resource.
#
# For example, /api/people/1/articles/1.
to_many_resource_methods = READONLY_METHODS & methods
add_rule(to_many_resource_url, view_func=api_view,
methods=to_many_resource_methods)
# if function evaluation is allowed, add an endpoint at /api/eval/...
# which responds only to GET requests and responds with the result of
# evaluating functions on all instances of the specified model
if allow_functions:
eval_api_name = '{0}.eval'.format(apiname)
eval_api_view = FunctionAPI.as_view(eval_api_name, self.session,
model)
eval_endpoint = '/eval{0}'.format(collection_url)
eval_methods = ['GET']
blueprint.add_url_rule(eval_endpoint, methods=eval_methods,
view_func=eval_api_view)
# Finally, record that this APIManager instance has created an API for
# the specified model.
self.created_apis_for[model] = APIInfo(collection_name, blueprint.name,
serializer, primary_key)
self.models.add(model)
return blueprint
def create_api(self, *args, **kw):
"""Creates and possibly registers a ReSTful API blueprint for
the given SQLAlchemy model.
If a Flask application was provided in the constructor of this
class, the created blueprint is immediately registered on that
application. Otherwise, the blueprint is stored for later
registration when the :meth:`init_app` method is invoked. In
that case, the blueprint will be registered each time the
:meth:`init_app` method is invoked.
The keyword arguments for this method are exactly the same as
those for :meth:`create_api_blueprint`, and are passed directly
to that method. However, unlike that method, this method accepts
only a single positional argument, `model`, the SQLAlchemy model
for which to create the API. A UUID will be automatically
generated for the blueprint name.
For example, if you only wish to create APIs on a single Flask
application::
app = Flask(__name__)
session = ... # create the SQLAlchemy session
manager = APIManager(app=app, session=session)
manager.create_api(User)
If you want to create APIs before having access to a Flask
application, you can call this method before calling
:meth:`init_app`::
session = ... # create the SQLAlchemy session
manager = APIManager(session=session)
manager.create_api(User)
# later...
app = Flask(__name__)
manager.init_app(app)
If you want to create an API and register it on multiple Flask
applications, you can call this method once and :meth:`init_app`
multiple times with different `app` arguments::
session = ... # create the SQLAlchemy session
manager = APIManager(session=session)
manager.create_api(User)
# later...
app1 = Flask('application1')
app2 = Flask('application2')
manager.init_app(app1)
manager.init_app(app2)
"""
blueprint_name = str(uuid1())
blueprint = self.create_api_blueprint(blueprint_name, *args, **kw)
# Store the created blueprint
self.blueprints.append(blueprint)
# If a Flask application was provided in the constructor of this
# API manager, then immediately register the blueprint on that
# application.
if self.app is not None:
self.app.register_blueprint(blueprint)
# If this is the first blueprint, create a schema
# endpoint. It will be updated indirectly each time
# `create_api_blueprint` is called, so it is not necessary
# to make any further modifications to the registered
# blueprint.
if len(self.blueprints) == 1:
blueprint = self._create_schema()
self.app.register_blueprint(blueprint)
| 41,419
|
Python
|
.py
| 762
| 44.267717
| 79
| 0.65379
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,619
|
__init__.py
|
jfinkels_flask-restless/flask_restless/__init__.py
|
# __init__.py - indicates that this directory is a Python package
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Provides classes for creating endpoints for interacting with
SQLAlchemy models via the JSON API protocol.
"""
# The following names are available as part of the public API for
# Flask-Restless. End users of this package can import these names by doing
# ``from flask_restless import APIManager``, for example.
from .helpers import collection_name
from .helpers import model_for
from .helpers import serializer_for
from .helpers import url_for
from .helpers import primary_key_for
from .manager import APIManager
from .manager import IllegalArgumentError
from .serialization import DefaultDeserializer
from .serialization import DefaultSerializer
from .serialization import DeserializationException
from .serialization import MultipleExceptions
from .serialization import SerializationException
from .serialization import simple_serialize
from .serialization import simple_serialize_many
from .search import register_operator
from .views import JSONAPI_MIMETYPE
from .views import ProcessingException
#: The current version of this extension.
#:
#: This should be the same as the version specified in the :file:`setup.py`
#: file.
__version__ = '1.0.0b2-dev'
__all__ = [
'APIManager',
'collection_name',
'DefaultDeserializer',
'DefaultSerializer',
'DeserializationException',
'IllegalArgumentError',
'JSONAPI_MIMETYPE',
'model_for',
'MultipleExceptions',
'primary_key_for',
'ProcessingException',
'register_operator',
'SerializationException',
'serializer_for',
'simple_serialize',
'simple_serialize_many',
'url_for',
]
| 2,069
|
Python
|
.py
| 58
| 33.448276
| 75
| 0.782869
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,620
|
helpers.py
|
jfinkels_flask-restless/flask_restless/helpers.py
|
# helpers.py - helper functions for Flask-Restless
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Helper functions for Flask-Restless.
Many of the functions in this module use the `SQLAlchemy inspection
API`_. As a rule, however, these functions do not catch
:exc:`sqlalchemy.exc.NoInspectionAvailable` exceptions; the
responsibility is on the calling function to ensure that functions that
expect, for example, a SQLAlchemy model actually receive a SQLAlchemy
model.
.. _SQLAlchemy inspection API:
https://docs.sqlalchemy.org/en/latest/core/inspection.html
"""
import datetime
import inspect
from dateutil.parser import parse as parse_datetime
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import Interval
from sqlalchemy import Time
from sqlalchemy.exc import NoInspectionAvailable
from sqlalchemy.ext.associationproxy import AssociationProxy
from sqlalchemy.orm import RelationshipProperty
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import ColumnElement
from sqlalchemy.inspection import inspect as sqlalchemy_inspect
from werkzeug.urls import url_quote_plus
#: Strings which, when received by the server as the value of a date or time
#: field, indicate that the server should use the current time when setting the
#: value of the field.
CURRENT_TIME_MARKERS = ('CURRENT_TIMESTAMP', 'CURRENT_DATE', 'LOCALTIMESTAMP')
def session_query(session, model):
"""Returns a SQLAlchemy query object for the specified `model`.
If `model` has a ``query`` attribute already, ``model.query`` will be
returned. If the ``query`` attribute is callable ``model.query()`` will be
returned instead.
If `model` has no such attribute, a query based on `session` will be
created and returned.
"""
if hasattr(model, 'query'):
if callable(model.query):
query = model.query()
else:
query = model.query
if hasattr(query, 'filter'):
return query
return session.query(model)
def assoc_proxy_scalar_collections(model):
"""Yields the name of each association proxy collection as a string.
This includes each association proxy that proxies to a scalar
collection (for example, a list of strings) via an association
table. It excludes each association proxy that proxies to a
collection of instances (for example, a to-many relationship) via an
association object.
.. seealso::
:func:`scalar_collection_proxied_relations`
.. versionadded:: 1.0.0
"""
mapper = sqlalchemy_inspect(model)
for k, v in mapper.all_orm_descriptors.items():
if isinstance(v, AssociationProxy) \
and not isinstance(v.remote_attr.property, RelationshipProperty) \
and is_like_list(model, v.local_attr.key):
yield k
def get_relations(model):
"""Yields the name of each relationship of a model as a string.
For a relationship via an association proxy, this function shows
only the remote attribute, not the intermediate relationship. For
example, if there is a table for ``Article`` and ``Tag`` and a table
associating the two via a many-to-many relationship, ::
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Article(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
articletags = relationship('ArticleTag')
tags = association_proxy('articletags', 'tag',
creator=lambda tag: ArticleTag(tag=tag))
class ArticleTag(Base):
__tablename__ = 'articletag'
article_id = Column(Integer, ForeignKey('article.id'),
primary_key=True)
tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True)
tag = relationship('Tag')
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
then this function reveals the ``tags`` proxy::
>>> list(get_relations(Article))
['tags']
Similarly, for association proxies that proxy to a scalar collection
via an association table, this will show the related model. For
example, if there is an association proxy for a scalar collection
like this::
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Article(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
tags = relationship('Tag', secondary=lambda: articletags_table)
tag_names = association_proxy('tags', 'name',
creator=lambda s: Tag(name=s))
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
articletags_table = \
Table('articletags', Base.metadata,
Column('article_id', Integer, ForeignKey('article.id'),
primary_key=True),
Column('tag_id', Integer, ForeignKey('tag.id'),
primary_key=True)
)
then this function yields only the ``tags`` relationship, not the
``tag_names`` attribute::
>>> list(get_relations(Article))
['tags']
"""
mapper = sqlalchemy_inspect(model)
# If we didn't have to deal with association proxies, we could just
# do `return list(mapper.relationships)`.
#
# However, we need to deal with (at least) two different usages of
# association proxies: one in which the proxy is to a scalar
# collection (like a list of strings) and one in which the proxy is
# to a collection of instances (like a to-many relationship).
#
# First we record each association proxy and the the local attribute
# through which it proxies. This information is stored in a mapping
# from local attribute key to proxy name. For example, an
# association proxy defined like this::
#
# tags = associationproxy('articletags', 'tag')
#
# is stored below as a dictionary entry mapping 'articletags' to
# 'tags'.
association_proxies = {}
for k, v in mapper.all_orm_descriptors.items():
if isinstance(v, AssociationProxy):
association_proxies[v.local_attr.key] = k
# Next we determine which association proxies represent scalar
# collections as opposed to to-many relationships. We need to ignore
# these.
scalar_collections = set(assoc_proxy_scalar_collections(model))
# Finally we find all plain old relationships and all association
# proxy relationships.
#
# If the association proxy is through an association object, we
# yield that too.
for r in mapper.relationships.keys():
yield r
proxy = association_proxies.get(r)
if proxy is not None and proxy not in scalar_collections:
yield association_proxies[r]
def get_related_model(model, relationname):
"""Gets the class of the model to which `model` is related by the attribute
whose name is `relationname`.
For example, if we have the model classes ::
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
articles = relationship('Article')
class Article(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
then ::
>>> get_related_model(Person, 'articles')
<class 'Article'>
>>> get_related_model(Article, 'author')
<class 'Person'>
This function also "sees through" association proxies and returns
the model of the proxied remote relation.
"""
mapper = sqlalchemy_inspect(model)
attribute = mapper.all_orm_descriptors[relationname]
# HACK This is required for Python 3.3 only. I'm guessing it lazily
# loads the attribute or something like that.
hasattr(model, relationname)
return get_related_model_from_attribute(attribute)
def get_related_model_from_attribute(attribute):
"""Gets the class of the model related to the given attribute via
the given name.
`attribute` may be an
:class:`~sqlalchemy.orm.attributes.InstrumentedAttribute` or an
:class:`~sqlalchemy.ext.associationproxy.AssociationProxy`, for
example ``Article.comments`` or ``Comment.tags``. This function
"sees through" association proxies to return the model of the
proxied remote relation.
"""
if isinstance(attribute, AssociationProxy):
return attribute.remote_attr.mapper.class_
return attribute.property.mapper.class_
def foreign_key_columns(model):
"""Returns a list of the :class:`sqlalchemy.Column` objects that contain
foreign keys for relationships in the specified model class.
"""
mapper = sqlalchemy_inspect(model)
return [c for c in mapper.columns if c.foreign_keys]
def foreign_keys(model):
"""Returns a list of the names of columns that contain foreign keys for
relationships in the specified model class.
"""
return [column.name for column in foreign_key_columns(model)]
def has_field(model, fieldname):
"""Returns ``True`` if the `model` has the specified field or if it has a
settable hybrid property for this field name.
"""
mapper = sqlalchemy_inspect(model)
# Get all descriptors, which include columns, relationships, and
# other things like association proxies and hybrid properties.
descriptors = mapper.all_orm_descriptors
if fieldname not in descriptors:
return False
field = descriptors[fieldname]
# First, we check whether `fieldname` specifies a settable hybrid
# property. This is a bit flimsy: we check whether the `fset`
# attribute has been set on the `hybrid_property` instance. The
# `fset` instance attribute is only set if the user defined a hybrid
# property setter.
if hasattr(field, 'fset'):
return field.fset is not None
# At this point, we simply check that the attribute is not callable.
return not callable(getattr(model, fieldname))
def is_relationship(model, fieldname):
"""Decides whether a field is a relationship (as opposed to a
field).
`model` is a SQLAlchemy model.
`fieldname` is a string naming a field of the given model. This
function returns True if and only if the field is a relationship.
This function currently does *not* return `True` for association
proxies.
"""
mapper = sqlalchemy_inspect(model)
return fieldname in mapper.relationships
def get_field_type(model, fieldname):
"""Returns the SQLAlchemy type of the field.
This works for plain columns and association proxies. If `fieldname`
specifies a hybrid property, this function returns `None`.
"""
field = getattr(model, fieldname)
if isinstance(field, ColumnElement):
return field.type
if isinstance(field, AssociationProxy):
field = field.remote_attr
if hasattr(field, 'property'):
prop = field.property
if isinstance(prop, RelationshipProperty):
return None
return prop.columns[0].type
return None
def primary_key_names(model):
"""Returns a list of all the primary keys for a model.
The returned list contains the name of each primary key as a string.
"""
mapper = sqlalchemy_inspect(model)
return [column.name for column in mapper.primary_key]
def primary_key_value(instance, as_string=False):
"""Returns the value of the primary key field of the specified `instance`
of a SQLAlchemy model.
This essentially a convenience function for::
getattr(instance, primary_key_for(instance))
If `as_string` is ``True``, try to coerce the return value to a string.
"""
result = getattr(instance, primary_key_for(instance))
if not as_string:
return result
try:
return str(result)
except UnicodeEncodeError:
return url_quote_plus(result.encode('utf-8'))
def is_like_list(model_or_instance, relationname):
"""Decides whether a relation of a SQLAlchemy model is list-like.
A relation may be like a list if it behaves like a to-many relation
(either lazy or eager)
`model_or_instance` may be either a SQLAlchemy model class or an
instance of such a class.
`relationname` is a string naming a relationship of the given
model or instance.
"""
# Use Python's built-in inspect module to decide whether the
# argument is a model or an instance of a model.
if not inspect.isclass(model_or_instance):
model = get_model(model_or_instance)
else:
model = model_or_instance
mapper = sqlalchemy_inspect(model)
relation = mapper.all_orm_descriptors[relationname]
if isinstance(relation, AssociationProxy):
relation = relation.local_attr
return relation.property.uselist
def is_mapped_class(cls):
"""Returns ``True`` if and only if the specified SQLAlchemy model class is
a mapped class.
"""
try:
sqlalchemy_inspect(cls)
except NoInspectionAvailable:
return False
else:
return True
def query_by_primary_key(session, model, pk_value, primary_key=None):
"""Returns a SQLAlchemy query object containing the result of querying
`model` for instances whose primary key has the value `pk_value`.
If `primary_key` is specified, the column specified by that string is used
as the primary key column. Otherwise, the column named ``id`` is used.
Presumably, the returned query should have at most one element.
"""
pk_name = primary_key or primary_key_for(model)
query = session_query(session, model)
return query.filter(getattr(model, pk_name) == pk_value)
def get_by(session, model, pk_value, primary_key=None):
"""Returns the first instance of `model` whose primary key has the value
`pk_value`, or ``None`` if no such instance exists.
If `primary_key` is specified, the column specified by that string is used
as the primary key column. Otherwise, the column named ``id`` is used.
"""
result = query_by_primary_key(session, model, pk_value, primary_key)
return result.first()
def string_to_datetime(model, fieldname, value):
"""Casts `value` to a :class:`datetime.datetime` or
:class:`datetime.timedelta` object if the given field of the given
model is a date-like or interval column.
If the field name corresponds to a field in the model which is a
:class:`sqlalchemy.types.Date`, :class:`sqlalchemy.types.DateTime`,
or :class:`sqlalchemy.Interval`, then the returned value will be the
:class:`datetime.datetime` or :class:`datetime.timedelta` Python
object corresponding to `value`. Otherwise, the `value` is returned
unchanged.
"""
if value is None:
return value
# If this is a date, time or datetime field, parse it and convert it to
# the appropriate type.
field_type = get_field_type(model, fieldname)
if isinstance(field_type, (Date, Time, DateTime)):
# If the string is empty, no datetime can be inferred from it.
if value.strip() == '':
return None
# If the string is a string indicating that the value of should be the
# current datetime on the server, get the current datetime that way.
if value in CURRENT_TIME_MARKERS:
return getattr(func, value.lower())()
value_as_datetime = parse_datetime(value)
# If the attribute on the model needs to be a Date or Time object as
# opposed to a DateTime object, just get the date component of the
# datetime.
if isinstance(field_type, Date):
return value_as_datetime.date()
if isinstance(field_type, Time):
return value_as_datetime.timetz()
return value_as_datetime
# If this is an Interval field, convert the integer value to a timedelta.
if isinstance(field_type, Interval) and isinstance(value, int):
return datetime.timedelta(seconds=value)
# In any other case, simply copy the value unchanged.
return value
def get_model(instance):
"""Returns the model class of which the specified object is an instance."""
return type(instance)
# This code comes from <http://stackoverflow.com/a/6798042/108197>, which is
# licensed under the Creative Commons Attribution-ShareAlike License version
# 3.0 Unported.
#
# That is an answer originally authored by the user
# <http://stackoverflow.com/users/500584/agf> to the question
# <http://stackoverflow.com/q/6760685/108197>.
#
# TODO This code is for simultaneous Python 2 and 3 usage. It can be greatly
# simplified when removing Python 2 support.
class _Singleton(type):
"""A metaclass for a singleton class."""
#: The known instances of the class instantiating this metaclass.
_instances = {}
def __call__(cls, *args, **kwargs):
"""Returns the singleton instance of the specified class."""
if cls not in cls._instances:
supercls = super(_Singleton, cls)
cls._instances[cls] = supercls.__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(_Singleton('SingletonMeta', (object,), {})):
"""Base class for a singleton class."""
pass
class KnowsAPIManagers:
"""An object that allows client code to register :class:`APIManager`
objects.
"""
def __init__(self):
#: A global list of created :class:`APIManager` objects.
self.created_managers = set()
def register(self, apimanager):
"""Inform this object about the specified :class:`APIManager` object.
"""
self.created_managers.add(apimanager)
class ModelFinder(KnowsAPIManagers, Singleton):
"""The singleton class that backs the :func:`model_for` function."""
def __call__(self, resource_type, _apimanager=None, **kw):
if _apimanager is not None:
# This may raise ValueError.
return _apimanager.model_for(resource_type, **kw)
for manager in self.created_managers:
try:
return self(resource_type, _apimanager=manager, **kw)
except ValueError:
pass
message = ('No model with collection name {0} is known to any'
' APIManager objects; maybe you have not set the'
' `collection_name` keyword argument when calling'
' `APIManager.create_api()`?').format(resource_type)
raise ValueError(message)
class CollectionNameFinder(KnowsAPIManagers, Singleton):
"""The singleton class that backs the :func:`collection_name` function."""
def __call__(self, model, _apimanager=None, **kw):
if _apimanager is not None:
if model not in _apimanager.created_apis_for:
message = ('APIManager {0} has not created an API for model '
' {1}').format(_apimanager, model)
raise ValueError(message)
return _apimanager.collection_name(model, **kw)
for manager in self.created_managers:
try:
return self(model, _apimanager=manager, **kw)
except ValueError:
pass
message = ('Model {0} is not known to any APIManager'
' objects; maybe you have not called'
' APIManager.create_api() for this model.').format(model)
raise ValueError(message)
class UrlFinder(KnowsAPIManagers, Singleton):
"""The singleton class that backs the :func:`url_for` function."""
def __call__(self, model, resource_id=None, relation_name=None,
related_resource_id=None, _apimanager=None,
relationship=False, **kw):
if _apimanager is not None:
if model not in _apimanager.created_apis_for:
message = ('APIManager {0} has not created an API for model '
' {1}; maybe another APIManager instance'
' did?').format(_apimanager, model)
raise ValueError(message)
return _apimanager.url_for(model, resource_id=resource_id,
relation_name=relation_name,
related_resource_id=related_resource_id,
relationship=relationship, **kw)
for manager in self.created_managers:
try:
return self(model, resource_id=resource_id,
relation_name=relation_name,
related_resource_id=related_resource_id,
relationship=relationship, _apimanager=manager,
**kw)
except ValueError:
pass
message = ('Model {0} is not known to any APIManager'
' objects; maybe you have not called'
' APIManager.create_api() for this model.').format(model)
raise ValueError(message)
class SerializerFinder(KnowsAPIManagers, Singleton):
"""The singleton class that backs the :func:`serializer_for` function."""
def __call__(self, model, _apimanager=None, **kw):
if _apimanager is not None:
if model not in _apimanager.created_apis_for:
message = ('APIManager {0} has not created an API for model '
' {1}').format(_apimanager, model)
raise ValueError(message)
return _apimanager.serializer_for(model, **kw)
for manager in self.created_managers:
try:
return self(model, _apimanager=manager, **kw)
except ValueError:
pass
message = ('Model {0} is not known to any APIManager'
' objects; maybe you have not called'
' APIManager.create_api() for this model.').format(model)
raise ValueError(message)
class PrimaryKeyFinder(KnowsAPIManagers, Singleton):
"""The singleton class that backs the :func:`primary_key_for` function."""
def __call__(self, instance_or_model, _apimanager=None, **kw):
if isinstance(instance_or_model, type):
model = instance_or_model
else:
model = instance_or_model.__class__
if _apimanager is not None:
managers_to_search = [_apimanager]
else:
managers_to_search = self.created_managers
for manager in managers_to_search:
if model in manager.created_apis_for:
primary_key = manager.primary_key_for(model, **kw)
break
else:
message = ('Model "{0}" is not known to {1}; maybe you have not'
' called APIManager.create_api() for this model?')
if _apimanager is not None:
manager_string = 'APIManager "{0}"'.format(_apimanager)
else:
manager_string = 'any APIManager objects'
message = message.format(model, manager_string)
raise ValueError(message)
# If `APIManager.create_api(model)` was called without providing
# a value for the `primary_key` keyword argument, then we must
# compute the primary key name from the model directly.
if primary_key is None:
pk_names = primary_key_names(model)
primary_key = 'id' if 'id' in pk_names else pk_names[0]
return primary_key
#: Returns the URL for the specified model, similar to :func:`flask.url_for`.
#:
#: `model` is a SQLAlchemy model class. This should be a model on which
#: :meth:`APIManager.create_api_blueprint` (or :meth:`APIManager.create_api`)
#: has been invoked previously. If no API has been created for it, this
#: function raises a `ValueError`.
#:
#: If `_apimanager` is not ``None``, it must be an instance of
#: :class:`APIManager`. Restrict our search for endpoints exposing `model` to
#: only endpoints created by the specified :class:`APIManager` instance.
#:
#: The `resource_id`, `relation_name`, and `relationresource_id` keyword
#: arguments allow you to get the URL for a more specific sub-resource.
#:
#: For example, suppose you have a model class ``Person`` and have created the
#: appropriate Flask application and SQLAlchemy session::
#:
#: >>> manager = APIManager(app, session=session)
#: >>> manager.create_api(Person, collection_name='people')
#: >>> url_for(Person, resource_id=3)
#: 'http://example.com/api/people/3'
#: >>> url_for(Person, resource_id=3, relation_name=computers)
#: 'http://example.com/api/people/3/computers'
#: >>> url_for(Person, resource_id=3, relation_name=computers,
#: ... related_resource_id=9)
#: 'http://example.com/api/people/3/computers/9'
#:
#: If a `resource_id` and a `relation_name` are provided, and you wish
#: to determine the relationship endpoint URL instead of the related
#: resource URL, set the `relationship` keyword argument to ``True``::
#:
#: >>> url_for(Person, resource_id=3, relation_name=computers,
#: ... relationship=True)
#: 'http://example.com/api/people/3/relatonships/computers'
#:
#: The remaining keyword arguments, `kw`, are passed directly on to
#: :func:`flask.url_for`.
#:
#: Since this function creates absolute URLs to resources linked to the given
#: instance, it must be called within a `Flask request context`_.
#:
#: .. _Flask request context: http://flask.pocoo.org/docs/0.10/reqcontext/
#:
url_for = UrlFinder()
#: Returns the collection name for the specified model, as specified by the
#: ``collection_name`` keyword argument to :meth:`APIManager.create_api` when
#: it was previously invoked on the model.
#:
#: `model` is a SQLAlchemy model class. This should be a model on which
#: :meth:`APIManager.create_api_blueprint` (or :meth:`APIManager.create_api`)
#: has been invoked previously. If no API has been created for it, this
#: function raises a `ValueError`.
#:
#: If `_apimanager` is not ``None``, it must be an instance of
#: :class:`APIManager`. Restrict our search for endpoints exposing `model` to
#: only endpoints created by the specified :class:`APIManager` instance.
#:
#: For example, suppose you have a model class ``Person`` and have created the
#: appropriate Flask application and SQLAlchemy session::
#:
#: >>> from mymodels import Person
#: >>> manager = APIManager(app, session=session)
#: >>> manager.create_api(Person, collection_name='people')
#: >>> collection_name(Person)
#: 'people'
#:
#: This function is the inverse of :func:`model_for`::
#:
#: >>> manager.collection_name(manager.model_for('people'))
#: 'people'
#: >>> manager.model_for(manager.collection_name(Person))
#: <class 'mymodels.Person'>
#:
collection_name = CollectionNameFinder()
#: Returns the callable serializer object for the specified model, as
#: specified by the `serializer` keyword argument to
#: :meth:`APIManager.create_api` when it was previously invoked on the
#: model.
#:
#: `model` is a SQLAlchemy model class. This should be a model on which
#: :meth:`APIManager.create_api_blueprint` (or :meth:`APIManager.create_api`)
#: has been invoked previously. If no API has been created for it, this
#: function raises a `ValueError`.
#:
#: If `_apimanager` is not ``None``, it must be an instance of
#: :class:`APIManager`. Restrict our search for endpoints exposing
#: `model` to only endpoints created by the specified
#: :class:`APIManager` instance.
#:
#: For example, suppose you have a model class ``Person`` and have
#: created the appropriate Flask application and SQLAlchemy session::
#:
#: >>> from mymodels import Person
#: >>> def my_serializer(model, *args, **kw):
#: ... # return something cool here...
#: ... return {}
#: ...
#: >>> manager = APIManager(app, session=session)
#: >>> manager.create_api(Person, serializer=my_serializer)
#: >>> serializer_for(Person)
#: <function my_serializer at 0x...>
#:
serializer_for = SerializerFinder()
#: Returns the model corresponding to the given collection name, as specified
#: by the ``collection_name`` keyword argument to :meth:`APIManager.create_api`
#: when it was previously invoked on the model.
#:
#: `collection_name` is a string corresponding to the "type" of a model. This
#: should be a model on which :meth:`APIManager.create_api_blueprint` (or
#: :meth:`APIManager.create_api`) has been invoked previously. If no API has
#: been created for it, this function raises a `ValueError`.
#:
#: If `_apimanager` is not ``None``, it must be an instance of
#: :class:`APIManager`. Restrict our search for endpoints exposing `model` to
#: only endpoints created by the specified :class:`APIManager` instance.
#:
#: For example, suppose you have a model class ``Person`` and have created the
#: appropriate Flask application and SQLAlchemy session::
#:
#: >>> from mymodels import Person
#: >>> manager = APIManager(app, session=session)
#: >>> manager.create_api(Person, collection_name='people')
#: >>> model_for('people')
#: <class 'mymodels.Person'>
#:
#: This function is the inverse of :func:`collection_name`::
#:
#: >>> manager.collection_name(manager.model_for('people'))
#: 'people'
#: >>> manager.model_for(manager.collection_name(Person))
#: <class 'mymodels.Person'>
#:
model_for = ModelFinder()
#: Returns the primary key to be used for the given model or model instance,
#: as specified by the ``primary_key`` keyword argument to
#: :meth:`APIManager.create_api` when it was previously invoked on the model.
#:
#: `primary_key` is a string corresponding to the primary key identifier
#: to be used by flask-restless for a model. If no primary key has been set
#: at the flask-restless level (by using the ``primary_key`` keyword argument
#: when calling :meth:`APIManager.create_api_blueprint`, the model's primary
#: key will be returned. If no API has been created for the model, this
#: function raises a `ValueError`.
#:
#: If `_apimanager` is not ``None``, it must be an instance of
#: :class:`APIManager`. Restrict our search for endpoints exposing `model` to
#: only endpoints created by the specified :class:`APIManager` instance.
#:
#: For example, suppose you have a model class ``Person`` and have created the
#: appropriate Flask application and SQLAlchemy session::
#:
#: >>> from mymodels import Person
#: >>> manager = APIManager(app, session=session)
#: >>> manager.create_api(Person, primary_key='name')
#: >>> primary_key_for(Person)
#: 'name'
#: >>> my_person = Person(name="Bob")
#: >>> primary_key_for(my_person)
#: 'name'
#:
#: This is in contrast to the typical default:
#:
#: >>> manager = APIManager(app, session=session)
#: >>> manager.create_api(Person)
#: >>> primary_key_for(Person)
#: 'id'
#:
primary_key_for = PrimaryKeyFinder()
| 32,023
|
Python
|
.py
| 691
| 39.892909
| 79
| 0.675205
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,621
|
serializers.py
|
jfinkels_flask-restless/flask_restless/serialization/serializers.py
|
# serializers.py - JSON serializers for SQLAlchemy models
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Classes for JSON serialization of SQLAlchemy models.
The abstract base class :class:`Serializer` can be used to implement
custom serialization from SQLAlchemy objects. The
:class:`DefaultSerializer` provide some basic serialization as expected
by classes that follow the JSON API protocol.
The implementations here are closely coupled to the rest of the
Flask-Restless code.
"""
from datetime import date
from datetime import datetime
from datetime import time
from datetime import timedelta
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from flask import request
from sqlalchemy.exc import NoInspectionAvailable
from sqlalchemy.ext.associationproxy import _AssociationDict
from sqlalchemy.ext.associationproxy import _AssociationList
from sqlalchemy.ext.associationproxy import _AssociationSet
from sqlalchemy.ext.hybrid import HYBRID_PROPERTY
from sqlalchemy.inspection import inspect
from werkzeug.routing import BuildError
from werkzeug.urls import url_quote_plus
from .exceptions import SerializationException
from .exceptions import MultipleExceptions
from ..helpers import assoc_proxy_scalar_collections
from ..helpers import collection_name
from ..helpers import foreign_keys
from ..helpers import get_model
from ..helpers import get_related_model
from ..helpers import get_relations
from ..helpers import is_like_list
from ..helpers import is_mapped_class
from ..helpers import primary_key_for
from ..helpers import primary_key_value
from ..helpers import serializer_for
from ..helpers import url_for
#: Names of columns which should definitely not be considered user columns to
#: be included in a dictionary representation of a model.
COLUMN_BLACKLIST = ('_sa_polymorphic_on', )
#: The highest version of the JSON API specification supported by
#: Flask-Restless.
JSONAPI_VERSION = '1.0'
# TODO In Python 2.7 or later, we can just use `timedelta.total_seconds()`.
if hasattr(timedelta, 'total_seconds'):
def total_seconds(td):
return td.total_seconds()
else:
# This formula comes from the Python 2.7 documentation for the
# `timedelta.total_seconds` method.
def total_seconds(td):
secs = td.seconds + td.days * 24 * 3600
return (td.microseconds + secs * 10**6) / 10**6
def to_unicode(s):
"""Convert a string to a Unicode string, if on Python 2."""
try:
return unicode(s) # noqa
except NameError:
return s
def create_relationship(model, instance, relation):
"""Creates a relationship from the given relation name.
Returns a dictionary representing a relationship as described in
the `Relationships`_ section of the JSON API specification.
`model` is the model class of the primary resource for which a
relationship object is being created.
`instance` is the instance of the model for which we are considering
a related value.
`relation` is the name of the relation of `instance` given as a
string.
This function may raise :exc:`ValueError` if an API has not been
created for the primary model, `model`, or the model of the
relation.
.. _Relationships:
http://jsonapi.org/format/#document-resource-object-relationships
"""
result = {}
# Create the self and related links.
pk_value = primary_key_value(instance)
self_link = url_for(model, pk_value, relation, relationship=True)
related_link = url_for(model, pk_value, relation)
result['links'] = {'self': self_link}
# If the user has not created a GET endpoint for the related
# resource, then there is no "related" link to provide, so we check
# whether the URL exists before setting the related link.
try:
related_model = get_related_model(model, relation)
url_for(related_model)
except ValueError:
pass
else:
result['links']['related'] = related_link
# Get the related value so we can see if it is a to-many
# relationship or a to-one relationship.
related_value = getattr(instance, relation)
# There are three possibilities for the relation: it could be a
# to-many relationship, a null to-one relationship, or a non-null
# to-one relationship. We decide whether the relation is to-many by
# determining whether it is list-like.
if is_like_list(instance, relation):
# We could pre-compute the "type" name for the related instances
# here and provide it in the `_type` keyword argument to the
# serialization function, but the to-many relationship could be
# heterogeneous.
result['data'] = list(map(simple_relationship_dump, related_value))
elif related_value is not None:
result['data'] = simple_relationship_dump(related_value)
else:
result['data'] = None
return result
def JsonApiDocument():
"""A skeleton JSON API document, containing the basic elements but
no data.
"""
document = {
'data': None,
'jsonapi': {
'version': JSONAPI_VERSION
},
'links': {},
'meta': {},
'included': []
}
return document
def get_column_name(column):
"""Retrieve a column name from a column attribute of SQLAlchemy model
class, or a string.
Raises `TypeError` when argument does not fall into either of those
options.
"""
try:
inspected_column = inspect(column)
except NoInspectionAvailable:
# In this case, we assume the column is actually just a string.
return column
else:
return inspected_column.key
class Serializer(object):
"""An object that serializes one or many instances of a SQLAlchemy
model to a dictionary representation.
**This is a base class with no implementation.**
"""
def serialize(self, instance, only=None):
"""Returns a dictionary representation of the specified instance
of a SQLAlchemy model.
If `only` is a list, only the fields and relationships whose
names appear as strings in `only` should appear in the returned
dictionary.
**This method is not implemented in this base class; subclasses must
override this method.**
"""
raise NotImplementedError
def serialize_many(self, instances, only=None):
"""Returns a dictionary representation of the specified
instances of a SQLAlchemy model.
If `only` is a list, only the fields and relationships whose
names appear as strings in `only` should appear in the returned
dictionary.
**This method is not implemented in this base class; subclasses must
override this method.**
"""
raise NotImplementedError
class DefaultSerializer(Serializer):
"""A default implementation of a JSON API serializer for SQLAlchemy
models.
The :meth:`.serialize` method of this class returns a complete JSON
API document as a dictionary containing the resource object
representation of the given instance of a SQLAlchemy model as its
primary data. Similarly, the :meth:`.serialize_many` method returns
a JSON API document containing a a list of resource objects as its
primary data.
If `only` is a list, only these fields and relationships will in the
returned dictionary. The only exception is that the keys ``'id'``
and ``'type'`` will always appear, regardless of whether they appear
in `only`. These settings take higher priority than the `only` list
provided to the :meth:`.serialize` or :meth:`.serialize_many`
methods: if an attribute or relationship appears in the `only`
argument to those method but not here in the constructor, it will
not appear in the returned dictionary.
If `exclude` is a list, these fields and relationships will **not**
appear in the returned dictionary.
If `additional_attributes` is a list, these attributes of the
instance to be serialized will appear in the returned
dictionary. This is useful if your model has an attribute that is
not a SQLAlchemy column but you want it to be exposed.
You **must not** specify both `only` and `exclude` lists; if you do,
the behavior of this function is undefined.
You **must not** specify a field in both `exclude` and in
`additional_attributes`; if you do, the behavior of this function is
undefined.
"""
def __init__(self, only=None, exclude=None, additional_attributes=None,
**kw):
super(DefaultSerializer, self).__init__(**kw)
# Always include at least the type and ID, regardless of what the user
# specified.
if only is not None:
# Convert SQLAlchemy Column objects to strings if necessary.
#
# TODO In Python 2.7 or later, this should be a set comprehension.
only = set(get_column_name(column) for column in only)
# TODO In Python 2.7 or later, this should be a set literal.
only |= set(['type', 'id'])
if exclude is not None:
# Convert SQLAlchemy Column objects to strings if necessary.
#
# TODO In Python 2.7 or later, this should be a set comprehension.
exclude = set(get_column_name(column) for column in exclude)
self.default_fields = only
self.exclude = exclude
self.additional_attributes = additional_attributes
def _is_excluded(self, f, only):
"""Decide whether a field should be excluded from serialization.
`f` is a string naming a column (either an attribute or a
relationship) of a resource. `only` is a list of strings naming
fields, as described in :meth:`.DefaultSerializer.serialize`.
This function returns a Boolean indicating whether the field
should be excluded from serialization. The decision is based on
the `only` fields requested by the client as well as the default
included or excluded fields specified in the constructor of this
class.
"""
if self.default_fields is not None and f not in self.default_fields:
return True
if only is not None and f not in only:
return True
if self.exclude is not None and f in self.exclude:
return True
return False
def _dump(self, instance, only=None):
# Always include at least the type and ID, regardless of what
# the user requested.
if only is not None:
# TODO In Python 2.7 or later, this should be a set literal.
only = set(only) | set(['type', 'id'])
model = type(instance)
try:
inspected_instance = inspect(model)
except NoInspectionAvailable:
message = 'failed to get columns for model {0}'.format(model)
raise SerializationException(instance, message=message)
# Determine the columns to serialize as "attributes".
#
# This include plain old columns (like strings and integers, for
# example), hybrid properties, and association proxies to scalar
# collections (like a list of strings, for example).
column_attrs = inspected_instance.column_attrs.keys()
assoc_scalars = list(assoc_proxy_scalar_collections(model))
descriptors = inspected_instance.all_orm_descriptors.items()
hybrid_columns = [k for k, d in descriptors
if d.extension_type == HYBRID_PROPERTY]
columns = column_attrs + assoc_scalars + hybrid_columns
# Also include any attributes specified by the user.
if self.additional_attributes is not None:
columns += self.additional_attributes
# Serialize each attribute, excluding those that should be excluded.
attributes = {}
foreign_key_columns = foreign_keys(model)
pk_name = primary_key_for(model)
for column in columns:
if self._is_excluded(column, only=only):
continue
# Exclude column names that are blacklisted.
if column.startswith('__') or column in COLUMN_BLACKLIST:
continue
# Exclude column names that are foreign keys (unless the
# foreign key is the primary key for the model; this can
# happen in the joined table inheritance database
# configuration).
if column in foreign_key_columns and column != pk_name:
continue
# Get the value for this column. Call it if it is callable.
value = getattr(instance, column)
if callable(value):
value = value()
# Attributes values that come from association proxy
# collections need to be cast to plain old Python data types
# so that the JSON serializer can handle them.
if isinstance(value, _AssociationList):
value = list(value)
elif isinstance(value, _AssociationSet):
value = set(value)
elif isinstance(value, _AssociationDict):
value = dict(value)
# Serialize any date- or time-like objects that appear in
# the attributes.
#
# TODO In Flask 0.11, the default JSON encoder for the Flask
# application object does this automatically. Alternately,
# the user could have set a smart JSON encoder on the Flask
# application, which would cause these attributes to be
# converted to strings when the Response object is created
# (in the `jsonify` function, for example). However, we
# should not rely on that JSON encoder since the user could
# set any crazy encoder on the Flask application.
if isinstance(value, (date, datetime, time)):
value = value.isoformat()
elif isinstance(value, timedelta):
value = total_seconds(value)
# Recursively serialize any object that appears in the
# attributes. This may happen if, for example, the return
# value of one of the callable functions is an instance of
# another SQLAlchemy model class.
#
# This is a bit of a fragile test for whether the object
# needs to be serialized: we simply check if the class of
# the object is a mapped class.
if is_mapped_class(type(value)):
model_ = get_model(value)
try:
serializer = serializer_for(model_)
serialized_val = serializer.serialize(value)
except ValueError:
# TODO Should this cause an exception, or fail
# silently? See similar comments in `views/base.py`.
# # raise SerializationException(instance)
serialized_val = simple_serialize(value)
# We only need the data from the JSON API document, not
# the metadata. (So really the serializer is doing more
# work than it needs to here.)
value = serialized_val['data']
# Set this column's value in the attributes dictionary.
attributes[column] = value
# Get the ID and type of the resource.
id_ = attributes.pop('id', None)
type_ = collection_name(model)
# Create the result dictionary and add the attributes.
result = dict(id=id_, type=type_)
if attributes:
result['attributes'] = attributes
# Add the self link unless it has been explicitly excluded.
is_self_in_default = (self.default_fields is None or
'self' in self.default_fields)
is_self_in_only = only is None or 'self' in only
if is_self_in_default and is_self_in_only:
instance_id = primary_key_value(instance)
# `url_for` may raise a `BuildError` if the user has not created a
# GET API endpoint for this model. In this case, we simply don't
# provide a self link.
#
# TODO This might fail if the user has set the
# `current_app.build_error_handler` attribute, in which case, the
# exception may not be raised.
try:
path = url_for(model, instance_id, _method='GET')
except BuildError:
pass
else:
# HACK In order to support users using Python 2.7 with
# the `future` compatibility library, we need to ensure
# that both `request.url_root` and `path` are of the
# same type.
path = to_unicode(path)
url = urljoin(request.url_root, path)
result['links'] = dict(self=url)
# # add any included methods
# if include_methods is not None:
# for method in include_methods:
# if '.' not in method:
# value = getattr(instance, method)
# # Allow properties and static attributes in
# # include_methods
# if callable(value):
# value = value()
# result[method] = value
# If the primary key is not named "id", we'll duplicate the
# primary key under the "id" key.
if pk_name != 'id':
result['id'] = result['attributes'][pk_name]
# TODO Same problem as above.
#
# In order to comply with the JSON API standard, primary keys must be
# returned to the client as strings, so we convert it here.
if 'id' in result:
try:
result['id'] = str(result['id'])
except UnicodeEncodeError:
result['id'] = url_quote_plus(result['id'].encode('utf-8'))
# Serialize each relationship, excluding those that should be excluded.
relationships = {}
for r in get_relations(model):
if not self._is_excluded(r, only=only):
relationships[r] = create_relationship(model, instance, r)
if relationships:
result['relationships'] = relationships
return result
def serialize(self, instance, only=None):
"""Returns a complete JSON API document as a dictionary
containing the resource object representation of the given
instance of a SQLAlchemy model as its primary data.
The returned dictionary is suitable as an argument to
:func:`flask.json.jsonify`. Specifically, date and time objects
(:class:`datetime.date`, :class:`datetime.time`,
:class:`datetime.datetime`, and :class:`datetime.timedelta`) as
well as :class:`uuid.UUID` objects are converted to string
representations, so no special JSON encoder behavior is
required.
If `only` is a list, only the fields and relationships whose
names appear as strings in `only` will appear in the resulting
dictionary. This filter is applied *after* the default fields
specified in the `only` keyword argument to the constructor of
this class, so only fields that appear in both `only` keyword
arguments will appear in the returned dictionary. The only
exception is that the keys ``'id'`` and ``'type'`` will always
appear, regardless of whether they appear in `only`.
Since this method creates absolute URLs to resources linked to
the given instance, it must be called within a `Flask request
context`_.
.. _Flask request context: http://flask.pocoo.org/docs/0.10/reqcontext/
"""
resource = self._dump(instance, only=only)
result = JsonApiDocument()
result['data'] = resource
return result
def serialize_many(self, instances, only=None):
"""Serializes each instance using its model-specific serializer.
This method works for heterogeneous collections of instances
(that is, collections in which each instance is of a different
type).
The `only` keyword argument must be a dictionary mapping
resource type name to list of fields representing a sparse
fieldset. The values in this dictionary must be valid values for
the `only` keyword argument in the
:meth:`DefaultSerializer.serialize` method.
"""
resources = []
failed = []
for instance in instances:
# Determine the serializer for this instance.
model = get_model(instance)
try:
serializer = serializer_for(model)
except ValueError:
message = 'Failed to find serializer class'
exception = SerializationException(instance, message=message)
failed.append(exception)
continue
# This may also raise ValueError
try:
_type = collection_name(model)
except ValueError:
message = 'Failed to find collection name'
exception = SerializationException(instance, message=message)
failed.append(exception)
continue
_only = only.get(_type)
try:
serialized = serializer.serialize(instance, only=_only)
# We only need the data from the JSON API document, not
# the metadata. (So really the serializer is doing more
# work than it needs to here.)
#
# TODO We could use `serializer._dump` instead.
serialized = serialized['data']
resources.append(serialized)
except SerializationException as exception:
failed.append(exception)
if failed:
raise MultipleExceptions(failed)
result = JsonApiDocument()
result['data'] = resources
return result
class DefaultRelationshipSerializer(Serializer):
"""A default implementation of a serializer for resource identifier
objects for use in relationship objects in JSON API documents.
This serializer differs from the default serializer for resources
since it only provides an ``'id'`` and a ``'type'`` in the
dictionary returned by the :meth:`.serialize` and
:meth:`.serialize_many` methods.
"""
def _dump(self, instance, _type=None):
if _type is None:
_type = collection_name(get_model(instance))
id_ = primary_key_value(instance, as_string=True)
return {'id': id_, 'type': _type}
def serialize(self, instance, only=None, _type=None):
resource_identifier = self._dump(instance, _type=_type)
result = JsonApiDocument()
result['data'] = resource_identifier
return result
def serialize_many(self, instances, only=None, _type=None):
# Since dumping each resource identifier from a given instance
# could theoretically raise a SerializationException, we collect
# all the errors and wrap them in a MultipleExceptions exception
# object.
resource_identifiers = []
failed = []
for instance in instances:
try:
resource_identifier = self._dump(instance, _type=_type)
resource_identifiers.append(resource_identifier)
except SerializationException as exception:
failed.append(exception)
if failed:
raise MultipleExceptions(failed)
result = JsonApiDocument()
result['data'] = resource_identifiers
return result
#: This is an instance of the default serializer class,
#: :class:`DefaultSerializer`.
#:
#: The purpose of this instance is to provide easy access to default
#: serialization methods.
singleton_serializer = DefaultSerializer()
#: This is an instance of the default relationship serializer class,
#: :class:`DefaultRelationshipSerializer`.
#:
#: The purpose of this instance is to provide easy access to default
#: serialization methods.
singleton_relationship_serializer = DefaultRelationshipSerializer()
simple_dump = singleton_serializer.serialize
#: Provides basic, uncustomized serialization functionality as provided
#: by the :meth:`DefaultSerializer.serialize` method.
#:
#: This function is suitable for calling on its own, no other
#: instantiation or customization necessary.
simple_serialize = singleton_serializer.serialize
#: Provides basic, uncustomized serialization functionality as provided
#: by the :meth:`DefaultSerializer.serialize_many` method.
#:
#: This function is suitable for calling on its own, no other
#: instantiation or customization necessary.
simple_serialize_many = singleton_serializer.serialize_many
simple_relationship_dump = singleton_relationship_serializer._dump
#: Provides basic, uncustomized serialization functionality as provided
#: by the :meth:`DefaultRelationshipSerializer.serialize` method.
#:
#: This function is suitable for calling on its own, no other
#: instantiation or customization necessary.
simple_relationship_serialize = singleton_relationship_serializer.serialize
#: Provides basic, uncustomized serialization functionality as provided
#: by the :meth:`DefaultRelationshipSerializer.serialize_many` method.
#:
#: This function is suitable for calling on its own, no other
#: instantiation or customization necessary.
simple_relationship_serialize_many = \
singleton_relationship_serializer.serialize_many
| 26,153
|
Python
|
.py
| 549
| 39.136612
| 79
| 0.665517
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,622
|
__init__.py
|
jfinkels_flask-restless/flask_restless/serialization/__init__.py
|
# __init__.py - indicates that this directory is a Python package
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Serialization and deserialization for Flask-Restless."""
from .deserializers import DefaultDeserializer
from .exceptions import DeserializationException
from .exceptions import MultipleExceptions
from .exceptions import SerializationException
from .serializers import DefaultSerializer
from .serializers import JsonApiDocument
from .serializers import simple_serialize
from .serializers import simple_serialize_many
from .serializers import simple_relationship_serialize
from .serializers import simple_relationship_serialize_many
__all__ = [
'DefaultDeserializer',
'DefaultSerializer',
'DeserializationException',
'JsonApiDocument',
'MultipleExceptions',
'SerializationException',
'simple_relationship_serialize',
'simple_relationship_serialize_many',
'simple_serialize',
'simple_serialize_many',
]
| 1,320
|
Python
|
.py
| 34
| 36.617647
| 72
| 0.8
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,623
|
exceptions.py
|
jfinkels_flask-restless/flask_restless/serialization/exceptions.py
|
# exceptions.py - serialization exceptions
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Exceptions that arise from serialization or deserialization."""
class SerializationException(Exception):
"""Raised when there is a problem serializing an instance of a
SQLAlchemy model to a dictionary representation.
`instance` is the (problematic) instance on which
:meth:`DefaultSerializer.serialize` was invoked.
`message` is an optional string describing the problem in more
detail.
`resource` is an optional partially-constructed serialized
representation of ``instance``.
Each of these keyword arguments is stored in a corresponding
instance attribute so client code can access them.
"""
def __init__(self, instance, message=None, resource=None, *args, **kw):
super(SerializationException, self).__init__(*args, **kw)
self.resource = resource
self.message = message
self.instance = instance
class MultipleExceptions(Exception):
"""Raised when there are multiple problems in serialization or
deserialization.
`exceptions` is a non-empty sequence of other exceptions that have
been raised in the code.
You may wish to raise this exception when implementing the
:meth:`DefaultSerializer.serialize_many` method, for example, if
there are multiple exceptions
"""
def __init__(self, exceptions, *args, **kw):
super(MultipleExceptions, self).__init__(*args, **kw)
#: Sequence of other exceptions that have been raised in the code.
self.exceptions = exceptions
class DeserializationException(Exception):
"""Raised when there is a problem deserializing a Python dictionary to an
instance of a SQLAlchemy model.
`status` is an integer representing the HTTP status code that
corresponds to this error. If not specified, it is set to 400,
representing :http:statuscode:`400`.
`detail` is a string describing the problem in more detail. If
provided, this will be incorporated in the return value of
:meth:`.message`.
Each of the keyword arguments `status` and `detail` are assigned
directly to instance-level attributes :attr:`status` and
:attr:`detail`.
"""
def __init__(self, status=400, detail=None, *args, **kw):
super(DeserializationException, self).__init__(*args, **kw)
#: A string describing the problem in more detail.
self.detail = detail
#: The HTTP status code corresponding to this error.
self.status = status
def message(self):
"""Returns a more detailed description of the problem as a
string.
"""
base = 'Failed to deserialize object'
if self.detail is not None:
return '{0}: {1}'.format(base, self.detail)
return base
class NotAList(DeserializationException):
"""Raised when a ``data`` element exists but is not a list when it
should be, as when deserializing a to-many relationship.
"""
def __init__(self, relation_name=None, *args, **kw):
# # For now, this is only raised when calling deserialize_many()
# # on a relationship, so this extra message should always be
# # inserted.
# if relation_name is not None:
inner = ('in linkage for relationship "{0}" ').format(relation_name)
# else:
# inner = ''
detail = ('"data" element {0}must be a list when calling'
' deserialize_many(); maybe you meant to call'
' deserialize()?').format(inner)
super(NotAList, self).__init__(detail=detail, *args, **kw)
class ClientGeneratedIDNotAllowed(DeserializationException):
"""Raised when attempting to deserialize a resource that provides
an ID when an ID is not allowed.
"""
def __init__(self, *args, **kw):
detail = 'Server does not allow client-generated IDS'
sup = super(ClientGeneratedIDNotAllowed, self)
sup.__init__(status=403, detail=detail, *args, **kw)
class ConflictingType(DeserializationException):
"""Raised when attempting to deserialize a linkage object with an
unexpected ``'type'`` key.
`relation_name` is a string representing the name of the
relationship for which a linkage object has a conflicting type.
`expected_type` is a string representing the expected type of the
related resource.
`given_type` is is a string representing the given value of the
``'type'`` element in the resource.
"""
def __init__(self, expected_type, given_type, relation_name=None, *args,
**kw):
if relation_name is None:
inner = ''
else:
inner = (' in linkage object for relationship'
' "{0}"').format(relation_name)
detail = 'expected type "{0}" but got type "{1}"{2}'
detail = detail.format(expected_type, given_type, inner)
sup = super(ConflictingType, self)
sup.__init__(status=409, detail=detail, *args, **kw)
class UnknownField(DeserializationException):
"""Raised when attempting to deserialize an object that references a
field that does not exist on the model.
`field` is the name of the unknown field as a string.
"""
#: Whether the unknown field is given as a field or a relationship.
#:
#: This attribute can only take one of the two values ``'field'`` or
#: ``'relationship'``.
field_type = None
def __init__(self, field, *args, **kw):
detail = 'model has no {0} "{1}"'.format(self.field_type, field)
super(UnknownField, self).__init__(detail=detail, *args, **kw)
class UnknownRelationship(UnknownField):
"""Raised when attempting to deserialize a linkage object that
references a relationship that does not exist on the model.
"""
field_type = 'relationship'
class UnknownAttribute(UnknownField):
"""Raised when attempting to deserialize an object that specifies a
field that does not exist on the model.
"""
field_type = 'attribute'
class MissingInformation(DeserializationException):
"""Raised when a linkage object does not specify an element required by
the JSON API specification.
`relation_name` is the name of the relationship in which the linkage
object is missing information.
"""
#: The name of the key in the dictionary that is missing.
#:
#: Subclasses must set this class attribute.
element = None
def __init__(self, relation_name=None, *args, **kw):
#: The relationship in which a linkage object is missing information.
self.relation_name = relation_name
if relation_name is not None:
inner = (' in linkage object for relationship'
' "{0}"').format(relation_name)
else:
inner = ''
detail = 'missing "{0}" element{1}'.format(self.element, inner)
super(MissingInformation, self).__init__(detail=detail, *args, **kw)
class MissingData(MissingInformation):
"""Raised when a resource does not specify a ``'data'`` element
where required by the JSON API specification.
"""
element = 'data'
class MissingID(MissingInformation):
"""Raised when a resource does not specify an ``'id'`` element where
required by the JSON API specification.
"""
element = 'id'
class MissingType(MissingInformation):
"""Raised when a resource does not specify a ``'type'`` element
where required by the JSON API specification.
"""
element = 'type'
| 7,955
|
Python
|
.py
| 172
| 39.726744
| 77
| 0.682054
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,624
|
deserializers.py
|
jfinkels_flask-restless/flask_restless/serialization/deserializers.py
|
# deserializers.py - SQLAlchemy deserializers for JSON documents
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Classes for deserialization of JSON API documents to SQLAlchemy.
The abstract base class :class:`Deserializer` can be used to implement
custom deserialization from JSON API documents to SQLAlchemy
objects. The :class:`DefaultDeserializer` provide some basic
deserialization as expected by classes that follow the JSON API
protocol.
The implementations here are closely coupled to the rest of the
Flask-Restless code. Specifically, they use global helper functions
(like :func:`.model_for`) that rely on information provided to the
:class:`.APIManager` at the time of API creation.
"""
from .exceptions import ClientGeneratedIDNotAllowed
from .exceptions import ConflictingType
from .exceptions import DeserializationException
from .exceptions import MissingData
from .exceptions import MissingID
from .exceptions import MissingType
from .exceptions import MultipleExceptions
from .exceptions import NotAList
from .exceptions import UnknownRelationship
from .exceptions import UnknownAttribute
from ..helpers import collection_name
from ..helpers import get_related_model
from ..helpers import get_by
from ..helpers import has_field
from ..helpers import is_like_list
from ..helpers import model_for
from ..helpers import primary_key_for
from ..helpers import string_to_datetime as to_datetime
class Deserializer(object):
"""An object that transforms a dictionary representation of a JSON
API document into an instance or instances of the SQLAlchemy model
specified at instantiation time.
`session` is the SQLAlchemy session in which to look for any related
resources.
`model` is the class of which instances will be created by the
:meth:`.deserialize` and :meth:`.deserialize_many` methods.
**This is a base class with no implementation.**
"""
def __init__(self, session, model):
self.session = session
self.model = model
def deserialize(self, document):
"""Creates and returns a new instance of the SQLAlchemy model
specified in the constructor whose attributes are given by the
specified dictionary.
`document` must be a dictionary representation of a JSON API
document containing a single resource as primary data, as
specified in the JSON API specification. For more information,
see the `Resource Objects`_ section of the JSON API
specification.
**This method is not implemented in this base class; subclasses
must override this method.**
.. _Resource Objects:
http://jsonapi.org/format/#document-structure-resource-objects
"""
raise NotImplementedError
def deserialize_many(self, document):
"""Creates and returns a list of instances of the SQLAlchemy
model specified in the constructor whose fields are given in the
JSON API document.
`document` must be a dictionary representation of a JSON API
document containing a list of resources as primary data, as
specified in the JSON API specification. For more information,
see the `Resource Objects`_ section of the JSON API
specification.
**This method is not implemented in this base class; subclasses
must override this method.**
.. _Resource Objects:
http://jsonapi.org/format/#document-structure-resource-objects
"""
raise NotImplementedError
class DeserializerBase(Deserializer):
def __init__(self, session, model):
super(DeserializerBase, self).__init__(session, model)
self.relation_name = None
def _check_type_and_id(self, data):
"""Check that an object has a valid type and ID.
`data` is a dictionary representation of a JSON API resource
object or a resource identifier object. This method does not
return anything, but implementing subclasses may raise an
exception here, for example if the ``type`` key is missing.
This is an abstract method; concrete subclasses must override
and implement it.
"""
raise NotImplementedError
def _resource_to_model(self, data):
"""Get the SQLAlchemy model for the type of the given resource.
`data` is a dictionary representation of a JSON API resource
object. This method returns the SQLAlchemy model class
corresponding to the resource type given in the ``type`` key of
the resource object.
This method raises :exc:`ConflictingType` if the type of the
resource object does not match the SQLAlchemy model specified in
the constructor of this class (that is, the
:attr:`.Deserializer.model` instance attribute).
"""
type_ = data['type']
expected_type = collection_name(self.model)
try:
model = model_for(type_)
except ValueError:
raise ConflictingType(expected_type, type_, self.relation_name)
# If we wanted to allow deserializing a subclass of the model,
# we could use:
#
# if not issubclass(model, self.model) and type != expected_type:
#
if type_ != expected_type:
raise ConflictingType(expected_type, type_, self.relation_name)
return model
def _check_unknown_fields(self, data):
"""Check for any unknown fields in an object.
`data` is a dictionary representation of a JSON API resource
object or resource identifier object.
`model` is a SQLAlchemy model class. The `data` object should
represent an instance of `model`.
This method does not return anything, but implementing
subclasses may raise an exception here, for example if `data`
includes a field that does not exist on `model`.
This is an abstract method; concrete subclasses must override
and implement it.
"""
raise NotImplementedError
def _extract_attributes(self, data, model):
"""Generate the attributes given in an object.
`data` is a dictionary representation of a JSON API resource
object or resource identifier object.
`model` is a SQLAlchemy model class. The `data` object should
represent an instance of `model`.
This method is an iterator generator. It yields pairs in which
the left element is a string naming an attribute and the right
element is the value of the attribute to assign to the instance
of `model` being deserialized. The attributes are passed along
to the :meth:`._get_or_create` method.
This is an abstract method; concrete subclasses must override
and implement it.
"""
raise NotImplementedError
def _get_or_create(self, model, attributes):
"""Get or create an instance of a model with the given attributes.
`model` is a SQLAlchemy model class. `attributes` is a
dictionary in which keys are strings naming instance attributes
of `model` and values are the values to assign to those
attributes.
This method may return either a new instance or an existing
instance of the given model that has the given attributes.
If an implementing subclass returns an existing instance, it
should (but is not obligated to) yield at least a pair of the
form ``(pk_name, pk_value)``, where ``pk_name`` is a string
naming the primary key attribute of `model` and ``pk_value`` is
the primary key value as it appears in `data`.
This is an abstract method; concrete subclasses must override
and implement it.
"""
raise NotImplementedError
def _load_related_resources(self, data, model):
"""Generate identifiers for related resources, if necessary.
This method is only relevant for subclasses that deserialize
resource objects, not for subclasses that deserialize resource
identifier objects (since resource identifier objects do not
contain any relationship information).
`data` is a dictionary representation of a JSON API resource
object.
`model` is a SQLAlchemy model class. The `data` resource object
should represent an instance of `model`.
This method is an iterator generator. It yields pairs in which
the left element is a string naming a relationship and the right
element is a deserialized version of the JSON API resource
identifiers of the relationship. For a to-one relationship, this
is just a single SQLAlchemy model instance. For a to-many
relationship, it is a list of SQLAlchemy model instances.
For example::
>>> # session = ...
>>> # class Article(Base): ...
>>> deserializer = DefaultDeserializer(session, Article)
>>> data = {
... 'relationships': {
... 'comments': [
... {'type': 'comment', 'id': 1}
... ],
... 'author': {'type': 'person', 'id': 1}
... }
... }
>>> rels = deserializer._load_related_resources(data, Article)
>>> for name, obj in sorted(rels):
... print(name, obj)
author <Person object at 0x...>
comments [<Comment object at 0x...>]
This method raises :exc:`DeserializationException` or
:exc:`MultipleExceptions` if there is a problem deserializing
any of the related resources.
This is an abstract method; concrete subclasses must override
and implement it.
"""
raise NotImplementedError
def _assign_related_resources(self, instance, related_resources):
"""Assign related resources to a given instance of a SQLAlchemy model.
This method is only relevant for subclasses that deserialize
resource objects, not for subclasses that deserialize resource
identifier objects (since resource identifier objects do not
contain any relationship information).
`instance` is an instance of a SQLAlchemy model class.
`related_resources` is a dictionary whose keys are strings
naming relationships of the SQLAlchemy model and whose values
are the corresponding relationship values.
This method does not return anything but modifies `instance` by
setting the value of the attributes named by
`related_resources`.
This is an abstract method; concrete subclasses must override
and implement it.
"""
raise NotImplementedError
def _load(self, data):
"""Returns a new instance of a SQLAlchemy model represented by
the given resource object.
`data` is a dictionary representation of a JSON API resource
object.
This method may raise one of various
:exc:`DeserializationException` subclasses. If the instance has
a to-many relationship, this method may raise
:exc:`MultipleExceptions` as well, if there are multiple
exceptions when deserializing the related instances.
"""
self._check_type_and_id(data)
model = self._resource_to_model(data)
self._check_unknown_fields(data, model)
attributes = self._extract_attributes(data, model)
instance = self._get_or_create(model, dict(attributes))
related_resources = self._load_related_resources(data, model)
# TODO Need to check here if any related instances are None,
# like we do in the patch() method. We could possibly refactor
# the code above and the code there into a helper function...
self._assign_related_resources(instance, dict(related_resources))
return instance
def deserialize(self, document):
"""Creates and returns a new instance of the SQLAlchemy model specified
in the constructor whose attributes are given in the JSON API
document.
`document` must be a dictionary representation of a JSON API
document containing a single resource as primary data, as
specified in the JSON API specification. For more information,
see the `Resource Objects`_ section of the JSON API
specification.
*Implementation note:* everything in the document other than the
``data`` element is ignored.
.. _Resource Objects:
http://jsonapi.org/format/#document-structure-resource-objects
"""
if 'data' not in document:
raise MissingData(self.relation_name)
data = document['data']
return self._load(data)
class DefaultDeserializer(DeserializerBase):
"""A default implementation of a deserializer for SQLAlchemy models.
When called, this object returns an instance of a SQLAlchemy model
with fields and relations specified by the provided dictionary.
"""
def __init__(self, session, model, allow_client_generated_ids=False, **kw):
super(DefaultDeserializer, self).__init__(session, model, **kw)
#: Whether to allow client generated IDs.
self.allow_client_generated_ids = allow_client_generated_ids
def _check_type_and_id(self, data):
"""Check that the resource object has a valid type and ID.
`data` is a dictionary representation of a JSON API resource
object. This method does not return anything, but raises
:exc:`MissingType` if the ``type`` key is missing and
:exc:`ClientGeneratedIDNotAllowed` if the ``id`` key is present
when not allowed.
"""
if 'type' not in data:
raise MissingType
if 'id' in data and not self.allow_client_generated_ids:
raise ClientGeneratedIDNotAllowed
def _check_unknown_fields(self, data, model):
"""Check for any unknown fields in a resource object.
`data` is a dictionary representation of a JSON API resource
object.
`model` is a SQLAlchemy model class. The `data` resource should
represent an instance of `model`.
This method does not return anything, but raises
:exc:`UnknownRelationship` or :exc:`UnknownAttribute` if any
relationship or attribute, respectively, does not exist on the
given model.
"""
for relation in data.get('relationships', []):
if not has_field(model, relation):
raise UnknownRelationship(relation)
for attribute in data.get('attributes', []):
if not has_field(model, attribute):
raise UnknownAttribute(attribute)
def _load_related_resources(self, data, model):
"""Generate identifiers for related resources.
`data` is a dictionary representation of a JSON API resource
object.
`model` is a SQLAlchemy model class. The `data` resource should
represent an instance of `model`.
This method is an iterator generator. It yields pairs in which
the left element is a string naming a relationship and the right
element is a deserialized version of the JSON API resource
identifiers of the relationship. For a to-one relationship, this
is just a single SQLAlchemy model instance. For a to-many
relationship, it is a list of SQLAlchemy model instances.
For example::
>>> # session = ...
>>> # class Article(Base): ...
>>> deserializer = DefaultDeserializer(session, Article)
>>> data = {
... 'relationships': {
... 'comments': [
... {'type': 'comment', 'id': 1}
... ],
... 'author': {'type': 'person', 'id': 1}
... }
... }
>>> rels = deserializer._load_related_resources(data, Article)
>>> for name, obj in sorted(rels):
... print(name, obj)
author <Person object at 0x...>
comments [<Comment object at 0x...>]
This method raises :exc:`DeserializationException` or
:exc:`MultipleExceptions` if there is a problem deserializing
any of the related resources.
"""
for link_name, link_object in data.get('relationships', {}).items():
related_model = get_related_model(model, link_name)
# Create the deserializer for this relationship object and
# decide whether we need to deserialize a to-one
# relationship or a to-many relationship.
#
# These may raise a DeserializationException or
# MultipleExceptions.
DRD = DefaultRelationshipDeserializer
deserializer = DRD(self.session, related_model, link_name)
if is_like_list(model, link_name):
deserialize = deserializer.deserialize_many
else:
deserialize = deserializer.deserialize
yield link_name, deserialize(link_object)
def _extract_attributes(self, data, model):
"""Generate the attributes given in the resource object.
`data` is a dictionary representation of a JSON API resource
object.
`model` is a SQLAlchemy model class. The `data` resource should
represent an instance of `model`.
This method is an iterator generator. It yields pairs in which
the left element is a string naming an attribute and the right
element is the value of the attribute to assign to the instance
of `model` being created.
This method yields the attributes as-is from the resource object
given in `data`, with the exception that strings are parsed into
:class:`datetime.date` or :class:`datetime.datetime` objects
when appropriate, based on the columns of the given `model`.
"""
# Yield the primary key name and value, if it exists.
pk = primary_key_for(model)
if pk in data:
yield pk, data[pk]
for k, v in data.get('attributes', {}).items():
# Special case: if there are any dates, convert the string
# form of the date into an instance of the Python
# ``datetime`` object.
yield k, to_datetime(model, k, v)
def _get_or_create(self, model, attributes):
"""Get or create an instance of a model with the given attributes.
`model` is a SQLAlchemy model class. `attributes` is a
dictionary in which keys are strings naming instance attributes
of `model` and values are the values to assign to those
attributes.
This method returns a new instance of the given model (created
using the constructor) with the given attributes set on it.
"""
return model(**attributes)
def _assign_related_resources(self, instance, related_resources):
"""Assign related resources to a given instance of a SQLAlchemy model.
`instance` is an instance of a SQLAlchemy model class.
`related_resources` is a dictionary whose keys are strings
naming relationships of the SQLAlchemy model and whose values
are the corresponding relationship values.
This method does not return anything but modifies `instance` by
setting the value of the attributes named by
`related_resources`.
"""
for relation_name, related_value in related_resources.items():
setattr(instance, relation_name, related_value)
# # TODO JSON API currently doesn't support bulk creation of resources,
# # so this code cannot be accurately used/tested.
# def deserialize_many(self, document):
# """Creates and returns a list of instances of the SQLAlchemy
# model specified in the constructor whose fields are given in the
# JSON API document.
#
# This method assumes that each resource in the given document is
# of the same type.
#
# For more information, see the documentation for the
# :meth:`Deserializer.deserialize_many` method.
#
# """
# if 'data' not in document:
# raise MissingData
# data = document['data']
# if not isinstance(data, list):
# raise NotAList
# # Since loading each instance from a given resource object
# # representation could theoretically raise a
# # DeserializationException, we collect all the errors and wrap
# # them in a MultipleExceptions exception object.
# result = []
# failed = []
# for resource in data:
# try:
# instance = self._load(resource)
# result.append(instance)
# except DeserializationException as exception:
# failed.append(exception)
# if failed:
# raise MultipleExceptions(failed)
# return result
class DefaultRelationshipDeserializer(DeserializerBase):
"""A default implementation of a deserializer for resource
identifier objects for use in relationships in JSON API documents.
Each instance of this class should correspond to a particular
relationship of a model.
This deserializer differs from the default deserializer for
resources since it expects that the ``'data'`` element of the input
dictionary to :meth:`.deserialize` contains only ``'id'`` and
``'type'`` keys.
`session` is the SQLAlchemy session in which to look for any related
resources.
`model` is the SQLAlchemy model class of the relationship, *not the
primary resource*. With the related model class, this deserializer
will be able to use the ID provided to the :meth:`__call__` method
to determine the instance of the `related_model` class which is
being deserialized.
`relation_name` is the name of the relationship being deserialized,
given as a string. This is used mainly for more helpful error
messages.
"""
def __init__(self, session, model, relation_name=None):
super(DefaultRelationshipDeserializer, self).__init__(session, model)
#: The related model whose objects this deserializer will return
#: in the :meth:`__call__` method.
self.model = model
#: The collection name given to the related model.
self.type_name = collection_name(self.model)
#: The name of the relationship being deserialized, as a string.
self.relation_name = relation_name
def _check_type_and_id(self, data):
"""Check that the resource identifier object has a valid type and ID.
`data` is a dictionary representation of a JSON API resource
identifier object. This method does not return anything, but
raises :exc:`MissingType` if the ``type`` key is missing and
:exc:`MissingID` if the ``id`` key is missing.
"""
if 'type' not in data:
raise MissingType(self.relation_name)
if 'id' not in data:
raise MissingID(self.relation_name)
def _check_unknown_fields(self, data, model):
"""Do nothing.
Since there are no attributes or relationships in `data`, a
resource identifier object, there is nothing to do here.
"""
pass
def _extract_attributes(self, data, model):
"""Yield the primary key name/value pair of the resource identifier."""
pk_name = primary_key_for(model)
yield pk_name, data[pk_name]
def _get_or_create(self, model, attributes):
"""Get a resource identified by primary key.
`model` is a SQLAlchemy model class. `attributes` includes the
primary key name/value pair that identifies an instance of the
model. This method returns that instance.
"""
pk_name = primary_key_for(model)
pk_value = attributes[pk_name]
return get_by(self.session, model, pk_value)
def _load_related_resources(self, data, model):
"""Return an empty list.
There is no relationship information for a resource identifer.
"""
return []
def _assign_related_resources(self, instance, related_resources):
"""Do nothing.
Since there are no relationships in a resource identifier
object, there is nothing to do here.
"""
pass
def deserialize_many(self, document):
"""Returns a list of SQLAlchemy instances identified by the
resource identifiers given as the primary data in the given
document.
The type given in each resource identifier must match the
collection name associated with the SQLAlchemy model specified
in the constructor of this class. If not, this raises
:exc:`ConflictingType`.
"""
if 'data' not in document:
raise MissingData(self.relation_name)
resource_identifiers = document['data']
if not isinstance(resource_identifiers, list):
raise NotAList(self.relation_name)
# Since loading each related instance from a given resource
# identifier object representation could theoretically raise a
# DeserializationException, we collect all the errors and wrap
# them in a MultipleExceptions exception object.
result = []
failed = []
for resource_identifier in resource_identifiers:
try:
instance = self._load(resource_identifier)
result.append(instance)
except DeserializationException as exception:
failed.append(exception)
if failed:
raise MultipleExceptions(failed)
return result
| 26,316
|
Python
|
.py
| 529
| 41.240076
| 79
| 0.669253
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,625
|
resources.py
|
jfinkels_flask-restless/flask_restless/views/resources.py
|
# resources.py - views for requests on SQLAlchemy resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Views for fetching, creating, updating, and deleting resources.
The main class in this module, :class:`API`, is a
:class:`~flask.MethodView` subclass that handles creating endpoints from
SQLAlchemy models compatible with the JSON API specification.
"""
import sys
from flask import json
from flask import request
from werkzeug.exceptions import BadRequest
from ..helpers import collection_name
from ..helpers import get_by
from ..helpers import get_model
from ..helpers import get_related_model
from ..helpers import has_field
from ..helpers import is_like_list
from ..helpers import is_relationship
from ..helpers import primary_key_value
from ..helpers import string_to_datetime
from ..serialization import DeserializationException
from ..serialization import SerializationException
from .base import APIBase
from .base import error
from .base import error_response
from .base import errors_from_serialization_exceptions
from .base import errors_response
from .base import jsonpify
from .base import MultipleExceptions
from .base import SingleKeyError
from .helpers import changes_on_update
STRING_TYPES = (str, )
if sys.version_info < (3, 0):
STRING_TYPES += (unicode, ) # noqa
def errors_from_deserialization_exceptions(exceptions, included=False):
"""Returns an errors response object, as returned by
:func:`errors_response`, representing the given list of
:exc:`DeserializationException` objects.
If `included` is ``True``, this indicates that the exceptions were
raised by attempts to serialize resources included in a compound
document; this modifies the error message for the exceptions a bit.
"""
def _to_error(exception):
detail = exception.message()
status = exception.status
return error(status=status, detail=detail)
errors = list(map(_to_error, exceptions))
# Workaround: if there is only one error, assign the status code of
# that error object to be the status code of the actual HTTP
# response.
if len(errors) == 1:
status = errors[0]['status']
else:
status = 400
return errors_response(status, errors)
class API(APIBase):
"""Provides method-based dispatching for :http:method:`get`,
:http:method:`post`, :http:method:`patch`, and :http:method:`delete`
requests, for both collections of resources and individual resources.
`session` and `model` are as described in the constructor of the
superclass. In addition to those described below, this constructor also
accepts all the keyword arguments of the constructor of the superclass.
`page_size`, `max_page_size`, `serializer`, `deserializer`, and
`includes` are as described in :meth:`APIManager.create_api`.
"""
def __init__(self, *args, **kw):
super(API, self).__init__(*args, **kw)
#: Whether any side-effect changes are made to the SQLAlchemy
#: model on updates.
self.changes_on_update = changes_on_update(self.model)
def collection_processor_type(self, is_relation=False, **kw):
"""The suffix for the pre- and postprocessor identifiers for
requests on collections of resources.
`is_relation` is ``True`` if and only if the request is for a
to-many relation. Otherwise, the request is for a collection of
primary resources.
"""
return 'TO_MANY_RELATION' if is_relation else 'COLLECTION'
def resource_processor_type(self, is_relation=False,
is_related_resource=False, **kw):
"""The suffix for the pre- and postprocessor identifiers for
requests on a single resource.
`is_relation` is ``True`` if and only if the request is for a
to-one relation. Otherwise, the request is for a single
resource.
"""
if is_relation:
if is_related_resource:
return 'RELATED_RESOURCE'
return 'TO_ONE_RELATION'
return 'RESOURCE'
def _get_related_resource(self, resource_id, relation_name,
related_resource_id):
"""Returns a response containing a resource related to a given
resource.
For example, a request like this::
GET /people/1/articles/2
will fetch the article with ID 2 that is related to the person with ID
1 via the ``articles`` relationship. In general, this method is called
on requests of the form::
GET /<collection>/<resourceid>/<relationname>/<relatedresourceid>
"""
for preprocessor in self.preprocessors['GET_RELATED_RESOURCE']:
temp_result = preprocessor(resource_id=resource_id,
relation_name=relation_name,
related_resource_id=related_resource_id)
# Let the return value of the preprocessor be the new value of
# instid, thereby allowing the preprocessor to effectively specify
# which instance of the model to process on.
#
# We assume that if the preprocessor returns None, it really just
# didn't return anything, which means we shouldn't overwrite the
# instid.
if temp_result is not None:
if isinstance(temp_result, tuple):
if len(temp_result) == 2:
resource_id, relation_name = temp_result
else:
resource_id, relation_name, related_resource_id = \
temp_result
else:
resource_id = temp_result
# Get the resource with the specified ID.
primary_resource = get_by(self.session, self.model, resource_id,
self.primary_key)
# We check here whether there actually is an instance of the
# correct type and ID.
#
# The first condition is True exactly when there is no row in
# the table with the given primary key value. The second is True
# in the special case when the resource exists but is a subclass
# of the actual model for this API; this may happen if the model
# is a polymorphic subclass of another class using a single
# inheritance table.
found_model = get_model(primary_resource)
if primary_resource is None or found_model is not self.model:
detail = 'no resource of type {0} with ID {1}'
detail = detail.format(collection_name(self.model), resource_id)
return error_response(404, detail=detail)
# Return an error if the specified relation does not exist on
# the model.
if not is_relationship(self.model, relation_name):
detail = 'No such relation: {0}'.format(relation_name)
return error_response(404, detail=detail)
# Return an error if the relation is a to-one relation.
if not is_like_list(primary_resource, relation_name):
detail = ('Cannot access a related resource by ID from a to-one'
' relation')
return error_response(404, detail=detail)
# Get the related resources.
resources = getattr(primary_resource, relation_name)
# Check if one of the related resources has the specified ID. (JSON API
# expects all IDs to be strings.)
primary_keys = (primary_key_value(resource, as_string=True)
for resource in resources)
if not any(k == str(related_resource_id) for k in primary_keys):
detail = 'No related resource with ID {0}'
detail = detail.format(related_resource_id)
return error_response(404, detail=detail)
# Get the related resource by its ID.
related_model = get_related_model(self.model, relation_name)
resource = get_by(self.session, related_model, related_resource_id)
return self._get_resource_helper(resource,
primary_resource=primary_resource,
relation_name=relation_name,
related_resource=True)
def _get_relation(self, resource_id, relation_name):
"""Returns a response containing a resource or a collection of
resources related to a given resource.
For example, a request for a to-many relationship like this::
GET /people/1/articles
will fetch the articles related to the person with ID 1 via the
``articles`` relationship. On a request to a to-one relationship::
GET /articles/2/author
a single resource will be returned.
In general, this method is called on requests of the form::
GET /<collection_name>/<resource_id>/<relation_name>
"""
try:
filters, sort, group_by, single, ignorecase = \
self.collection_parameters(resource_id=resource_id,
relation_name=relation_name)
except (TypeError, ValueError, OverflowError) as exception:
detail = 'Unable to decode filter objects as JSON list'
return error_response(400, cause=exception, detail=detail)
except SingleKeyError as exception:
detail = 'Invalid format for filter[single] query parameter'
return error_response(400, cause=exception, detail=detail)
for preprocessor in self.preprocessors['GET_RELATION']:
temp_result = preprocessor(resource_id=resource_id,
relation_name=relation_name,
filters=filters, sort=sort,
group_by=group_by, single=single)
# Let the return value of the preprocessor be the new value of
# instid, thereby allowing the preprocessor to effectively specify
# which instance of the model to process on.
#
# We assume that if the preprocessor returns None, it really just
# didn't return anything, which means we shouldn't overwrite the
# instid.
if temp_result is not None:
if isinstance(temp_result, tuple) and len(temp_result) == 2:
resource_id, relation_name = temp_result
else:
resource_id = temp_result
# Get the resource with the specified ID.
primary_resource = get_by(self.session, self.model, resource_id,
self.primary_key)
# We check here whether there actually is an instance of the
# correct type and ID.
#
# The first condition is True exactly when there is no row in
# the table with the given primary key value. The second is True
# in the special case when the resource exists but is a subclass
# of the actual model for this API; this may happen if the model
# is a polymorphic subclass of another class using a single
# inheritance table.
found_model = get_model(primary_resource)
if primary_resource is None or found_model is not self.model:
detail = 'no resource of type {0} with ID {1}'
detail = detail.format(collection_name(self.model), resource_id)
return error_response(404, detail=detail)
# Return an error if the specified relation does not exist on
# the model.
if not is_relationship(self.model, relation_name):
detail = 'No such relation: {0}'.format(relation_name)
return error_response(404, detail=detail)
# Get the model of the specified relation.
# Determine if this is a to-one or a to-many relation.
if is_like_list(primary_resource, relation_name):
return self._get_collection_helper(resource=primary_resource,
relation_name=relation_name,
filters=filters, sort=sort,
group_by=group_by,
ignorecase=ignorecase,
single=single)
else:
resource = getattr(primary_resource, relation_name)
return self._get_resource_helper(resource=resource,
primary_resource=primary_resource,
relation_name=relation_name)
def _get_resource(self, resource_id):
"""Returns a response containing a single resource with the specified
ID.
For example, a request like::
GET /people/1
will fetch the person resource with ID 1.
In general, this method is called on requests of the form::
GET /<collection_name>/<resource_id>
"""
for preprocessor in self.preprocessors['GET_RESOURCE']:
temp_result = preprocessor(resource_id=resource_id)
# Let the return value of the preprocessor be the new value of
# instid, thereby allowing the preprocessor to effectively specify
# which instance of the model to process on.
#
# We assume that if the preprocessor returns None, it really just
# didn't return anything, which means we shouldn't overwrite the
# instid.
if temp_result is not None:
resource_id = temp_result
# Get the resource with the specified ID.
resource = get_by(self.session, self.model, resource_id,
self.primary_key)
# We check here whether there actually is an instance of the
# correct type and ID.
#
# The first condition is True exactly when there is no row in
# the table with the given primary key value. The second is True
# in the special case when the resource exists but is a subclass
# of the actual model for this API; this may happen if the model
# is a polymorphic subclass of another class using a single
# inheritance table.
if resource is None or get_model(resource) is not self.model:
detail = 'no resource of type {0} with ID {1}'
detail = detail.format(collection_name(self.model), resource_id)
return error_response(404, detail=detail)
return self._get_resource_helper(resource)
def _get_collection(self):
"""Returns a response containing a collection of resources of the type
specified by the ``model`` argument to the constructor of this class.
For example, a request like::
GET /people
will fetch a collection of people resources.
In general, this method is called on requests of the form::
GET /<collection_name>
Filtering, sorting, grouping, and pagination are applied to the
response in this method.
"""
try:
filters, sort, group_by, single, ignorecase = \
self.collection_parameters()
except (TypeError, ValueError, OverflowError) as exception:
detail = 'Unable to decode filter objects as JSON list'
return error_response(400, cause=exception, detail=detail)
except SingleKeyError as exception:
detail = 'Invalid format for filter[single] query parameter'
return error_response(400, cause=exception, detail=detail)
for preprocessor in self.preprocessors['GET_COLLECTION']:
preprocessor(filters=filters, sort=sort, group_by=group_by,
single=single)
return self._get_collection_helper(filters=filters, sort=sort,
group_by=group_by, single=single,
ignorecase=ignorecase)
def get(self, resource_id, relation_name, related_resource_id):
"""Returns the JSON document representing a resource or a collection of
resources.
If ``resource_id`` is ``None`` (that is, if the request is of the form
:http:get:`/people/`), this method returns a collection of resources.
Otherwise, if ``relation_name`` is ``None`` (that is, if the request is
of the form :http:get:`/people/1`), this method returns a resource with
the specified ID.
Otherwise, if ``related_resource_id`` is ``None`` (that is, if the
request is of the form :http:get:`/people/1/articles` or
:http:get:`/articles/1/author`), this method returns either a resource
in the case of a to-one relationship or a collection of resources in
the case of a to-many relationship.
Otherwise, if none of the arguments are ``None`` (that is, if the
request is of the form :http:get:`/people/1/articles/2`), this method
returns the particular resource in the to-many relationship with the
specified ID.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
if resource_id is None:
return self._get_collection()
if relation_name is None:
return self._get_resource(resource_id)
if related_resource_id is None:
return self._get_relation(resource_id, relation_name)
return self._get_related_resource(resource_id, relation_name,
related_resource_id)
def delete(self, resource_id):
"""Deletes the resource with the specified ID.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
for preprocessor in self.preprocessors['DELETE_RESOURCE']:
temp_result = preprocessor(resource_id=resource_id)
# See the note under the preprocessor in the get() method.
if temp_result is not None:
resource_id = temp_result
was_deleted = False
instance = get_by(self.session, self.model, resource_id,
self.primary_key)
found_model = get_model(instance)
# If no instance of the model exists with the specified instance ID,
# return a 404 response.
#
# The first condition is True exactly when there is no row in
# the table with the given primary key value. The second is True
# in the special case when the resource exists but is a subclass
# of the actual model for this API; this may happen if the model
# is a polymorphic subclass of another class using a single
# inheritance table.
if instance is None or found_model is not self.model:
detail = 'No resource found with type {0} and ID {1}'
detail = detail.format(collection_name(self.model), resource_id)
return error_response(404, detail=detail)
self.session.delete(instance)
was_deleted = len(self.session.deleted) > 0
# Flush all changes to database but do not commit the transaction
# so that postprocessors have the chance to roll it back
self.session.flush()
for postprocessor in self.postprocessors['DELETE_RESOURCE']:
postprocessor(was_deleted=was_deleted)
self.session.commit()
if not was_deleted:
detail = 'There was no instance to delete.'
return error_response(404, detail=detail)
return jsonpify({}), 204
def post(self):
"""Creates a new resource based on request data.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
# try to read the parameters for the model from the body of the request
try:
document = json.loads(request.get_data()) or {}
except (BadRequest, TypeError, ValueError, OverflowError) as exception:
detail = 'Unable to decode data'
return error_response(400, cause=exception, detail=detail)
# apply any preprocessors to the POST arguments
for preprocessor in self.preprocessors['POST_RESOURCE']:
preprocessor(data=document)
# Convert the dictionary representation into an instance of the
# model.
try:
instance = self.deserializer.deserialize(document)
self.session.add(instance)
# Flush all changes to database but do not commit the transaction
# so that postprocessors have the chance to roll it back
self.session.flush()
# This also catches subclasses of `DeserializationException`,
# like ClientGeneratedIDNotAllowed and ConflictingType.
except DeserializationException as exception:
return errors_from_deserialization_exceptions([exception])
except MultipleExceptions as e:
return errors_from_deserialization_exceptions(e.exceptions)
except self.validation_exceptions as exception:
return self._handle_validation_exception(exception)
only = self.sparse_fields.get(self.collection_name)
# Get the dictionary representation of the new instance as it
# appears in the database.
try:
result = self.serializer.serialize(instance, only=only)
except SerializationException as exception:
return errors_from_serialization_exceptions([exception])
# Determine the value of the primary key for this instance and
# encode URL-encode it (in case it is a Unicode string).
primary_key = primary_key_value(instance, as_string=True)
# The URL at which a client can access the newly created instance
# of the model.
url = '{0}/{1}'.format(request.base_url, primary_key)
# Provide that URL in the Location header in the response.
headers = dict(Location=url)
# Include any requested resources in a compound document.
try:
included = self.get_all_inclusions(instance)
except MultipleExceptions as e:
# By the way we defined `get_all_inclusions()`, we are
# guaranteed that each of the underlying exceptions is a
# `SerializationException`. Thus we can use
# `errors_from_serialization_exception()`.
return errors_from_serialization_exceptions(e.exceptions,
included=True)
if included:
result['included'].extend(included)
status = 201
for postprocessor in self.postprocessors['POST_RESOURCE']:
postprocessor(result=result)
self.session.commit()
return jsonpify(result), status, headers
def _update_instance(self, instance, data, resource_id):
"""Updates the attributes and relationships of the specified instance
according to the elements in the `data` dictionary.
`instance` must be an instance of the SQLAlchemy model class specified
in the constructor of this class.
`data` must be a dictionary representation of a resource object as
described in the `Updating Resources`_ section of the JSON API
specification.
`resource_id` is the ID of the `instance` as determined from the
URL, given as a string. This is passed directly from the
:meth:`patch` method.
.. _Updating Resources: http://jsonapi.org/format/#crud-updating
"""
# Update any relationships.
links = data.pop('relationships', {})
for linkname, link in links.items():
if not isinstance(link, dict):
detail = ('missing relationship object for "{0}" in resource'
' of type "{1}" with ID "{2}"')
detail = detail.format(linkname, self.collection_name,
resource_id)
return error_response(400, detail=detail)
# The client is obligated by JSON API to provide linkage if
# the `links` attribute exists.
if 'data' not in link:
detail = 'relationship "{0}" is missing resource linkage'
detail = detail.format(linkname)
return error_response(400, detail=detail)
linkage = link['data']
related_model = get_related_model(self.model, linkname)
# If this is a to-many relationship, get all the related
# resources.
if is_like_list(instance, linkname):
# Replacement of a to-many relationship may have been disabled
# by the user.
if not self.allow_to_many_replacement:
detail = 'Not allowed to replace a to-many relationship'
return error_response(403, detail=detail)
# The provided data must be a list for a to-many relationship.
if not isinstance(linkage, list):
detail = ('"data" element for the to-many relationship'
' "{0}" on the instance of "{1}" with ID "{2}"'
' must be a list; maybe you intended to provide'
' an empty list?')
detail = detail.format(linkname, self.collection_name,
resource_id)
return error_response(400, detail=detail)
# If this is left empty, the relationship will be zeroed.
newvalue = []
not_found = []
for rel in linkage:
expected_type = collection_name(related_model)
type_ = rel['type']
if type_ != expected_type:
detail = 'Type must be {0}, not {1}'
detail = detail.format(expected_type, type_)
return error_response(409, detail=detail)
id_ = rel['id']
inst = get_by(self.session, related_model, id_)
if inst is None:
not_found.append((id_, type_))
else:
newvalue.append(inst)
# If any of the requested to-many linkage objects do not exist,
# return an error response.
if not_found:
detail = 'No resource of type {0} found with ID {1}'
errors = [error(detail=detail.format(t, i))
for t, i in not_found]
return errors_response(404, errors)
# Otherwise, it is a to-one relationship, so just get the single
# related resource.
else:
# If the client provided "null" for this relation,
# remove it by setting the attribute to ``None``.
if linkage is None:
newvalue = None
else:
expected_type = collection_name(related_model)
type_ = linkage['type']
if type_ != expected_type:
detail = 'Type must be {0}, not {1}'
detail = detail.format(expected_type, type_)
return error_response(409, detail=detail)
id_ = linkage['id']
inst = get_by(self.session, related_model, id_)
# If the to-one relationship resource does not
# exist, return an error response.
if inst is None:
detail = 'No resource of type {0} found with ID {1}'
detail = detail.format(type_, id_)
return error_response(404, detail=detail)
newvalue = inst
# Set the new value of the relationship.
try:
# TODO Here if there are any extra attributes in
# newvalue[inst], (1) get the secondary association object for
# that relation, then (2) set the extra attributes on that
# object.
setattr(instance, linkname, newvalue)
except self.validation_exceptions as exception:
return self._handle_validation_exception(exception)
# Now consider only the attributes to update.
data = data.pop('attributes', {})
# Check for any request parameter naming a column which does not exist
# on the current model.
for field in data:
if not has_field(self.model, field):
detail = "Model does not have field '{0}'".format(field)
return error_response(400, detail=detail)
# Special case: if there are any dates, convert the string form of the
# date into an instance of the Python ``datetime`` object.
data = dict((k, string_to_datetime(self.model, k, v))
for k, v in data.items())
# Finally, update each attribute individually.
try:
if data:
for field, value in data.items():
setattr(instance, field, value)
# Flush all changes to database but do not commit the transaction
# so that postprocessors have the chance to roll it back
self.session.flush()
except self.validation_exceptions as exception:
return self._handle_validation_exception(exception)
def patch(self, resource_id):
"""Updates the resource with the specified ID according to the request
data.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
# try to load the fields/values to update from the body of the request
try:
data = json.loads(request.get_data()) or {}
except (BadRequest, TypeError, ValueError, OverflowError) as exception:
# this also happens when request.data is empty
detail = 'Unable to decode data'
return error_response(400, cause=exception, detail=detail)
for preprocessor in self.preprocessors['PATCH_RESOURCE']:
temp_result = preprocessor(resource_id=resource_id, data=data)
# See the note under the preprocessor in the get() method.
if temp_result is not None:
resource_id = temp_result
# Get the instance on which to set the new attributes.
instance = get_by(self.session, self.model, resource_id,
self.primary_key)
found_model = get_model(instance)
# If no instance of the model exists with the specified instance ID,
# return a 404 response.
#
# The first condition is True exactly when there is no row in
# the table with the given primary key value. The second is True
# in the special case when the resource exists but is a subclass
# of the actual model for this API; this may happen if the model
# is a polymorphic subclass of another class using a single
# inheritance table.
if instance is None or found_model is not self.model:
detail = 'No resource found with type {0} and ID {1}'
detail = detail.format(collection_name(self.model), resource_id)
return error_response(404, detail=detail)
# Unwrap the data from the collection name key.
data = data.pop('data', {})
if 'type' not in data:
detail = 'Missing "type" element'
return error_response(400, detail=detail)
if 'id' not in data:
detail = 'Missing resource ID'
return error_response(400, detail=detail)
type_ = data.pop('type')
id_ = data.pop('id')
# Check that the requested type matches the expected collection
# name for this model.
if type_ != self.collection_name:
detail = 'expected type {0}, not {1}'
detail = detail.format(self.collection_name, type_)
return error_response(409, detail=detail)
# Check that the ID is a string, as required by the "Resource
# Object: Identification" section of the JSON API specification.
if not isinstance(id_, STRING_TYPES):
detail = ('The "id" element of the resource object must be a JSON'
' string: {0}')
detail = detail.format(id_)
return error_response(409, detail=detail)
if id_ != resource_id:
message = 'ID must be {0}, not {1}'.format(resource_id, id_)
return error_response(409, detail=message)
result = self._update_instance(instance, data, resource_id)
# If result is not None, that means there was an error updating the
# resource.
if result is not None:
return result
# If we believe that the resource changes in ways other than the
# updates specified by the request, we must return 200 OK and a
# representation of the modified resource.
if self.changes_on_update:
only = self.sparse_fields.get(self.collection_name)
try:
result = self.serializer.serialize(instance, only=only)
except SerializationException as exception:
return errors_from_serialization_exceptions([exception])
status = 200
else:
result = dict()
status = 204
# Perform any necessary postprocessing.
for postprocessor in self.postprocessors['PATCH_RESOURCE']:
postprocessor(result=result)
self.session.commit()
return jsonpify(result), status
| 34,549
|
Python
|
.py
| 650
| 40.686154
| 79
| 0.616258
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,626
|
function.py
|
jfinkels_flask-restless/flask_restless/views/function.py
|
# function.py - views for evaluating SQL functions on SQLAlchemy models
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Views for evaluating functions on a SQLAlchemy model.
The main class in this module, :class:`FunctionAPI`, is a
:class:`~flask.MethodView` subclass that creates endpoints for fetching
the result of evaluating a SQL function on a SQLAlchemy model.
"""
from flask import json
from flask import request
from sqlalchemy.exc import OperationalError
from sqlalchemy.sql import func
from ..search import create_filters
from ..search import FilterParsingError
from ..search import FilterCreationError
from .base import error_response
from .base import jsonpify
from .base import ModelView
from .base import SingleKeyError
def create_function_query(session, model, functions):
"""Creates a SQLAlchemy query representing the given SQLAlchemy functions.
`session` is the SQLAlchemy session in which all database
transactions will be performed.
`model` is the SQLAlchemy model class on which the specified
functions will be evaluated.
``functions`` is a non-empty list of dictionaries of the form::
{'name': 'avg', 'field': 'amount'}
The return value of this function is a SQLAlchemy query with the
given functions applied.
If a field does not exist on a given model, :exc:`AttributeError` is
raised. If a function does not exist,
:exc:`sqlalchemy.exc.OperationalError` is raised. The former
exception will have a ``field`` attribute which is the name of the
field which does not exist. The latter exception will have a
``function`` attribute which is the name of the function with does
not exist.
"""
processed = []
for function in functions:
if 'name' not in function:
raise KeyError('Missing `name` key in function object')
if 'field' not in function:
raise KeyError('Missing `field` key in function object')
funcname, fieldname = function['name'], function['field']
# We retrieve the function by name from the SQLAlchemy ``func``
# module and the field by name from the model class.
#
# If the specified field doesn't exist, this raises AttributeError.
funcobj = getattr(func, funcname)
try:
field = getattr(model, fieldname)
except AttributeError as exception:
exception.field = fieldname
raise exception
processed.append(funcobj(field))
return session.query(*processed)
class FunctionAPI(ModelView):
"""Provides method-based dispatching for :http:method:`get` requests which
wish to apply SQL functions to all instances of a model.
.. versionadded:: 0.4
"""
# TODO Currently, this method first creates a query from the given
# functions, then applies the filters to the query
# afterwards. However, in SQLAlchemy 1.0.0, we could use the
# :func:`sqlalchemy.funcfilter` function for backends that support
# the FILTER clause with aggregate functions.
def get(self):
"""Returns the result of evaluating the SQL functions specified in the
body of the request.
For a description of the request and response formats, see
:ref:`functionevaluation`.
"""
# Get the functions list from the query parameters.
if 'functions' not in request.args:
detail = 'Must provide `functions` query parameter'
return error_response(400, detail=detail)
functions = request.args.get('functions')
try:
functions = json.loads(str(functions)) or []
except (TypeError, ValueError, OverflowError) as exception:
detail = 'Unable to decode JSON in `functions` query parameter'
return error_response(400, cause=exception, detail=detail)
# If there are no functions to execute, simply return the empty list.
if not functions:
return jsonpify({'data': []})
# Create the function query.
try:
query = create_function_query(self.session, self.model, functions)
except AttributeError as exception:
detail = 'unknown field "{0}"'.format(exception.field)
return error_response(400, cause=exception, detail=detail)
except KeyError as exception:
detail = str(exception)
return error_response(400, cause=exception, detail=detail)
# Get the filtering, sorting, and grouping parameters.
try:
filters, sort, group_by, single, ignorecase = \
self.collection_parameters()
except (TypeError, ValueError, OverflowError) as exception:
detail = 'Unable to decode filter objects as JSON list'
return error_response(400, cause=exception, detail=detail)
except SingleKeyError as exception:
detail = 'Invalid format for filter[single] query parameter'
return error_response(400, cause=exception, detail=detail)
try:
# Create the filtered query according to the parameters.
filters = create_filters(self.model, filters)
# Apply the filters to the query.
query = query.filter(*filters)
except (FilterParsingError, FilterCreationError) as exception:
detail = 'invalid filter object: {0}'.format(str(exception))
return error_response(400, cause=exception, detail=detail)
# Evaluate all the functions at once and get a list of results.
try:
result = list(query.one())
except OperationalError as exception:
# HACK original error message is of the form:
#
# '(OperationalError) no such function: bogusfuncname'
#
original_msg = exception.args[0]
bad_function = original_msg[37:]
detail = 'unknown function "{0}"'.format(bad_function)
return error_response(400, cause=exception, detail=detail)
return jsonpify({'data': result})
| 6,438
|
Python
|
.py
| 133
| 40.691729
| 78
| 0.686306
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,627
|
__init__.py
|
jfinkels_flask-restless/flask_restless/views/__init__.py
|
# __init__.py - indicates that this directory is a Python package
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""View classes for responding to JSON API requests with a SQLAlchemy
backend.
The classes :class:`API`, :class:`FunctionAPI`, and
:class:`RelationshipAPI` are the :class:`~flask.MethodView` subclasses
that do most of the work.
"""
from .base import JSONAPI_MIMETYPE
from .base import ProcessingException
from .base import SchemaView
from .resources import API
from .relationships import RelationshipAPI
from .function import FunctionAPI
__all__ = [
'API',
'FunctionAPI',
'JSONAPI_MIMETYPE',
'ProcessingException',
'RelationshipAPI',
'SchemaView',
]
| 1,053
|
Python
|
.py
| 31
| 32.096774
| 72
| 0.766438
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,628
|
base.py
|
jfinkels_flask-restless/flask_restless/views/base.py
|
# base.py - base classes for views of SQLAlchemy objects
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Base classes for fetching, creating, updating, and deleting
SQLAlchemy resources and relationships.
The main class in this module, :class:`APIBase`, is a
:class:`~flask.MethodView` subclass that is also an abstract base class
for JSON API requests on a SQLAlchemy backend.
"""
from __future__ import division
from collections import defaultdict
from functools import partial
from functools import wraps
from itertools import chain
import math
import re
# In Python 3...
try:
from urllib.parse import parse_qs
from urllib.parse import urlencode
from urllib.parse import urlparse
from urllib.parse import urlunparse
# In Python 2...
except ImportError:
from urllib import urlencode
from urlparse import parse_qs
from urlparse import urlparse
from urlparse import urlunparse
from flask import current_app
from flask import json
from flask import request
from flask.views import MethodView
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm.exc import MultipleResultsFound
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.query import Query
from werkzeug import parse_options_header
from werkzeug.exceptions import HTTPException
from ..helpers import collection_name
from ..helpers import get_model
from ..helpers import get_related_model
from ..helpers import is_like_list
from ..helpers import is_relationship
from ..helpers import primary_key_for
from ..helpers import primary_key_value
from ..helpers import serializer_for
from ..helpers import url_for
from ..search import FilterCreationError
from ..search import FilterParsingError
from ..search import search
from ..search import search_relationship
from ..serialization import DeserializationException
from ..serialization import JsonApiDocument
from ..serialization import MultipleExceptions
from ..serialization import simple_serialize_many
from ..serialization import simple_relationship_serialize
from ..serialization import simple_relationship_serialize_many
from ..serialization import SerializationException
from .helpers import count
from .helpers import upper_keys as upper
#: The Content-Type we expect for most requests to APIs.
#:
#: The JSON API specification requires the content type to be
#: ``application/vnd.api+json``.
JSONAPI_MIMETYPE = 'application/vnd.api+json'
#: The Content-Type for Javascript data.
#:
#: This is used, for example, in JSONP responses.
JAVASCRIPT_MIMETYPE = 'application/javascript'
#: The highest version of the JSON API specification supported by
#: Flask-Restless.
JSONAPI_VERSION = '1.0'
#: Strings that indicate a database conflict when appearing in an error
#: message of an exception raised by SQLAlchemy.
#:
#: The particular error message depends on the particular environment
#: containing the SQLite backend, it seems.
CONFLICT_INDICATORS = ('conflicts with', 'UNIQUE constraint failed',
'is not unique')
#: The names of pagination links that appear in both ``Link`` headers
#: and JSON API links.
LINK_NAMES = ('first', 'last', 'prev', 'next')
#: The query parameter key that identifies filter objects in a
#: :http:method:`get` request.
FILTER_PARAM = 'filter[objects]'
#: The query parameter key that indicates whether to expect a single
#: resource in the response.
SINGLE_PARAM = 'filter[single]'
#: The query parameter key that identifies sort fields in a :http:method:`get`
#: request.
SORT_PARAM = 'sort'
#: The query parameter key that indicates whether sorting is case-insensitive.
IGNORECASE_PARAM = 'ignorecase'
#: The query parameter key that identifies grouping fields in a
#: :http:method:`get` request.
GROUP_PARAM = 'group'
#: The query parameter key that identifies the page number in a
#: :http:method:`get` request.
PAGE_NUMBER_PARAM = 'page[number]'
#: The query parameter key that identifies the page size in a
#: :http:method:`get` request.
PAGE_SIZE_PARAM = 'page[size]'
#: A regular expression for Accept headers.
#:
#: For an explanation of "media-range", etc., see Sections 5.3.{1,2} of
#: RFC 7231.
ACCEPT_RE = re.compile(
r'''( # media-range capturing-parenthesis
[^\s;,]+ # type/subtype
(?:[ \t]*;[ \t]* # ";"
(?: # parameter non-capturing-parenthesis
[^\s;,q][^\s;,]* # token that doesn't start with "q"
| # or
q[^\s;,=][^\s;,]* # token that is more than just "q"
)
)* # zero or more parameters
) # end of media-range
(?:[ \t]*;[ \t]*q= # weight is a "q" parameter
(\d*(?:\.\d+)?) # qvalue capturing-parentheses
[^,]* # "extension" accept params: who cares?
)? # accept params are optional
''', re.VERBOSE)
#: Keys in a JSON API error object.
ERROR_FIELDS = ('id_', 'links', 'status', 'code_', 'title', 'detail', 'source',
'meta')
# For the sake of brevity, rename this function.
chain = chain.from_iterable
class SingleKeyError(KeyError):
"""Raised when attempting to parse the "single" query parameter reveals
that the client did not correctly provide a Boolean value.
"""
pass
class PaginationError(Exception):
"""Raised when pagination fails, due to, for example, a bad
pagination parameter supplied by the client.
"""
pass
class ProcessingException(HTTPException):
"""Raised when a preprocessor or postprocessor encounters a problem.
This exception should be raised by functions supplied in the
``preprocessors`` and ``postprocessors`` keyword arguments to
:class:`APIManager.create_api`. When this exception is raised, all
preprocessing or postprocessing halts, so any processors appearing
later in the list will not be invoked.
The keyword arguments ``id_``, ``href`` ``status``, ``code``,
``title``, ``detail``, ``links``, ``paths`` correspond to the
elements of the JSON API error object; the values of these keyword
arguments will appear in the error object returned to the client.
Any additional positional or keyword arguments are supplied directly
to the superclass, :exc:`werkzeug.exceptions.HTTPException`.
"""
def __init__(self, id_=None, links=None, status=400, code=None, title=None,
detail=None, source=None, meta=None, *args, **kw):
super(ProcessingException, self).__init__(*args, **kw)
self.id_ = id_
self.links = links
self.status = status
# This attribute would otherwise override the class-level
# attribute `code` in the superclass, HTTPException.
self.code_ = code
self.code = status
self.title = title
self.detail = detail
self.source = source
self.meta = meta
def _is_msie8or9():
"""Returns ``True`` if and only if the user agent of the client making the
request indicates that it is Microsoft Internet Explorer 8 or 9.
.. note::
We have no way of knowing if the user agent is lying, so we just make
our best guess based on the information provided.
"""
if request.user_agent is None or request.user_agent.browser != 'msie' \
or request.user_agent.version is None:
return False
# request.user_agent.version comes as a string, so we have to parse it
version = tuple(map(int, request.user_agent.version.split('.')))
return (8, 0) <= version < (10, 0)
def un_camel_case(s):
"""Inserts spaces before the capital letters in a camel case string.
"""
# This regular expression appears on StackOverflow
# <http://stackoverflow.com/a/199120/108197>, and is distributed
# under the Creative Commons Attribution-ShareAlike 3.0 Unported
# license.
return re.sub(r'(?<=\w)([A-Z])', r' \1', s)
def catch_processing_exceptions(func):
"""Decorator that catches :exc:`ProcessingException`s and subsequently
returns a JSON-ified error response.
"""
@wraps(func)
def new_func(*args, **kw):
"""Executes ``func(*args, **kw)`` but catches
:exc:`ProcessingException`s.
"""
try:
return func(*args, **kw)
except ProcessingException as exception:
# TODO In Python 2.7 and later, this should be a dict comprehension
kw = dict((key, getattr(exception, key)) for key in ERROR_FIELDS)
# Need to change the name of the `code` key as a workaround
# for name collisions with Werkzeug exception classes.
kw['code'] = kw.pop('code_')
return error_response(cause=exception, **kw)
return new_func
# This code is (lightly) adapted from the ``werkzeug`` library, in the
# ``werkzeug.http`` module. See <http://werkzeug.pocoo.org> for more
# information.
def parse_accept_header(value):
"""Parses an HTTP Accept-* header.
This does not implement a complete valid algorithm but one that
supports at least value and quality extraction.
`value` is the :http:header:`Accept` header string (everything after
the ``Accept:``) to be parsed.
Returns an iterator over ``(value, extra)`` tuples. If there were no
media type parameters, then ``extra`` is simply ``None``.
"""
for match in ACCEPT_RE.finditer(value):
name = match.group(1)
extra = match.group(2)
# This is the main difference between our implementation and
# Werkzeug's implementation: all we want to know is whether
# there is any media type parameters or not, so we mark the
# quality as ``None`` instead of ``1`` here.
quality = max(min(float(extra), 1), 0) if extra else None
yield name, quality
def requires_json_api_accept(func):
"""Decorator that requires :http:header:`Accept` headers with the
JSON API media type to have no media type parameters.
This does *not* require that all requests have an
:http:header:`Accept` header, just that those requests with an
:http:header:`Accept` header for the JSON API media type have no
media type parameters. However, if there are only
:http:header:`Accept` headers that specify non-JSON API media types,
this will cause a :http:status`406` response.
If a request does not have the correct ``Accept`` header, a
:http:status:`406` response is returned. An incorrect header is
described in the `Server Responsibilities`_ section of the JSON API
specification:
Servers MUST respond with a 406 Not Acceptable status code if a
request's Accept header contains the JSON API media type and all
instances of that media type are modified with media type
parameters.
Headers of the form ``Accept: */*`` are okay, though, as required by
:rfc:`2616#sec14.1`.
View methods can be wrapped like this::
@requires_json_api_accept
def get(self, *args, **kw):
return '...'
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
@wraps(func)
def new_func(*args, **kw):
"""Executes ``func(*args, **kw)`` only after checking for the
correct JSON API :http:header:`Accept` header.
"""
header = request.headers.get('Accept')
# If there is no Accept header, we don't need to do anything.
if header is None:
return func(*args, **kw)
header_pairs = list(parse_accept_header(header))
# If the Accept header is empty, then do nothing.
#
# An empty Accept header is technically allowed by RFC 2616,
# Section 14.1 (for more information, see
# http://stackoverflow.com/a/12131993/108197). Since an empty
# Accept header doesn't violate JSON APIs rule against having
# only JSON API mimetypes with media type parameters, we simply
# proceed as normal with the request.
if len(header_pairs) == 0:
return func(*args, **kw)
# If the Accept header includes */*, then proceed as normal,
# since */* captures the appropriate JSON API content type.
if any(name == '*/*' for name, extra in header_pairs):
return func(*args, **kw)
jsonapi_pairs = [(name, extra) for name, extra in header_pairs
if name.startswith(JSONAPI_MIMETYPE)]
# If there are Accept headers but none of them specifies the
# JSON API media type, respond with `406 Not Acceptable`.
if len(jsonapi_pairs) == 0:
detail = ('Accept header, if specified, must be the JSON API media'
' type: application/vnd.api+json')
return error_response(406, detail=detail)
# If there are JSON API Accept headers, but they all have media
# type parameters, respond with `406 Not Acceptable`.
if all(extra is not None for name, extra in jsonapi_pairs):
detail = ('Accept header contained JSON API content type, but each'
' instance occurred with media type parameters; at least'
' one instance must appear without parameters (the part'
' after the semicolon)')
return error_response(406, detail=detail)
# At this point, everything is fine, so just execute the method as-is.
return func(*args, **kw)
return new_func
def requires_json_api_mimetype(func):
"""Decorator that requires requests *that include data* have the
:http:header:`Content-Type` header required by the JSON API
specification.
If the request does not have the correct :http:header:`Content-Type`
header, a :http:status:`415` response is returned.
View methods can be wrapped like this::
@requires_json_api_mimetype
def get(self, *args, **kw):
return '...'
"""
@wraps(func)
def new_func(*args, **kw):
"""Executes ``func(*args, **kw)`` only after checking for the
correct JSON API :http:header:`Content-Type` header.
"""
# GET and DELETE requests don't have request data in JSON API,
# so we can ignore those and only continue if this is a PATCH or
# POST request.
#
# Ideally we would be able to decorate each individual request
# methods directly, but it is not possible with the current
# design of Flask's method-based views.
if request.method not in ('PATCH', 'POST'):
return func(*args, **kw)
header = request.headers.get('Content-Type')
content_type, extra = parse_options_header(header)
content_is_json = content_type.startswith(JSONAPI_MIMETYPE)
is_msie = _is_msie8or9()
# Request must have the Content-Type: application/vnd.api+json header,
# unless the User-Agent string indicates that the client is Microsoft
# Internet Explorer 8 or 9 (which has a fixed Content-Type of
# 'text/html'; for more information, see issue #267).
if not is_msie and not content_is_json:
detail = ('Request must have "Content-Type: {0}"'
' header').format(JSONAPI_MIMETYPE)
return error_response(415, detail=detail)
# JSON API requires that the content type header does not have
# any media type parameters.
if extra:
detail = ('Content-Type header must not have any media type'
' parameters but found {0}'.format(extra))
return error_response(415, detail=detail)
return func(*args, **kw)
return new_func
def catch_integrity_errors(session):
"""Returns a decorator that catches database integrity errors.
`session` is the SQLAlchemy session in which all database transactions will
be performed.
View methods can be wrapped like this::
@catch_integrity_errors(session)
def get(self, *args, **kw):
return '...'
Specifically, functions wrapped with the returned decorator catch the
exceptions specified in :data:`ROLLBACK_ERRORS`. After the exceptions are
caught, the session is rolled back, the exception is logged on the current
Flask application, and an error response is returned to the client.
"""
def decorated(func):
"""Returns a decorated version of ``func``, as described in the
wrapper defined within.
"""
@wraps(func)
def wrapped(*args, **kw):
"""Executes ``func(*args, **kw)`` but catches any exception
that warrants a database rollback.
"""
try:
return func(*args, **kw)
# This should include: DataError, IntegrityError,
# ProgrammingError, FlushError, OperationalError,
# InalidRequestError, and any other SQLAlchemyError
# subclass.
except SQLAlchemyError as exception:
session.rollback()
# Special status code for conflicting instances: 409 Conflict
status = 409 if is_conflict(exception) else 400
detail = str(exception)
title = un_camel_case(exception.__class__.__name__)
return error_response(status, cause=exception, detail=detail,
title=title)
return wrapped
return decorated
def is_conflict(exception):
"""Returns ``True`` if and only if the specified exception represents a
conflict in the database.
"""
exception_string = str(exception)
return any(s in exception_string for s in CONFLICT_INDICATORS)
def jsonpify(data):
"""Creates a HTTP response containing JSON or JSONP data.
`data` is a dictionary representing a JSON object.
If the incoming HTTP request has no query parameter ``callback``,
then the body of the response will be a JSON document and the
:http:header:`Content-Type` will be ``application/vnd.api+json``,
the JSON API mimetype. If the request has a query parameter
``callback=foo``, then the body of the response will be
``foo(<json>)``, where ``<json>`` is the JSON object that would have
been returned, and the :http:header:`Content-Type` will be
``application/javascript``.
"""
document = json.dumps(data)
mimetype = JSONAPI_MIMETYPE
callback = request.args.get('callback', False)
if callback:
document = '{0}({1})'.format(callback, document)
mimetype = JAVASCRIPT_MIMETYPE
response = current_app.response_class(document, mimetype=mimetype)
return response
def parse_sparse_fields(type_=None):
"""Get the sparse fields as requested by the client.
Returns a dictionary mapping resource type names to set of fields to
include for that resource.
For example, if the client requests::
GET /articles?fields[articles]=title,body&fields[people]=name
then::
>>> parse_sparse_fields()
{'articles': {'title', 'body'}, 'people': {'name'}}
If the `type_` argument is given, only the set of fields for that resource
type will be returned::
>>> parse_sparse_fields('articles')
{'title', 'body'}
"""
# TODO use a regular expression to ensure field parameters are of the
# correct format? (maybe ``fields\[[^\[\]\.]*\]``)
# TODO In Python 2.7 and later, this should be a dictionary comprehension.
fields = dict((key[7:-1], set(value.split(',')))
for key, value in request.args.items()
if key.startswith('fields[') and key.endswith(']'))
return fields.get(type_) if type_ is not None else fields
def resources_from_path(instance, path):
"""Returns an iterable of all resources along the given relationship
path for the specified instance of the model.
For example, if our model includes three classes, ``Article``,
``Person``, and ``Comment``::
>>> article = Article(id=1)
>>> comment1 = Comment(id=1)
>>> comment2 = Comment(id=2)
>>> person1 = Person(id=1)
>>> person2 = Person(id=2)
>>> article.comments = [comment1, comment2]
>>> comment1.author = person1
>>> comment2.author = person2
>>> instances = [article, comment1, comment2, person1, person2]
>>> session.add_all(instances)
>>>
>>> l = list(api.resources_from_path(article, 'comments.author'))
>>> len(l)
4
>>> [r.id for r in l if isinstance(r, Person)]
[1, 2]
>>> [r.id for r in l if isinstance(r, Comment)]
[1, 2]
"""
# First, split the path to determine the sequence of relationships
# to follow.
if '.' in path:
path = path.split('.')
else:
path = [path]
# Next, do a breadth-first traversal of the resources related to
# `instance` via the given path.
seen = set()
# TODO In Pyhon 2.7 and later, this should be a set literal.
nextlevel = set([instance])
first_time = True
while nextlevel:
thislevel = nextlevel
nextlevel = set()
# Follow the relation given in the path to get the "neighbor"
# resources of any resource in the curret level of the
# breadth-first traversal.
if path:
relation = path.pop(0)
else:
relation = None
for resource in thislevel:
if resource in seen:
continue
# Since this method is going to be used to populate the
# `included` section of a compound document, we don't want
# to yield the instance from which related resources are
# being included.
if first_time:
first_time = False
else:
yield resource
seen.add(resource)
# If there are still parts of the relationship path to
# traverse, queue up the related resources at the next
# level.
if relation is not None:
if is_like_list(resource, relation):
update = nextlevel.update
else:
update = nextlevel.add
update(getattr(resource, relation))
# TODO these need to become JSON Pointers
def extract_error_messages(exception):
"""Tries to extract a dictionary mapping field name to validation error
messages from `exception`, which is a validation exception as provided in
the ``validation_exceptions`` keyword argument to the constructor of the
:class:`APIBase` class.
Since the type of the exception is provided by the user in the constructor
of that class, we cannot know for sure where the validation error messages
live inside `exception`. Therefore this method simply attempts to access a
few likely attributes and returns the first one it finds (or ``None`` if no
error messages dictionary can be extracted).
"""
# Check for our own built-in validation error.
if isinstance(exception, DeserializationException):
return exception.args[0]
# Try some common names error message attributes.
if hasattr(exception, 'errors'):
return exception.errors
if hasattr(exception, 'message'):
return exception.message
if hasattr(exception, '__str__'):
return str(exception)
return None
def error(id_=None, links=None, status=None, code=None, title=None,
detail=None, source=None, meta=None):
"""Returns a dictionary representation of an error as described in the
JSON API specification.
Note: the ``id_`` keyword argument corresponds to the ``id`` element
of the JSON API error object.
For more information, see the `Errors`_ section of the JSON API
specification.
.. Errors_: http://jsonapi.org/format/#errors
"""
# HACK We use locals() so we don't have to list every keyword argument.
if all(kwvalue is None for kwvalue in locals().values()):
raise ValueError('At least one of the arguments must not be None.')
return {'id': id_, 'links': links, 'status': status, 'code': code,
'title': title, 'detail': detail, 'source': source, 'meta': meta}
def error_response(status=400, cause=None, **kw):
"""Returns a correctly formatted error response with the specified
parameters.
This is a convenience function for::
errors_response(status, [error(**kw)])
For more information, see :func:`errors_response`.
"""
if cause is not None:
current_app.logger.exception(str(cause))
kw['status'] = status
return errors_response(status, [error(**kw)])
def errors_response(status, errors):
"""Return an error response with multiple errors.
`status` is an integer representing an HTTP status code corresponding to an
error response.
`errors` is a list of error dictionaries, each of which must satisfy the
requirements of the JSON API specification.
This function returns a two-tuple whose left element is a dictionary
representing a JSON API response document and whose right element is
simply `status`.
The keys within each error object are described in the `Errors`_
section of the JSON API specification.
.. _Errors: http://jsonapi.org/format/#errors
"""
# TODO Use an error serializer.
document = {'errors': errors, 'jsonapi': {'version': JSONAPI_VERSION}}
return jsonpify(document), status
def error_from_serialization_exception(exception, included=False):
"""Returns an error dictionary, as returned by :func:`error`,
representing the given instance of :exc:`SerializationException`.
The ``detail`` element in the returned dictionary will be more
detailed if :attr:`SerializationException.instance` is not ``None``.
If `included` is ``True``, this indicates that the exceptions were
raised by attempts to serialize resources included in a compound
document; this modifies the error message for the exceptions a bit
to indicate that the resources were included resource, not primary
data. If :attr:`~SerializationException.instance` is not ``None``,
however, that message is preferred and `included` has no effect.
"""
# As long as `exception` is a `SerializationException` that has been
# initialized with an actual instance of a SQLAlchemy model, these
# helper function calls should not cause a problem.
type_ = collection_name(get_model(exception.instance))
id_ = primary_key_value(exception.instance)
if exception.message is not None:
detail = exception.message
else:
resource = 'included resource' if included else 'resource'
detail = 'Failed to serialize {0} of type {1} and ID {2}'
detail = detail.format(resource, type_, id_)
return error(status=500, detail=detail)
def errors_from_serialization_exceptions(exceptions, included=False):
"""Returns an errors response object, as returned by
:func:`errors_response`, representing the given list of
:exc:`SerializationException` objects.
If `included` is ``True``, this indicates that the exceptions were
raised by attempts to serialize resources included in a compound
document; this modifies the error message for the exceptions a bit.
"""
_to_error = partial(error_from_serialization_exception, included=included)
errors = list(map(_to_error, exceptions))
return errors_response(500, errors)
# TODO Subclasses for different kinds of linkers (relationship, resource
# object, to-one relations, related resource, etc.).
class Linker(object):
def __init__(self, model):
self.model = model
def _related_resource_links(self, resource, primary_resource,
relation_name):
resource_id = primary_key_value(primary_resource)
related_resource_id = primary_key_value(resource)
self_link = url_for(self.model, resource_id, relation_name,
related_resource_id)
links = {'self': self_link}
return links
def _relationship_links(self, resource_id, relation_name):
self_link = url_for(self.model, resource_id, relation_name,
relationship=True)
related_link = url_for(self.model, resource_id, relation_name)
links = {'self': self_link, 'related': related_link}
return links
def _to_one_relation_links(self, resource_id, relation_name):
self_link = url_for(self.model, resource_id, relation_name)
links = {'self': self_link}
return links
def _primary_resource_links(self, resource_id):
self_link = url_for(self.model, resource_id=resource_id)
links = {'self': self_link}
return links
def _collection_links(self):
self_link = url_for(self.model)
links = {'self': self_link}
return links
def generate_links(self, resource, primary_resource, relation_name,
is_related_resource, is_relationship):
if primary_resource is not None:
if is_related_resource:
return self._related_resource_links(resource, primary_resource,
relation_name)
else:
resource_id = primary_key_value(primary_resource)
if is_relationship:
return self._relationship_links(resource_id, relation_name)
else:
return self._to_one_relation_links(resource_id,
relation_name)
else:
if resource is not None:
resource_id = primary_key_value(resource)
return self._primary_resource_links(resource_id)
else:
return self._collection_links()
class PaginationLinker(object):
def __init__(self, pagination):
self.pagination = pagination
def generate_links(self):
return self.pagination.pagination_links
def generate_header_links(self):
return self.pagination.header_links
class Paginated(object):
"""Represents a paginated list of resources.
This class is intended to be instantiated *after* the correct page
of a collection has been computed. It is mainly used to handle link
URLs for JSON API documents and HTTP headers.
`items` is a list of dictionaries, each of which is a JSON API
resource, either a resource object or a link object.
`page_size` and `page_number` are the size and number of the current
page (that is, the page containing `items`). If `page_size` is zero,
then `items` must be *all* the items in the collection requested by
the client. In this particular case, this object does not really
represent a paginated response. Thus, there will be no pagination or
header links; see :attr:`header_links` and
:attr:`pagination_links`. Otherwise, `page_size` must be at least as
large as the length of `items`.
`num_results` is the total number of resources or link objects on
all pages, not just the page represented by `items`.
`first`, `last`, `prev`, and `next_` are integers representing the
number of the first, last, previous, and next pages,
respectively. These can also be ``None``, in the case that there is
no such page.
`filters`, `sort`, and `group_by` are the filtering, sorting, and
grouping query parameters from the request that yielded the given
items.
After instantiating this object, one can access a list of link
header strings and a dictionary of pagination link strings as
suggested by the JSON API specification, as well as the number of
results and the items provided in the constructor. For example::
>>> people = ['person1', 'person2', 'person3']
>>> paginated = Paginated(people, num_results=10, page_number=2,
... page_size=3, first=1, last=4, prev=1, next=3)
>>> paginated.items
['person1', 'person2', 'person3']
>>> paginated.num_results
10
>>> for rel, url in paginated.pagination_links.items():
... print(rel, url)
...
first http://localhost/api/person?page[size]=3&page[number]=1
last http://localhost/api/person?page[size]=3&page[number]=4
prev http://localhost/api/person?page[size]=3&page[number]=1
next http://localhost/api/person?page[size]=3&page[number]=3
>>> for link in paginated.header_links:
... print(link)
...
<http://localhost/api/person?page[size]=3&page[number]=1>; rel="first"
<http://localhost/api/person?page[size]=3&page[number]=4>; rel="last"
<http://localhost/api/person?page[size]=3&page[number]=1>; rel="prev"
<http://localhost/api/person?page[size]=3&page[number]=3>; rel="next"
"""
@staticmethod
def _filters_to_string(filters):
"""Returns a string representation of the specified dictionary
of filter objects.
This is essentially the inverse operation of the parsing that is
done when reading the filter objects from the query parameters
of the request string in a :http:method:`get` request.
"""
return json.dumps(filters)
@staticmethod
def _sort_to_string(sort):
"""Returns a string representation of the specified sort fields.
This is essentially the inverse operation of the parsing that is
done when reading the sort fields from the query parameters of
the request string in a :http:method:`get` request.
"""
return ','.join(''.join((dir_, field)) for dir_, field in sort)
@staticmethod
def _group_to_string(group_by):
"""Returns a string representation of the specified grouping
fields.
This is essentially the inverse operation of the parsing that is
done when reading the grouping fields from the query parameters
of the request string in a :http:method:`get` request.
"""
return ','.join(group_by)
@staticmethod
def _url_without_pagination_params():
"""Returns the request URL including all query parameters except
the page size and page number query parameters.
The URL is returned as a string.
"""
# Parse pieces of the URL requested by the client.
base_url = request.base_url
query_params = request.args
# Set the new query_parameters to be everything except the
# pagination query parameters.
#
# TODO In Python 3, this should be a dict comprehension.
new_query = dict((k, v) for k, v in query_params.items()
if k not in (PAGE_NUMBER_PARAM, PAGE_SIZE_PARAM))
# TODO Use urllib.parse functions here.
new_query_string = '&'.join(map('='.join, new_query.items()))
# Join the base URL with the query parameter string.
return '{0}?{1}'.format(base_url, new_query_string)
@staticmethod
def _to_url(base_url, query_params):
"""Returns the specified base URL augmented with the given query
parameters.
`base_url` is a string representing a URL.
`query_params` is a dictionary whose keys and values are strings,
representing the query parameters to append to the given URL.
If the base URL already has query parameters, the ones given in
`query_params` are appended.
"""
scheme, netloc, path, params, query_str, fragment = urlparse(base_url)
query = defaultdict(list)
query.update(parse_qs(query_str))
for k, v in query_params.items():
query[k].append(v)
# TODO In Python 3.5+, this should be
#
# query_str = urlencode(query, doseq=True, quote_via=quote)
#
# since otherwise we get + symbols in place of encoded spaces.
query_str = urlencode(query, doseq=True)
parts = (scheme, netloc, path, params, query_str, fragment)
return urlunparse(parts)
def __init__(self, items, first=None, last=None, prev=None, next_=None,
page_size=None, num_results=None, filters=None, sort=None,
group_by=None):
self._items = items
self._num_results = num_results
# Pagination links and the link header are computed by the code below.
self._pagination_links = {}
self._header_links = []
# If page size is zero, there is really no pagination, so we
# don't need to compute pagination links or header links.
if page_size == 0:
return
query_params = {}
# The page size is independent of the link type (first, last,
# next, or prev).
query_params[PAGE_SIZE_PARAM] = str(page_size)
# Maintain a list of URLs that should appear in a Link
# header. If a link does not exist (for example, if there is no
# previous page), then that link URL will not appear in this
# list.
link_numbers = [first, last, prev, next_]
# Determine the URL as it would appear without the
# client-requested pagination query parameters.
#
# (`base_url` is not a great name here, since
# `flask.Request.base_url` is the URL *without* the query
# parameters.)
base_url = Paginated._url_without_pagination_params()
for rel, num in zip(LINK_NAMES, link_numbers):
# If the link doesn't exist (for example, if there is no
# previous page), then add ``None`` to the pagination links
# but don't add a link URL to the headers.
if num is None:
self._pagination_links[rel] = None
else:
# Each time through this `for` loop we update the page
# number in the `query_param` dictionary, so the the
# `_to_url` method will give us the correct URL for that
# page.
query_params[PAGE_NUMBER_PARAM] = str(num)
url = Paginated._to_url(base_url, query_params)
link_string = '<{0}>; rel="{1}"'.format(url, rel)
self._header_links.append(link_string)
self._pagination_links[rel] = url
# TODO Here we should really make the attributes immutable:
#
# self._header_links = ImmutableList(self._header_links)
# ...
#
@property
def header_links(self):
"""List of link header strings for the paginated response.
The headers can be provided to the HTTP response by using a
dictionary like this::
>>> paginated = Paginated(...)
>>> headers = {'Link': ','.join(paginated.header_links)}
There may be a way of creating multiple link headers like
this, in certain situations::
>>> headers = [('Link', link) for link in header_links]
"""
return self._header_links
@property
def pagination_links(self):
"""Dictionary of pagination links for JSON API documents.
This dictionary has the relationship of the page to this page as
the key (``'first'``, ``'last'``, ``'prev'``, and ``'next'``)
and the URL as the value.
"""
return self._pagination_links
@property
def items(self):
"""The items in the current page that this object represents."""
return self._items
@property
def num_results(self):
"""The total number of elements in the search result, one page
of which this object represents.
"""
return self._num_results
class SchemaView(MethodView):
"""A view of the entire schema of an API.
This class provides a :meth:`.SchemaView.get` method that returns a
JSON API document containing metadata about the models exposed by
this API.
`models` is the set of models for which an API has been defined via
the :meth:`.APIManager.create_api` method. The
:meth:`.SchemaView.get` method will call :func:`.collection_name`,
:func:`.url_for`, and :func:`.primary_key_for` on each model, so if
any is unknown, this view will raise a server-side exception.
"""
#: List of decorators applied to every method of this class.
decorators = [requires_json_api_accept, requires_json_api_mimetype]
def __init__(self, models):
self.models = models
def get(self):
result = JsonApiDocument()
modelinfo = {}
for model in self.models:
name = collection_name(model)
url = url_for(model)
key = primary_key_for(model)
modelinfo[name] = {
'url': url,
'primarykey': key,
}
if modelinfo:
result['meta']['modelinfo'] = modelinfo
return jsonpify(result)
class ModelView(MethodView):
"""Base class for :class:`flask.MethodView` classes which represent a view
of a SQLAlchemy model.
`session` is the SQLAlchemy session in which all database transactions will
be performed.
`model` is the SQLALchemy declarative model class of the database model for
which this instance of the class is an API.
The model class for this view can be accessed from the :attr:`model`
attribute, and the session in which all database transactions will be
performed when dealing with this model can be accessed from the
:attr:`session` attribute.
"""
#: List of decorators applied to every method of this class.
decorators = [requires_json_api_accept, requires_json_api_mimetype]
def __init__(self, session, model, *args, **kw):
super(ModelView, self).__init__(*args, **kw)
self.session = session
self.model = model
def collection_parameters(self, resource_id=None, relation_name=None):
"""Gets filtering, sorting, grouping, and other settings from
the request that affect the collection of resources in a
response.
Returns a four-tuple of the form ``(filters, sort, group_by,
single)``. These can be provided to the
:func:`~flask_restless.search.search` function; for more
information, see the documentation for that function.
This function can only be invoked in a request context.
"""
# Determine filtering options.
#
# `filters` stores the filter objects, which are retrieved from the
# query parameter at :data:`FILTER_PARAM`. We also support simple
# filtering, but we need to search the entire list of query
# parameters for everything of the form 'filter[...]' and convert
# each value found into a filter object.
filters = json.loads(request.args.get(FILTER_PARAM, '[]'))
for key, value in request.args.items():
# Skip keys that are not filters and are not filter[objects]
# and filter[single] request parameters.
#
# TODO Document that field names cannot be 'objects' or 'single'.
if not key.startswith('filter'):
continue
if key in (FILTER_PARAM, SINGLE_PARAM):
continue
# Get the field on which to filter and the values to match.
field = key[7:-1]
values = value.split(',')
# Determine whether this is a request of the form `GET
# /comments` or `GET /article/1/comments`.
if resource_id is not None and relation_name is not None:
primary_model = get_related_model(self.model, relation_name)
else:
primary_model = self.model
# If the field is a relationship, use the `has` operator
# with the `in` operator to select only those instances of
# the primary model that have related instances matching the
# given foreign keys. Otherwise, the field is an attribute,
# so we use the `in` operator directly.
if is_relationship(primary_model, field):
related_model = get_related_model(primary_model, field)
field_name = primary_key_for(related_model)
new_filter = {
'name': field,
'op': 'has',
'val': {
'name': field_name,
'op': 'in',
'val': values
}
}
else:
new_filter = {
'name': field,
'op': 'in',
'val': values
}
# TODO This creates a problem where the computed link URLs
# have the additional filter object as a `filter[objects]`
# param.
filters.append(new_filter)
# # TODO fix this using the below
# filters = [strings_to_dates(self.model, f) for f in filters]
# # resolve date-strings as required by the model
# for param in search_params.get('filters', list()):
# if 'name' in param and 'val' in param:
# query_model = self.model
# query_field = param['name']
# if '__' in param['name']:
# fieldname, relation = param['name'].split('__')
# submodel = getattr(self.model, fieldname)
# if isinstance(submodel, InstrumentedAttribute):
# query_model = submodel.property.mapper.class_
# query_field = relation
# elif isinstance(submodel, AssociationProxy):
# # For the sake of brevity, rename this function.
# get_assoc = get_related_association_proxy_model
# query_model = get_assoc(submodel)
# query_field = relation
# to_convert = {query_field: param['val']}
# try:
# result = strings_to_dates(query_model, to_convert)
# except ValueError as exception:
# current_app.logger.exception(str(exception))
# return dict(message='Unable to construct query'), 400
# param['val'] = result.get(query_field)
# Determine sorting options.
sort = request.args.get(SORT_PARAM)
if sort:
sort = [('-', value[1:]) if value.startswith('-') else ('+', value)
for value in sort.split(',')]
else:
sort = []
ignorecase = bool(int(request.args.get(IGNORECASE_PARAM, '0')))
# Determine grouping options.
group_by = request.args.get(GROUP_PARAM)
if group_by:
group_by = group_by.split(',')
else:
group_by = []
# Determine whether the client expects a single resource response.
try:
single = bool(int(request.args.get(SINGLE_PARAM, 0)))
except ValueError:
raise SingleKeyError('failed to extract Boolean from parameter')
return filters, sort, group_by, single, ignorecase
class APIBase(ModelView):
"""Base class for view classes that provide fetch, create, update, and
delete functionality for resources and relationships on resources.
`session` and `model` are as described in the constructor of the
superclass.
`preprocessors` and `postprocessors` are as described in :ref:`processors`.
`primary_key` is as described in :ref:`primarykey`.
`serializer` and `deserializer` are as described in
:ref:`serialization`.
`validation_exceptions` are as described in :ref:`validation`.
`includes` are as described in :ref:`includes`.
`page_size` and `max_page_size` are as described in
:ref:`pagination`.
`allow_to_many_replacement` is as described in
:ref:`allowreplacement`.
"""
#: List of decorators applied to every method of this class.
decorators = [catch_processing_exceptions] + ModelView.decorators
def __init__(self, session, model, preprocessors=None, postprocessors=None,
primary_key=None, serializer=None, deserializer=None,
validation_exceptions=None, includes=None, page_size=10,
max_page_size=100, allow_to_many_replacement=False, *args,
**kw):
super(APIBase, self).__init__(session, model, *args, **kw)
#: The name of the collection specified by the given model class
#: to be used in the URL for the ReSTful API created.
self.collection_name = collection_name(self.model)
#: The default set of related resources to include in compound
#: documents, given as a set of relationship paths.
self.default_includes = includes
if self.default_includes is not None:
self.default_includes = frozenset(self.default_includes)
#: Whether to allow complete replacement of a to-many relationship when
#: updating a resource.
self.allow_to_many_replacement = allow_to_many_replacement
#: The default page size for responses that consist of a
#: collection of resources.
#:
#: Requests made by clients may override this default by
#: specifying ``page_size`` as a query parameter.
self.page_size = page_size
#: The maximum page size that a client can request.
#:
#: Even if a client specifies that greater than `max_page_size`
#: should be returned, at most `max_page_size` results will be
#: returned.
self.max_page_size = max_page_size
#: A custom serialization function for primary resources; see
#: :ref:`serialization` for more information.
#:
#: This should not be ``None``, unless a subclass is not going to use
#: serialization.
self.serializer = serializer
#: A custom deserialization function for primary resources; see
#: :ref:`serialization` for more information.
#:
#: This should not be ``None``, unless a subclass is not going to use
#: deserialization.
self.deserializer = deserializer
#: The tuple of exceptions that are expected to be raised during
#: validation when creating or updating a model.
self.validation_exceptions = tuple(validation_exceptions or ())
#: The name of the attribute containing the primary key to use as the
#: ID of the resource.
self.primary_key = primary_key
#: The mapping from method name to a list of functions to apply after
#: the main functionality of that method has been executed.
self.postprocessors = defaultdict(list, upper(postprocessors or {}))
#: The mapping from method name to a list of functions to apply before
#: the main functionality of that method has been executed.
self.preprocessors = defaultdict(list, upper(preprocessors or {}))
#: The mapping from resource type name to requested sparse
#: fields for resources of that type.
self.sparse_fields = parse_sparse_fields()
# HACK: We would like to use the :attr:`API.decorators` class attribute
# in order to decorate each view method with a decorator that catches
# database integrity errors. However, in order to rollback the session,
# we need to have a session object available to roll back. Therefore we
# need to manually decorate each of the view functions here.
for method in ['get', 'post', 'patch', 'delete']:
# Check if the subclass has the method before trying to decorate
# it.
if hasattr(self, method):
wrapper = catch_integrity_errors(self.session)
old_method = getattr(self, method)
setattr(self, method, wrapper(old_method))
def collection_processor_type(self, *args, **kw):
"""The suffix for the pre- and postprocessor identifiers for
requests on collections of resources.
This is an abstract method; subclasses must override this
method.
"""
raise NotImplementedError
def resource_processor_type(self, *args, **kw):
"""The suffix for the pre- and postprocessor identifiers for
requests on resource objects.
This is an abstract method; subclasses must override this
method.
"""
raise NotImplementedError
def use_resource_identifiers(self):
"""Whether primary data in responses use resource identifiers or
full resource objects.
Subclasses that handle resource linkage should override this
method so that it returns ``True``.
"""
return False
def _handle_validation_exception(self, exception):
"""Rolls back the session, extracts validation error messages, and
returns an error response with :http:statuscode:`400` containing the
extracted validation error messages.
Again, *this method calls
:meth:`sqlalchemy.orm.session.Session.rollback`*.
"""
self.session.rollback()
errors = extract_error_messages(exception)
if not errors:
title = 'Validation error'
return error_response(400, cause=exception, title=title)
if isinstance(errors, dict):
errors = [error(title='Validation error', status=400,
detail='{0}: {1}'.format(field, detail))
for field, detail in errors.items()]
current_app.logger.exception(str(exception))
return errors_response(400, errors)
def get_all_inclusions(self, instance_or_instances):
"""Returns a list of all the requested included resources
associated with the given instance or instances of a SQLAlchemy
model.
``instance_or_instances`` is either a SQLAlchemy
:class:`~sqlalchemy.orm.query.Query` object representing
multiple instances of a SQLAlchemy model, or it is simply one
instance of a model. These instances represent the resources
that will be returned as primary data in the JSON API
response. The resources to include will be computed based on
these data and the client's ``include`` query parameter.
This function raises :exc:`MultipleExceptions` if any included
resource causes a serialization exception. If this exception is
raised, the :attr:`MultipleExceptions.exceptions` attribute
contains a list of the :exc:`SerializationException` objects
that caused it.
"""
# If `instance_or_instances` is actually just a single instance
# of a SQLAlchemy model, get the resources to include for that
# one instance. Otherwise, collect the resources to include for
# each instance in `instances`.
if isinstance(instance_or_instances, Query):
instances = instance_or_instances
to_include = set(chain(map(self.resources_to_include, instances)))
else:
instance = instance_or_instances
to_include = self.resources_to_include(instance)
only = self.sparse_fields
# HACK We only need the primary data from the JSON API document,
# not the metadata (so really the serializer is doing more work
# than it needs to here).
result = simple_serialize_many(to_include, only=only)
return result['data']
def _paginated(self, items, filters=None, sort=None, group_by=None):
"""Returns a :class:`Paginated` object representing the
correctly paginated list of resources to return to the client,
based on the current request.
`items` is a SQLAlchemy query, or a Flask-SQLAlchemy query,
containing all requested elements of a collection regardless of
the page number or size in the client's request.
`filters`, `sort`, and `group_by` must have already been
extracted from the client's request (as by
:meth:`collection_parameters`) and applied to the query.
If `relationship` is ``True``, the resources in the query object
will be serialized as linkage objects instead of resources
objects.
# This method serializes the (correct page of) resources. As such,
# it raises an instance of :exc:`MultipleExceptions` if there is a
# problem serializing resources.
"""
# Determine the client's page size request. Raise an exception
# if the page size is out of bounds, either too small or too
# large.
page_size = int(request.args.get(PAGE_SIZE_PARAM, self.page_size))
if page_size < 0:
raise PaginationError('Page size must be a positive integer')
if page_size > self.max_page_size:
msg = "Page size must not exceed the server's maximum: {0}"
msg = msg.format(self.max_page_size)
raise PaginationError(msg)
# If the page size is 0, just return everything.
if page_size == 0:
# # These serialization calls may raise MultipleExceptions, or
# # possible SerializationExceptions.
# if is_relationship:
# result = self.relationship_serializer.serialize_many(items)
# else:
# serialize_many = self.serializer.serialize_many
# result = serialize_many(items, only=self.sparse_fields)
# TODO Ideally we would like to use the folowing code.
#
# # Use `len()` here instead of doing `count(self.session,
# # items)` because the former should be faster.
# num_results = len(result['data'])
#
# but we can't get the length of the list of items until
# we serialize them.
num_results = count(self.session, items)
return Paginated(items, page_size=0, num_results=num_results)
# Determine the client's page number request. Raise an exception
# if the page number is out of bounds.
page_number = int(request.args.get(PAGE_NUMBER_PARAM, 1))
if page_number < 0:
raise PaginationError('Page number must be a positive integer')
# At this point, we know the page size is positive, so we
# paginate the response.
#
# If the query is really a Flask-SQLAlchemy query, we can use
# its built-in pagination. Otherwise, we need to manually
# compute the page numbers, the number of results, etc.
if hasattr(items, 'paginate'):
pagination = items.paginate(page_number, page_size,
error_out=False)
num_results = pagination.total
first = 1
last = pagination.pages
prev = pagination.prev_num
next_ = pagination.next_num
items = pagination.items
else:
num_results = count(self.session, items)
first = 1
# Handle a special case for an empty collection of items.
#
# There will be no division-by-zero error here because we
# have already checked that page size is not equal to zero
# above.
if num_results == 0:
last = 1
else:
last = int(math.ceil(num_results / page_size))
prev = page_number - 1 if page_number > 1 else None
next_ = page_number + 1 if page_number < last else None
offset = (page_number - 1) * page_size
# TODO Use Query.slice() instead, since it's easier to use.
items = items.limit(page_size).offset(offset)
# Wrap the list of results in a Paginated object, which
# represents the result set and stores some extra information
# about how it was determined.
return Paginated(items, num_results=num_results, first=first,
last=last, next_=next_, prev=prev,
page_size=page_size, filters=filters, sort=sort,
group_by=group_by)
def _get_resource_helper(self, resource, primary_resource=None,
relation_name=None, related_resource=False):
is_relationship = self.use_resource_identifiers()
# The resource to serialize may be `None`, if we are fetching a
# to-one relation that has no value. In this case, the "data"
# for the JSON API response is just `None`.
if resource is None:
result = JsonApiDocument()
# Otherwise, we are serializing one of several possibilities.
#
# - a primary resource (as in `GET /person/1`),
# - a to-one relation (as in `GET /article/1/author`)
# - a related resource (as in `GET /person/1/articles/2`).
# - a to-one relationship (as in `GET /article/1/relationships/author`)
#
else:
try:
# This covers the relationship object case...
if is_relationship:
result = simple_relationship_serialize(resource)
# ...and this covers the resource object cases.
else:
model = get_model(resource)
# Determine the serializer for this instance. If there
# is no serializer, use the default serializer for the
# current resource, even though the current model may
# different from the model of the current instance.
try:
serializer = serializer_for(model)
except ValueError:
# TODO Should we fail instead, thereby effectively
# requiring that an API has been created for each
# type of resource? This is mainly a design
# question.
serializer = self.serializer
# This may raise ValueError
_type = collection_name(model)
only = self.sparse_fields.get(_type)
# This may raise SerializationException
result = serializer.serialize(resource, only=only)
except SerializationException as exception:
return errors_from_serialization_exceptions([exception])
# Determine the top-level links.
linker = Linker(self.model)
links = linker.generate_links(resource, primary_resource,
relation_name, related_resource,
is_relationship)
result['links'] = links
# TODO Create an Includer class, like the Linker class.
# # Determine the top-level inclusions.
# includer = Includer(resource)
# includes = includer.generate_includes(resource)
# result['includes'] = includes
# Include any requested resources in a compound document.
try:
included = self.get_all_inclusions(resource)
except MultipleExceptions as e:
# By the way we defined `get_all_inclusions()`, we are
# guaranteed that each of the underlying exceptions is a
# `SerializationException`. Thus we can use
# `errors_from_serialization_exception()`.
return errors_from_serialization_exceptions(e.exceptions,
included=True)
if included:
result['included'] = included
# HACK Need to do this here to avoid a too-long line.
is_relation = primary_resource is not None
is_related_resource = is_relation and related_resource
kw = {'is_relation': is_relation,
'is_related_resource': is_related_resource}
# This method could have been called on a request to fetch a
# single resource, a to-one relation, or a member of a to-many
# relation. We need to use the appropriate postprocessor here.
processor_type = 'GET_{0}'.format(self.resource_processor_type(**kw))
for postprocessor in self.postprocessors[processor_type]:
postprocessor(result=result)
return jsonpify(result), 200
def _get_collection_helper(self, resource=None, relation_name=None,
filters=None, sort=None, group_by=None,
ignorecase=False, single=False):
if (resource is None) ^ (relation_name is None):
raise ValueError('resource and relation must be both None or both'
' not None')
# Compute the result of the search on the model.
is_relation = resource is not None
if is_relation:
search_ = partial(search_relationship, self.session, resource,
relation_name)
else:
search_ = partial(search, self.session, self.model)
try:
search_items = search_(filters=filters, sort=sort,
group_by=group_by, ignorecase=ignorecase)
except (FilterParsingError, FilterCreationError) as exception:
detail = 'invalid filter object: {0}'.format(str(exception))
return error_response(400, cause=exception, detail=detail)
except Exception as exception:
detail = 'Unable to construct query'
return error_response(400, cause=exception, detail=detail)
is_relationship = self.use_resource_identifiers()
# Add the primary data (and any necessary links) to the JSON API
# response object.
#
# If the result of the search is a SQLAlchemy query object, we need to
# return a collection.
if not single:
try:
paginated = self._paginated(search_items, filters=filters,
sort=sort, group_by=group_by)
except PaginationError as exception:
detail = exception.args[0]
return error_response(400, cause=exception, detail=detail)
# Serialize the found items.
#
# We are serializing one of three possibilities.
#
# - a collection of primary resources (as in `GET /person`),
# - a to-many relation (as in `GET /person/1/articles`),
# - a to-many relationship (as in
# `GET /person/1/relationships/articles`)
#
items = paginated.items
# This covers the relationship object case...
if is_relationship:
result = simple_relationship_serialize_many(items)
# ...and this covers the primary resource collection and
# to-many relation cases.
else:
only = self.sparse_fields
try:
result = self.serializer.serialize_many(items, only=only)
except MultipleExceptions as e:
return errors_from_serialization_exceptions(e.exceptions)
except SerializationException as exception:
return errors_from_serialization_exceptions([exception])
# Determine the top-level links.
linker = Linker(self.model)
links = linker.generate_links(resource, None, relation_name, None,
is_relationship)
pagination_linker = PaginationLinker(paginated)
pagination_links = pagination_linker.generate_links()
if 'links' not in result:
result['links'] = {}
result['links'].update(links)
result['links'].update(pagination_links)
# Create the metadata for the response, like headers and
# total number of found items.
pagination_header_links = pagination_linker.generate_header_links()
link_header = ','.join(pagination_header_links)
headers = dict(Link=link_header)
num_results = paginated.num_results
# Otherwise, the result of the search should be a single resource.
else:
try:
resource = search_items.one()
except NoResultFound as exception:
detail = 'No result found'
return error_response(404, cause=exception, detail=detail)
except MultipleResultsFound as exception:
detail = 'Multiple results found'
return error_response(404, cause=exception, detail=detail)
# Serialize the single resource.
try:
if is_relationship:
result = simple_relationship_serialize(resource)
else:
only = self.sparse_fields.get(self.collection_name)
result = self.serializer.serialize(resource, only=only)
except SerializationException as exception:
return errors_from_serialization_exceptions([exception])
# Determine the top-level links.
linker = Linker(self.model)
# Here we determine whether we are looking at a collection,
# as in `GET /people`, or a to-many relation, as in `GET
# /people/1/comments`.
if resource is None:
links = linker.generate_links(None, None, None, None, False,
False)
else:
links = linker.generate_links(resource, None, None, False,
False)
result['links'].update(links)
# Create the metadata for the response, like headers and
# total number of found items.
primary_key = primary_key_for(resource)
pk_value = result['data'][primary_key]
location = url_for(self.model, resource_id=pk_value)
headers = dict(Location=location)
num_results = 1
# Determine the resources to include (in a compound document).
if self.use_resource_identifiers():
instances = resource
else:
instances = search_items
# Include any requested resources in a compound document.
try:
included = self.get_all_inclusions(instances)
except MultipleExceptions as e:
# By the way we defined `get_all_inclusions()`, we are
# guaranteed that each of the underlying exceptions is a
# `SerializationException`. Thus we can use
# `errors_from_serialization_exception()`.
return errors_from_serialization_exceptions(e.exceptions,
included=True)
result.setdefault('included', []).extend(included)
# This method could have been called on either a request to
# fetch a collection of resources or a to-many relation.
processor_type = \
self.collection_processor_type(is_relation=is_relation)
processor_type = 'GET_{0}'.format(processor_type)
for postprocessor in self.postprocessors[processor_type]:
postprocessor(result=result, filters=filters, sort=sort,
group_by=group_by, single=single)
# Add the metadata to the JSON API response object.
status = 200
meta = {'total': num_results}
result.setdefault('meta', {}).update(meta)
return jsonpify(result), status, headers
def resources_to_include(self, instance):
"""Returns a set of resources to include in a compound document
response based on the ``include`` query parameter and the default
includes specified in the constructor of this class.
The ``include`` query parameter is as described in the `Inclusion of
Related Resources`_ section of the JSON API specification. It specifies
which resources, other than the primary resource or resources, will be
included in a compound document response.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
# Add any links requested to be included by URL parameters.
#
# We expect `toinclude` to be a comma-separated list of relationship
# paths.
toinclude = request.args.get('include')
if toinclude is None and self.default_includes is None:
return {}
elif toinclude is None and self.default_includes is not None:
toinclude = self.default_includes
else:
toinclude = set(toinclude.split(','))
return set(chain(resources_from_path(instance, path)
for path in toinclude))
| 73,760
|
Python
|
.py
| 1,499
| 39.649099
| 79
| 0.635125
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,629
|
relationships.py
|
jfinkels_flask-restless/flask_restless/views/relationships.py
|
# relationships.py - views for requests on SQLAlchemy relationships
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Views for fetching, creating, updating, and deleting relationships.
The main class in this module, :class:`RelationshipAPI`, is a
:class:`~flask.MethodView` subclass that handles requests for updating
relationships according to the JSON API specification.
"""
from flask import json
from flask import request
from werkzeug.exceptions import BadRequest
from ..helpers import collection_name
from ..helpers import get_by
from ..helpers import get_related_model
from ..helpers import is_like_list
from .base import APIBase
from .base import error
from .base import error_response
from .base import errors_response
from .base import jsonpify
from .base import SingleKeyError
class RelationshipAPI(APIBase):
"""Provides fetching, updating, and deleting from relationship URLs.
The endpoints provided by this class are of the form
``/people/1/relationships/articles``, and the requests and responses
include **link objects**, as opposed to **resource objects**.
`session` and `model` are as described in the constructor of the
superclass. In addition to those described below, this constructor
also accepts all the keyword arguments of the constructor of the
superclass.
`allow_delete_from_to_many_relationships` is as described in
:meth:`APIManager.create_api`.
"""
def __init__(self, session, model,
allow_delete_from_to_many_relationships=False, *args, **kw):
super(RelationshipAPI, self).__init__(session, model, *args, **kw)
self.allow_delete_from_to_many_relationships = \
allow_delete_from_to_many_relationships
def collection_processor_type(self, *args, **kw):
return 'TO_MANY_RELATIONSHIP'
def resource_processor_type(self, *args, **kw):
return 'TO_ONE_RELATIONSHIP'
def use_resource_identifiers(self):
return True
def get(self, resource_id, relation_name):
"""Fetches a to-one or to-many relationship from a resource.
If the specified relationship is a to-one relationship, this method
returns a link object. If it is a to-many relationship, it returns a
collection of link objects.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
for preprocessor in self.preprocessors['GET_RELATIONSHIP']:
temp_result = preprocessor(resource_id=resource_id,
relation_name=relation_name)
# Let the return value of the preprocessor be the new value of
# instid, thereby allowing the preprocessor to effectively specify
# which instance of the model to process on.
#
# We assume that if the preprocessor returns None, it really just
# didn't return anything, which means we shouldn't overwrite the
# instid.
if temp_result is not None:
resource_id = temp_result
# get the instance of the "main" model whose ID is `resource_id`
primary_resource = get_by(self.session, self.model, resource_id,
self.primary_key)
if primary_resource is None:
detail = 'No resource with ID {0}'.format(resource_id)
return error_response(404, detail=detail)
if is_like_list(primary_resource, relation_name):
try:
filters, sort, group_by, single, ignorecase = \
self.collection_parameters(resource_id=resource_id,
relation_name=relation_name)
except (TypeError, ValueError, OverflowError) as exception:
detail = 'Unable to decode filter objects as JSON list'
return error_response(400, cause=exception, detail=detail)
except SingleKeyError as exception:
detail = 'Invalid format for filter[single] query parameter'
return error_response(400, cause=exception, detail=detail)
return self._get_collection_helper(resource=primary_resource,
relation_name=relation_name,
filters=filters, sort=sort,
group_by=group_by,
single=single)
resource = getattr(primary_resource, relation_name)
return self._get_resource_helper(resource,
primary_resource=primary_resource,
relation_name=relation_name)
def post(self, resource_id, relation_name):
"""Adds resources to a to-many relationship.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
# try to load the fields/values to update from the body of the request
try:
data = json.loads(request.get_data()) or {}
except (BadRequest, TypeError, ValueError, OverflowError) as exception:
# this also happens when request.data is empty
detail = 'Unable to decode data'
return error_response(400, cause=exception, detail=detail)
for preprocessor in self.preprocessors['POST_RELATIONSHIP']:
temp_result = preprocessor(resource_id=resource_id,
relation_name=relation_name, data=data)
# See the note under the preprocessor in the get() method.
if temp_result is not None:
resource_id, relation_name = temp_result
instance = get_by(self.session, self.model, resource_id,
self.primary_key)
# If no instance of the model exists with the specified instance ID,
# return a 404 response.
if instance is None:
detail = 'No instance with ID {0} in model {1}'
detail = detail.format(resource_id, self.model)
return error_response(404, detail=detail)
# If no such relation exists, return a 404.
if not hasattr(instance, relation_name):
detail = 'Model {0} has no relation named {1}'
detail = detail.format(self.model, relation_name)
return error_response(404, detail=detail)
related_model = get_related_model(self.model, relation_name)
related_value = getattr(instance, relation_name)
# Unwrap the data from the request.
data = data.pop('data', {})
for rel in data:
if 'type' not in rel:
detail = 'Must specify correct data type'
return error_response(400, detail=detail)
if 'id' not in rel:
detail = 'Must specify resource ID'
return error_response(400, detail=detail)
type_ = rel['type']
# The type name must match the collection name of model of the
# relation.
if type_ != collection_name(related_model):
detail = ('Type must be {0}, not'
' {1}').format(collection_name(related_model), type_)
return error_response(409, detail=detail)
# Get the new objects to add to the relation.
new_value = get_by(self.session, related_model, rel['id'])
if new_value is None:
detail = ('No resource of type {0} found with ID'
' {1}').format(type_, rel['id'])
return error_response(404, detail=detail)
# Don't append a new value if it already exists in the to-many
# relationship.
if new_value not in related_value:
try:
related_value.append(new_value)
except self.validation_exceptions as exception:
return self._handle_validation_exception(exception)
# Flush all changes to database but do not commit the transaction
# so that postprocessors have the chance to roll it back
self.session.flush()
# Perform any necessary postprocessing.
for postprocessor in self.postprocessors['POST_RELATIONSHIP']:
postprocessor()
self.session.commit()
return jsonpify({}), 204
def patch(self, resource_id, relation_name):
"""Updates to a to-one or to-many relationship.
If the relationship is a to-many relationship and this class was
instantiated with the ``allow_to_many_replacement`` keyword argument
set to ``False``, then this method returns a :http:status:`403`
response.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
# try to load the fields/values to update from the body of the request
try:
data = json.loads(request.get_data()) or {}
except (BadRequest, TypeError, ValueError, OverflowError) as exception:
# this also happens when request.data is empty
detail = 'Unable to decode data'
return error_response(400, cause=exception, detail=detail)
for preprocessor in self.preprocessors['PATCH_RELATIONSHIP']:
temp_result = preprocessor(instance_id=resource_id,
relation_name=relation_name, data=data)
# See the note under the preprocessor in the get() method.
if temp_result is not None:
resource_id, relation_name = temp_result
instance = get_by(self.session, self.model, resource_id,
self.primary_key)
# If no instance of the model exists with the specified instance ID,
# return a 404 response.
if instance is None:
detail = 'No instance with ID {0} in model {1}'
detail = detail.format(resource_id, self.model)
return error_response(404, detail=detail)
# If no such relation exists, return a 404.
if not hasattr(instance, relation_name):
detail = 'Model {0} has no relation named {1}'
detail = detail.format(self.model, relation_name)
return error_response(404, detail=detail)
related_model = get_related_model(self.model, relation_name)
# related_value = getattr(instance, relation_name)
# Unwrap the data from the request.
data = data.pop('data', {})
# If the client sent a null value, we assume it wants to remove a
# to-one relationship.
if data is None:
if is_like_list(instance, relation_name):
detail = 'Cannot set null value on a to-many relationship'
return error_response(400, detail=detail)
setattr(instance, relation_name, None)
else:
# If this is a list, we assume the client is trying to set a
# to-many relationship.
if isinstance(data, list):
# Replacement of a to-many relationship may have been disabled
# on the server-side by the user.
if not self.allow_to_many_replacement:
detail = 'Not allowed to replace a to-many relationship'
return error_response(403, detail=detail)
replacement = []
for rel in data:
if 'type' not in rel:
detail = 'Must specify correct data type'
return error_response(400, detail=detail)
if 'id' not in rel:
detail = 'Must specify resource ID or IDs'
return error_response(400, detail=detail)
type_ = rel['type']
# The type name must match the collection name of model of
# the relation.
if type_ != collection_name(related_model):
detail = 'Type must be {0}, not {1}'
detail = detail.format(collection_name(related_model),
type_)
return error_response(409, detail=detail)
id_ = rel['id']
obj = get_by(self.session, related_model, id_)
replacement.append(obj)
# Otherwise, we assume the client is trying to set a to-one
# relationship.
else:
if 'type' not in data:
detail = 'Must specify correct data type'
return error_response(400, detail=detail)
if 'id' not in data:
detail = 'Must specify resource ID or IDs'
return error_response(400, detail=detail)
type_ = data['type']
# The type name must match the collection name of model of the
# relation.
if type_ != collection_name(related_model):
detail = ('Type must be {0}, not'
' {1}').format(collection_name(related_model),
type_)
return error_response(409, detail=detail)
id_ = data['id']
replacement = get_by(self.session, related_model, id_)
# If the to-one relationship resource or any of the to-many
# relationship resources do not exist, return an error response.
if replacement is None:
detail = ('No resource of type {0} found'
' with ID {1}').format(type_, id_)
return error_response(404, detail=detail)
if isinstance(replacement, list) \
and any(value is None for value in replacement):
not_found = (rel for rel, value in zip(data, replacement)
if value is None)
detail = 'No resource of type {0} found with ID {1}'
errors = [error(detail=detail.format(rel['type'], rel['id']))
for rel in not_found]
return errors_response(404, errors)
# Finally, set the relationship to have the new value.
try:
setattr(instance, relation_name, replacement)
except self.validation_exceptions as exception:
return self._handle_validation_exception(exception)
# Flush all changes to database but do not commit the transaction
# so that postprocessors have the chance to roll it back
self.session.flush()
# Perform any necessary postprocessing.
for postprocessor in self.postprocessors['PATCH_RELATIONSHIP']:
postprocessor()
self.session.commit()
return jsonpify({}), 204
def delete(self, resource_id, relation_name):
"""Deletes resources from a to-many relationship.
If this class was instantiated with the
``allow_delete_from_to_many_relationships`` keyword argument set to
``False``, then this method returns a :http:status:`403` response.
The request documents, response documents, and status codes are in the
format specified by the JSON API specification.
"""
if not self.allow_delete_from_to_many_relationships:
detail = 'Not allowed to delete from a to-many relationship'
return error_response(403, detail=detail)
# try to load the fields/values to update from the body of the request
try:
data = json.loads(request.get_data()) or {}
except (BadRequest, TypeError, ValueError, OverflowError) as exception:
# this also happens when request.data is empty
detail = 'Unable to decode data'
return error_response(400, cause=exception, detail=detail)
was_deleted = False
for preprocessor in self.preprocessors['DELETE_RELATIONSHIP']:
temp_result = preprocessor(instance_id=resource_id,
relation_name=relation_name)
# See the note under the preprocessor in the get() method.
if temp_result is not None:
resource_id = temp_result
instance = get_by(self.session, self.model, resource_id,
self.primary_key)
# If no such relation exists, return an error to the client.
if not hasattr(instance, relation_name):
detail = 'No such link: {0}'.format(relation_name)
return error_response(404, detail=detail)
# We assume that the relation is a to-many relation.
related_model = get_related_model(self.model, relation_name)
related_type = collection_name(related_model)
relation = getattr(instance, relation_name)
data = data.pop('data')
not_found = []
to_remove = []
for rel in data:
if 'type' not in rel:
detail = 'Must specify correct data type'
return error_response(400, detail=detail)
if 'id' not in rel:
detail = 'Must specify resource ID'
return error_response(400, detail=detail)
type_ = rel['type']
id_ = rel['id']
if type_ != related_type:
detail = ('Conflicting type: expected {0} but got type {1} for'
' linkage object with ID {2}')
detail = detail.format(related_type, type_, id_)
return error_response(409, detail=detail)
resource = get_by(self.session, related_model, id_)
if resource is None:
not_found.append((type_, id_))
else:
to_remove.append(resource)
if not_found:
detail = 'No resource of type {0} and ID {1} found'
errors = [error(detail=detail.format(t, i)) for t, i in not_found]
return errors_response(404, errors)
# Remove each of the resources from the relation (if they are not
# already absent).
for resource in to_remove:
try:
relation.remove(resource)
except ValueError:
# The JSON API specification requires that we silently
# ignore requests to delete resources that are already
# missing from a to-many relation.
pass
was_deleted = len(self.session.dirty) > 0
# Flush all changes to database but do not commit the transaction
# so that postprocessors have the chance to roll it back
self.session.flush()
for postprocessor in self.postprocessors['DELETE_RELATIONSHIP']:
postprocessor(was_deleted=was_deleted)
self.session.commit()
if not was_deleted:
detail = 'There was no instance to delete'
return error_response(404, detail=detail)
return jsonpify({}), 204
| 19,601
|
Python
|
.py
| 370
| 39.664865
| 79
| 0.599104
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,630
|
helpers.py
|
jfinkels_flask-restless/flask_restless/views/helpers.py
|
# helpers.py - helper functions for view classes
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Helper functions for view classes."""
from sqlalchemy.inspection import inspect as sqlalchemy_inspect
from sqlalchemy.sql import func
def upper_keys(dictionary):
"""Returns a new dictionary with the keys of ``dictionary``
converted to upper case and the values left unchanged.
"""
# In Python 3, this should be
#
# return {k.upper(): v for k, v in dictionary.items()}
#
return dict((k.upper(), v) for k, v in dictionary.items())
def count(session, query):
"""Returns the count of the specified `query`.
This function employs an optimization that bypasses the
:meth:`sqlalchemy.orm.Query.count` method, which can be very slow
for large queries.
"""
counts = query.selectable.with_only_columns([func.count()])
num_results = session.execute(counts.order_by(None)).scalar()
if num_results is None or query._limit is not None:
return query.order_by(None).count()
return num_results
def changes_on_update(model):
"""Returns a best guess at whether the specified SQLAlchemy model class is
modified on updates.
We guess whether this happens by checking whether any columns of model have
the :attr:`sqlalchemy.Column.onupdate` attribute set.
"""
return any(column.onupdate is not None
for column in sqlalchemy_inspect(model).columns)
| 1,817
|
Python
|
.py
| 42
| 39.261905
| 79
| 0.727324
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,631
|
filters.py
|
jfinkels_flask-restless/flask_restless/search/filters.py
|
# filters.py - parsing and creation of SQLAlchemy filter expressions
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Functions for parsing and creating SQLAlchemy filter expressions.
The :func:`create_filters` function allows you to create SQLAlchemy
expressions that can be used by the :meth:`sqlalchemy.orm.Query.filter`
method. It parses a dictionary representation of a filter as described
in :doc:`filtering` into an executable SQLAlchemy expression.
The :exc:`FilterParsingError` and :exc:`FilterCreationError` exceptions
provide information about problems that arise from parsing filters and
generating the SQLAlchemy expressions, respectively.
"""
from operator import methodcaller
from functools import partial
from sqlalchemy import and_
from sqlalchemy import not_
from sqlalchemy import or_
from ..helpers import get_related_model_from_attribute
from ..helpers import string_to_datetime
from .operators import create_operation
from .operators import NO_ARGUMENT
from .operators import OperatorCreationError
class FilterCreationError(Exception):
"""Raised when there is a problem creating a SQLAlchemy filter object."""
class FilterParsingError(Exception):
"""Raised if there is a problem parsing a filter object from a
dictionary into an instance of the :class:`.Filter` class.
"""
class Filter(object):
"""Represents a filter to apply to a SQLAlchemy query object.
This is an abstract base class. Subclasses must override and
implement the :meth:`.to_expression` method.
The :meth:`.to_expression` method returns the SQLAlchemy operator
expression represented by this filter object.
"""
def to_expression(self):
"""Returns the SQLAlchemy expression represented by this filter.
**This method is not implemented in this base class; subclasses
must override this method.**
"""
raise NotImplementedError
class FieldFilter(Filter):
"""Represents a filter on a field of a model.
`field` is the field (i.e. the actual column or relationship object)
to be placed on the left side of the operator.
`operator` is a string representing the SQLAlchemy operator to apply
to the field named by `fieldname`. This must be one of the
operations named in :mod:`.operators`.
`argument` is the second argument to the operator, which may be a
value (such as a string or an integer) or another field object. This
may also be None in case the operator is unary (such as the "is
null" operator).
"""
def __init__(self, field, operator, argument):
self.field = field
self.operator = operator
self.argument = argument
def __repr__(self):
s = '<FieldFilter {0} {1} {2}>'
s = s.format(self.field, self.operator, self.argument)
return s
def to_expression(self):
"""Returns the SQLAlchemy expression represented by this filter.
For example::
>>> f = FieldFilter(Person.age, '>', 10)
>>> print(f.to_expression())
person.age > :age_1
>>> f = FieldFilter(Person.age, '>', Person.id)
>>> print(f.to_expression())
person.age > person.id
This method raises :exc:`FilterCreationError` if there is a
problem creating the operator expression.
"""
argument = self.argument
# In the case of relationship operators 'has' and 'any', the
# argument is another Filter object entirely, so we need to
# recursively generate the expression for that Filter object as
# well.
if isinstance(self.argument, Filter):
argument = self.argument.to_expression()
try:
return create_operation(self.field, self.operator, argument)
except OperatorCreationError as exception:
raise FilterCreationError(str(exception))
class BooleanFilter(Filter):
"""A Boolean expression comprising other filters.
This is an abstract base class. Subclasses must override and
implement the :meth:`.to_expression` method.
"""
class NegationFilter(BooleanFilter):
"""A negation of another filter.
`subfilter` is the :class:`.Filter` object being negated.
"""
def __init__(self, subfilter):
self.subfilter = subfilter
def __repr__(self):
return 'not_({0})'.format(repr(self.subfilter))
def to_expression(self):
return not_(self.subfilter.to_expression())
class JunctionFilter(Filter):
"""A conjunction or disjunction of other filters.
This is an abstract base class. Subclasses must override and
implement the :meth:`.to_expression` method.
`subfilters` is an iterable of :class:`.Filter` objects.
"""
def __init__(self, subfilters):
self.subfilters = subfilters
class ConjunctionFilter(JunctionFilter):
"""A conjunction of other filters."""
def __repr__(self):
return 'and_{0}'.format(tuple(map(repr, self.subfilters)))
def to_expression(self):
return and_(f.to_expression() for f in self.subfilters)
class DisjunctionFilter(JunctionFilter):
"""A disjunction of other filters."""
def __repr__(self):
return 'or_{0}'.format(tuple(map(repr, self)))
def to_expression(self):
return or_(f.to_expression() for f in self.subfilters)
def from_dictionary(model, dictionary):
"""Returns a new :class:`Filter` object with arguments parsed from
`dictionary`.
`dictionary` is a dictionary of the form::
{'name': 'age', 'op': 'lt', 'val': 20}
or::
{'name': 'age', 'op': 'lt', 'other': 'height'}
where ``dictionary['name']`` is the name of the field of the model on
which to apply the operator, ``dictionary['op']`` is the name of the
operator to apply, ``dictionary['val']`` is the value on the right to
which the operator will be applied, and ``dictionary['other']`` is the
name of the other field of the model to which the operator will be
applied.
'dictionary' may also be an arbitrary Boolean formula consisting of
dictionaries such as these. For example::
{'or':
[{'and':
[dict(name='name', op='like', val='%y%'),
dict(name='age', op='ge', val=10)]},
dict(name='name', op='eq', val='John')
]
}
The returned object is an instance of a subclass of :class:`Filter`,
representing the root of the Boolean formula parsed from the given
dictionary.
This method raises :exc:`FilterParsingError` if one of several
possible errors occurs while parsing the dictionary.
"""
# If there are no ANDs, ORs, and NOTs, we are in the base case
# of the recursion.
d = dictionary
if 'or' not in d and 'and' not in d and 'not' not in d:
# First, get the field on which to operate.
if 'name' not in dictionary:
raise FilterParsingError('missing field name')
fieldname = dictionary.get('name')
if not hasattr(model, fieldname):
message = 'no such field "{0}"'.format(fieldname)
raise FilterParsingError(message)
field = getattr(model, fieldname)
# Next, get the operator to apply to the field.
if 'op' not in dictionary:
raise FilterParsingError('missing operator')
operator = dictionary.get('op')
# Finally, get the second argument to the operator. The argument
# may be another field, a simple value, or another filter.
if 'field' in dictionary:
otherfield = dictionary.get('field')
if not hasattr(model, otherfield):
message = 'no such field "{0}"'.format(otherfield)
raise FilterParsingError(message)
argument = getattr(model, otherfield)
return FieldFilter(field, operator, argument)
else:
# We need to be able to distinguish the case of an argument
# of value ``None`` and the absence of an argument. The
# `NO_ARGUMENT` constant is a sentinel value that signals
# the absence of the `val` key in the dicionary.
argument = dictionary.get('val', NO_ARGUMENT)
# In the special case that the operator is one of the
# relationship operators 'has' or 'any', the argument is
# another filter object entirely, so we need to recursively
# construct a filter from the argument.
if operator in ('has', 'any'):
# Get the remote model of the relationship, since
# `field` is either an InstrumentedAttribute or an
# AssociationProxy.
related_model = get_related_model_from_attribute(field)
argument = from_dictionary(related_model, argument)
return FieldFilter(field, operator, argument)
# HACK: need to deal with the special case of converting dates.
argument = string_to_datetime(model, fieldname, argument)
return FieldFilter(field, operator, argument)
from_dict = partial(from_dictionary, model)
# If there is an OR or an AND in the dictionary, recurse on the
# provided list of filters.
if 'or' in dictionary:
subfilters = map(from_dict, dictionary.get('or'))
return DisjunctionFilter(subfilters)
if 'and' in dictionary:
subfilters = map(from_dict, dictionary.get('and'))
return ConjunctionFilter(subfilters)
# At this point, the only remaining possibility is for 'not'.
subfilter = dictionary.get('not')
return NegationFilter(from_dict(subfilter))
def create_filters(model, filters):
"""Returns an iterator over SQLAlchemy filter expressions.
The objects generated by this function can be provided as the
positional arguments in an invocation of
:meth:`sqlalchemy.orm.Query.filter`.
`model` is the SQLAlchemy model on which the filters will be
applied.
`filters` is an iterable of dictionaries representing filter
objects, as described in the Flask-Restless documentation
(:ref:`filtering`).
This function may raise :exc:`FilterParsingError` if there is a
problem converting a dictionary filter into an intermediate
representation (the :class:`.Filter` object) and
:exc:`FilterCreationError` if there is a problem converting the
intermediate representation into a SQLAlchemy expression.
"""
from_dict = partial(from_dictionary, model)
# `Filter.from_dictionary()` converts the dictionary representation
# of a filter object into an intermediate representation, an
# instance of :class:`.Filter` that facilitates the construction of
# the actual SQLAlchemy code in `create_filter` below.
filters = map(from_dict, filters)
# Each of these function calls may raise a FilterCreationError.
#
# TODO In Python 3.3+, this should be `yield from ...`.
return map(methodcaller('to_expression'), filters)
| 11,426
|
Python
|
.py
| 238
| 40.840336
| 77
| 0.683164
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,632
|
drivers.py
|
jfinkels_flask-restless/flask_restless/search/drivers.py
|
# drivers.py - high-level functions for filtering SQLAlchemy queries
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""High-level functions for creating filtered SQLAlchemy queries.
The :func:`search` and :func:`search_relationship` functions return
filtered queries on a SQLAlchemy model. The latter specifically
restricts the query to only those instances of a model that are related
to a particular object via a given to-many relationship.
"""
from sqlalchemy.orm import aliased
from sqlalchemy.sql import false as FALSE
from ..helpers import get_model
from ..helpers import get_related_model
from ..helpers import primary_key_names
from ..helpers import primary_key_value
from ..helpers import session_query
from .filters import create_filters
def search_relationship(session, instance, relation, filters=None, sort=None,
group_by=None, ignorecase=False):
"""Returns a filtered, sorted, and grouped SQLAlchemy query
restricted to those objects related to a given instance.
`session` is the SQLAlchemy session in which to create the query.
`instance` is an instance of a SQLAlchemy model whose relationship
will be queried.
` `relation` is a string naming a to-many relationship of `instance`.
`filters`, `sort`, `group_by`, and `ignorecase` are identical to the
corresponding arguments of :func:`.search`.
"""
model = get_model(instance)
related_model = get_related_model(model, relation)
query = session_query(session, related_model)
# Filter by only those related values that are related to `instance`.
relationship = getattr(instance, relation)
# TODO In Python 2.7+, this should be a set comprehension.
primary_keys = set(primary_key_value(inst) for inst in relationship)
# If the relationship is empty, we can avoid a potentially expensive
# filtering operation by simply returning an intentionally empty
# query.
if not primary_keys:
return query.filter(FALSE())
query = query.filter(primary_key_value(related_model).in_(primary_keys))
return search(session, related_model, filters=filters, sort=sort,
group_by=group_by, ignorecase=ignorecase,
_initial_query=query)
def search(session, model, filters=None, sort=None, group_by=None,
ignorecase=False, _initial_query=None):
"""Returns a filtered, sorted, and grouped SQLAlchemy query.
`session` is the SQLAlchemy session in which to create the query.
`model` is the SQLAlchemy model on which to create a query.
`filters` is a list of filter objects. Each filter object is a
dictionary representation of the filters to apply to the
query. (This dictionary is provided directly to the
:func:`.filters.create_filters` function.) For more information on
the format of this dictionary, see :doc:`filtering`.
`sort` is a list of pairs of the form ``(direction, fieldname)``,
where ``direction`` is either '+' or '-' and ``fieldname`` is a
string representing an attribute of the model or a dot-separated
relationship path (for example, 'owner.name'). If `ignorecase` is
True, the sorting will be case-insensitive (so 'a' will precede 'B'
instead of the default behavior in which 'B' precedes 'a').
`group_by` is a list of dot-separated relationship paths on which to
group the query results.
If `_initial_query` is provided, the filters, sorting, and grouping
will be appended to this query. Otherwise, an empty query will be
created for the specified model.
When building the query, filters are applied first, then sorting,
then grouping.
"""
query = _initial_query
if query is None:
query = session_query(session, model)
# Filter the query.
#
# This function call may raise an exception.
filters = create_filters(model, filters)
query = query.filter(*filters)
# Order the query. If no order field is specified, order by primary
# key.
# if not _ignore_sort:
if sort:
for (symbol, field_name) in sort:
direction_name = 'asc' if symbol == '+' else 'desc'
if '.' in field_name:
field_name, field_name_in_relation = field_name.split('.')
relation_model = aliased(get_related_model(model, field_name))
field = getattr(relation_model, field_name_in_relation)
if ignorecase:
field = field.collate('NOCASE')
direction = getattr(field, direction_name)
query = query.join(relation_model)
query = query.order_by(direction())
else:
field = getattr(model, field_name)
if ignorecase:
field = field.collate('NOCASE')
direction = getattr(field, direction_name)
query = query.order_by(direction())
else:
pks = primary_key_names(model)
pk_order = (getattr(model, field).asc() for field in pks)
query = query.order_by(*pk_order)
# Group the query.
if group_by:
for field_name in group_by:
if '.' in field_name:
field_name, field_name_in_relation = field_name.split('.')
relation_model = aliased(get_related_model(model, field_name))
field = getattr(relation_model, field_name_in_relation)
query = query.join(relation_model)
query = query.group_by(field)
else:
field = getattr(model, field_name)
query = query.group_by(field)
return query
| 6,012
|
Python
|
.py
| 122
| 41.942623
| 78
| 0.681958
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,633
|
operators.py
|
jfinkels_flask-restless/flask_restless/search/operators.py
|
# operators.py - parsing and creation of SQLAlchemy operators
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Functions for parsing and creating SQLAlchemy operators.
The :func:`create_operation` function allows you to create a single
SQLAlchemy operation that can be used by the
:meth:`sqlalchemy.orm.Query.filter` method. The
:exc:`.OperatorCreationError` exception is raised when there is a problem
creating the expression.
"""
#: Special symbol that represents the absence of a `val` element in a
#: dictionary representing a filter object.
NO_ARGUMENT = object()
class OperatorCreationError(Exception):
"""Raised when there is a problem creating an operator expression."""
def is_null(arg):
# This is intentionally `arg == None` instead of `arg is None`
# because that's how SQLAlchemy expects a comparison to NULL. The
# same comment goes for the `is_not_null` function below.
return arg == None # NOQA
def is_not_null(arg):
return arg != None # NOQA
def equals(arg1, arg2):
return arg1 == arg2
def not_equals(arg1, arg2):
return arg1 != arg2
def greater_than(arg1, arg2):
return arg1 > arg2
def greater_than_equals(arg1, arg2):
return arg1 >= arg2
def less_than(arg1, arg2):
return arg1 < arg2
def less_than_equals(arg1, arg2):
return arg1 <= arg2
def generic_op(arg1, arg2, op):
return arg1.op(op)(arg2)
def inet_is_contained_by(arg1, arg2):
return generic_op(arg1, arg2, '<<')
def inet_is_contained_by_or_equals(arg1, arg2):
return generic_op(arg1, arg2, '<<=')
def inet_contains(arg1, arg2):
return generic_op(arg1, arg2, '>>')
def inet_contains_or_equals(arg1, arg2):
return generic_op(arg1, arg2, '>>=')
def inet_not_equals(arg1, arg2):
return generic_op(arg1, arg2, '<>')
def inet_contains_or_is_contained_by(arg1, arg2):
return generic_op(arg1, arg2, '&&')
def ilike(arg1, arg2):
return arg1.ilike(arg2)
def like(arg1, arg2):
return arg1.like(arg2)
def not_like(arg1, arg2):
return ~arg1.like(arg2)
def in_(arg1, arg2):
return arg1.in_(arg2)
def not_in(arg1, arg2):
return ~arg1.in_(arg2)
def has(arg1, arg2):
return arg1.has(arg2)
def any_(arg1, arg2):
return arg1.any(arg2)
#: Operator functions keyed by name.
#:
#: Each of these functions accepts either one or two arguments. The
#: first argument is the field object on which to apply the operator.
#: The second argument, where it exists, is the second argument to the
#: operator.
#:
#: Some operations have multiple names. For example, the equality
#: operation can be described by the strings '==', 'eq', 'equals', etc.
OPERATORS = {
# Unary operators.
'is_null': is_null,
'is_not_null': is_not_null,
# Binary operators.
'==': equals,
'eq': equals,
'equals': equals,
'equal_to': equals,
'!=': not_equals,
'ne': not_equals,
'neq': not_equals,
'not_equal_to': not_equals,
'does_not_equal': not_equals,
'>': greater_than,
'gt': greater_than,
'<': less_than,
'lt': less_than,
'>=': greater_than_equals,
'ge': greater_than_equals,
'gte': greater_than_equals,
'geq': greater_than_equals,
'<=': less_than_equals,
'le': less_than_equals,
'lte': less_than_equals,
'leq': less_than_equals,
'<<': inet_is_contained_by,
'<<=': inet_is_contained_by_or_equals,
'>>': inet_contains,
'>>=': inet_contains_or_equals,
'<>': inet_not_equals,
'&&': inet_contains_or_is_contained_by,
'ilike': ilike,
'like': like,
'not_like': not_like,
'in': in_,
'not_in': not_in,
# (Binary) relationship operators.
'has': has,
'any': any_,
}
def register_operator(name, op):
"""Register an operator so the system can create expressions involving it.
`name` is a string naming the operator and `op` is a function that
takes up to two arguments as input. If the name provided is one of
the built-in operators (see :ref:`operators`), it will override the
default behavior of that operator. For example, calling ::
register_operator('gt', myfunc)
will cause ``myfunc()`` to be invoked in the SQLAlchemy expression
created for this operator instead of the default "greater than"
operator.
"""
OPERATORS[name] = op
def create_operation(arg1, operator, arg2):
"""Creates a SQLAlchemy expression for the given operation.
More specifically, this translates the string representation of an
operation, for example 'gt', to an expression corresponding to a
SQLAlchemy expression, ``arg1 > arg2``. The recognized operators are
given by the keys of :data:`OPERATORS`. For more information on
recognized search operators, see :doc:`filtering`.
`operator` is a string representating the operation which will be
executed between the field and the argument received. For example,
'gt', 'lt', 'like', 'in', 'has', etc. `operator` must not be
None. If the operator is unknown, an :exc:`OperatorCreationError`
exception is raised.
`arg1` and `arg2` are the arguments to the operator. If the operator
is unary, like the 'is_null' operator, then the second argument is
ignored. Calling code may provide :data:`NO_ARGUMENT` as the second
argument in case no argument was provided by the ultimate end
user. If the operator expects two arguments but `arg2 is
:data:`NO_ARGUMENT`, an :exc:`OperatorCreationError` is
raised. Also, the same exception is raised if the operator expects
two arguments but `arg2` is None, since comparisons to ``NULL``
should use the 'is_null' or 'is_not_null' unary operators instead.
"""
if operator not in OPERATORS:
raise OperatorCreationError('unknown operator "{0}"'.format(operator))
opfunc = OPERATORS[operator]
# If the operator is a comparison to null, the function is unary.
if opfunc in (is_null, is_not_null):
# In this case we expect the argument to be `NO_ARGUMENT`.
# However, we don't explicitly check this, we just ignore
# whatever argument was provided.
return opfunc(arg1)
# Otherwise, the function will accept two arguments.
#
# If None is given as an argument, the user is trying to compare a
# value to NULL, so we politely suggest using the unary `is_null` or
# `is_not_null` operators intead.
#
# It is also possible that no argument was given (as opposed to an
# argument of `None`), as indicated by an argument of value
# `NO_ARGUMENT`. This should happen only when the operator is unary,
# so we raise an exception in that case as well.
if arg2 is None:
message = ('To compare a value to NULL, use the unary'
' is_null/is_not_null operators.')
raise OperatorCreationError(message)
if arg2 is NO_ARGUMENT:
msg = 'expected an argument for this operator but none was given'
raise OperatorCreationError(msg)
return opfunc(arg1, arg2)
| 7,381
|
Python
|
.py
| 181
| 36.370166
| 78
| 0.695993
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,634
|
__init__.py
|
jfinkels_flask-restless/flask_restless/search/__init__.py
|
# __init__.py - indicates that this directory is a Python package
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Provides search queries for SQLAlchemy models.
The :func:`search` function creates a SQLAlchemy query object for a
given set of filters, sorting rules, etc. The
:func:`search_relationship` function creates a query restricted to a
relationship on a particular instance of a SQLAlchemy model.
The :func:`create_filters` function is a finer-grained tool: it allows
you to create the SQLAlchemy expressions without executing them.
The :exc:`FilterParsingError` and :exc:`FilterCreationError` exceptions
are the exceptions that may be raised by the func:`search` and
:func:`create_filters` functions.
"""
from .drivers import create_filters
from .drivers import search
from .drivers import search_relationship
from .filters import FilterCreationError
from .filters import FilterParsingError
from .operators import register_operator
__all__ = [
'create_filters',
'FilterCreationError',
'FilterParsingError',
'register_operator',
'search',
'search_relationship',
]
| 1,467
|
Python
|
.py
| 36
| 38.916667
| 72
| 0.787368
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,635
|
quickstart.py
|
jfinkels_flask-restless/examples/quickstart.py
|
import flask
import flask_sqlalchemy
import flask_restless
# Create the Flask application and the Flask-SQLAlchemy object.
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask_sqlalchemy.SQLAlchemy(app)
# Create your Flask-SQLALchemy models as usual but with the following
# restriction: they must have an __init__ method that accepts keyword
# arguments for all columns (the constructor in
# flask_sqlalchemy.SQLAlchemy.Model supplies such a method, so you
# don't need to declare a new one).
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode)
birth_date = db.Column(db.Date)
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Unicode)
published_at = db.Column(db.DateTime)
author_id = db.Column(db.Integer, db.ForeignKey('person.id'))
author = db.relationship(Person, backref=db.backref('articles',
lazy='dynamic'))
# Create the database tables.
db.create_all()
# Create the Flask-Restless API manager.
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)
# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Article, methods=['GET'])
# start the flask loop
app.run()
| 1,502
|
Python
|
.py
| 34
| 40.294118
| 72
| 0.725652
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,636
|
requests_client.py
|
jfinkels_flask-restless/examples/clients/requests_client.py
|
"""
Using Flask-Restless with the "requests" library
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This provides an example of using Flask-Restless on the server side to
provide a ReSTful API and the Python `requests
<http://docs.python-requests.org/en/latest/>`_ library on the client side
to make HTTP requests to the server.
To install the requests library::
pip install "requests>1.0.3"
(If you have ``requests`` version less then 1.0.3, just change the code
below from ``requests.json()`` to ``requests.json``).
Before executing the code in this module, you must first run the quickstart
server example from this directory (that is, the ``examples/`` directory)::
PYTHONPATH=.. python quickstart.py
Now run this script from this directory to see some example requests using
the ``requests`` library::
python requests_client.py
Remember, the client must specify the ``application/vnd.api+json``
MIME type when sending requests.
:copyright: 2013 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>
:license: GNU AGPLv3+ or BSD
"""
import json
import requests
url = 'http://127.0.0.1:5000/api/person'
headers = {'Accept': 'application/vnd.api+json'}
post_headers = {'Accept': 'application/vnd.api+json',
'Content-Type': 'application/vnd.api+json'}
# Make a POST request to create an object in the database.
person = {
'data': {
'type': 'person',
'attributes': {
'name': 'Jeffrey',
}
}
}
response = requests.post(url, data=json.dumps(person), headers=post_headers)
assert response.status_code == 201
# Make a GET request for the entire collection.
response = requests.get(url, headers=headers)
assert response.status_code == 200
print(response.json())
# Make a GET request for an individual instance of the model.
response = requests.get(url + '/1', headers=headers)
assert response.status_code == 200
print(response.json())
# Use query parameters to make a search. `requests.get` doesn't like
# arbitrary query parameters, so be sure that you pass a dictionary
# whose values are strings to the keyword argument `params`.
filters = [dict(name='name', op='like', val='%y%')]
params = {'filter[objects]': json.dumps(filters)}
response = requests.get(url, params=params, headers=headers)
assert response.status_code == 200
print(response.json())
| 2,416
|
Python
|
.py
| 55
| 39.872727
| 79
| 0.700213
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,637
|
__main__.py
|
jfinkels_flask-restless/examples/clients/jquery/__main__.py
|
"""
Using Flask-Restless with jQuery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This provides a simple example of using Flask-Restless on the server to
create ReSTful API endpoints and [jQuery][0] on the client to make API
requests.
This requires the following Python libraries to be installed:
* Flask
* Flask-Restless
* Flask-SQLAlchemy
To install them using ``pip``, do::
pip install Flask Flask-SQLAlchemy Flask-Restless
To use this example, run this package from the command-line. If you are
using Python 2.7 or later::
python -m jquery
If you are using Python 2.6 or earlier::
python -m jquery.__main__
To view the example in action, direct your web browser to
``http://localhost:5000``. For this example to work, you must have
an Internet connection (in order to access jQuery from a CDN) and
you must enable JavaScript in your web browser (in order to make
requests to the Flask application).
:copyright: 2012 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>
:license: GNU AGPLv3+ or BSD
"""
import os
import os.path
from flask import Flask, render_template
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
# Step 0: the database in this example is at './test.sqlite'.
DATABASE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'test.sqlite')
if os.path.exists(DATABASE):
os.unlink(DATABASE)
# Step 1: setup the Flask application.
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['TESTING'] = True
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % DATABASE
# Step 2: initialize extensions.
db = SQLAlchemy(app)
api_manager = APIManager(app, flask_sqlalchemy_db=db)
# Step 3: create the database model.
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode)
# Step 4: create the database and add some test people.
db.create_all()
for i in range(1, 10):
name = u'person{0}'.format(i)
person = Person(name=name)
db.session.add(person)
db.session.commit()
print(Person.query.all())
# Step 5: create endpoints for the application.
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
# Step 6: create the API endpoints.
api_manager.create_api(Person, methods=['GET', 'POST'])
# Step 7: run the application.
app.run()
| 2,465
|
Python
|
.py
| 64
| 34.6875
| 75
| 0.707071
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,638
|
separate_endpoints.py
|
jfinkels_flask-restless/examples/server_configurations/separate_endpoints.py
|
"""
Separate URLs example
~~~~~~~~~~~~~~~~~~~~~
This provides an example of creating separate API endpoints for different
HTTP methods.
You can read from the database by making a
:http:get:`http://localhost:5000/get/person` request, add a new person
using :http:get:`http://localhost:5000/add/person`, etc.
:copyright: 2012 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>
:license: GNU AGPLv3+ or BSD
"""
import flask
import flask_sqlalchemy
import flask_restless
# Create the Flask application and the Flask-SQLAlchemy object.
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask_sqlalchemy.SQLAlchemy(app)
# Create your Flask-SQLALchemy models as usual but with the following two
# (reasonable) restrictions:
# 1. They must have a primary key column of type sqlalchemy.Integer or
# type sqlalchemy.Unicode.
# 2. They must have an __init__ method which accepts keyword arguments for
# all columns (the constructor in flask_sqlalchemy.SQLAlchemy.Model
# supplies such a method, so you don't need to declare a new one).
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
birth_date = db.Column(db.Date)
class Computer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
vendor = db.Column(db.Unicode)
purchase_time = db.Column(db.DateTime)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
owner = db.relationship('Person', backref=db.backref('computers',
lazy='dynamic'))
# Create the database tables.
db.create_all()
# Create the Flask-Restless API manager.
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)
# Create API endpoints, each at a different URL and with different allowed HTTP
# methods, but which all affect the Person model.
manager.create_api(Person, methods=['GET'], url_prefix='/get')
manager.create_api(Person, methods=['POST'], url_prefix='/add')
manager.create_api(Person, methods=['PATCH'], url_prefix='/update')
manager.create_api(Person, methods=['DELETE'], url_prefix='/remove')
# start the flask loop
app.run()
| 2,312
|
Python
|
.py
| 50
| 42.38
| 79
| 0.715302
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,639
|
custom_serialization.py
|
jfinkels_flask-restless/examples/server_configurations/custom_serialization.py
|
# custom_serialization.py - using Marshmallow serialization with Flask-Restless
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Using Marshmallow for serialization in Flask-Restless.
This script is an example of using `Marshmallow`_ to provide custom
serialization (and the corresponding deserialization) from SQLAlchemy
models to Python dictionaries that will eventually become JSON API
responses to the client. Specifically, this example uses the
`marshmallow-jsonapi`_ library to create serialization/deserialization
functions for use with Flask-Restless.
There are some problems with this approach. You will need to specify
some configuration twice, once for marshmallow-jsonapi and once for
Flask-Restless. For example, you must provide a custom "collection name"
as both the class-level attribute :attr:`Meta.type_` and as the
*collection_name* keyword argument to :meth:`APIManager.create_api`. For
another example, you must specify the URLs for relationships and related
resources directly in the schema definition, and thus these must match
EXACTLY the URLs created by Flask-Restless. The URLs created by
Flask-Restless are fairly predictable, so this requirement, although not
ideal, should not be too challenging.
(This example might have used the `marshmallow-sqlalchemy`_ model to
mitigate some of these issues, but there does not seem to be an easy way
to combine these two Marshmallow layers together.)
To install the necessary requirements for this example, run::
pip install flask-restless flask-sqlalchemy marshmallow-jsonapi
To run this script from the current directory::
python -m custom_serialization
This will run a Flask server at ``http://localhost:5000``. You can then
make requests using any web client.
.. _Marshmallow: https://marshmallow.readthedocs.org
.. _marshmallow-sqlalchemy: https://marshmallow-sqlalchemy.readthedocs.org
.. _marshmallow-jsonapi: https://marshmallow-jsonapi.readthedocs.org
"""
from flask import Flask
from flask_restless import APIManager
from flask_restless import DefaultSerializer
from flask_restless import DefaultDeserializer
from flask_sqlalchemy import SQLAlchemy
from marshmallow import post_load
from marshmallow_jsonapi import fields
from marshmallow_jsonapi import Schema
# Flask application and database configuration
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Flask-SQLAlchemy model definitions #
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode)
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Unicode)
author_id = db.Column(db.Unicode, db.ForeignKey(Person.id))
author = db.relationship(Person, backref=db.backref('articles'))
# Marshmallow schema definitions #
class PersonSchema(Schema):
class Meta:
model = Person
type_ = 'person'
sqla_session = db.session
strict = True
id = fields.Integer(dump_only=True)
name = fields.Str()
articles = fields.Relationship(
self_url='/api/person/{personid}/relationships/articles',
self_url_kwargs={'personid': '<id>'},
related_url='/api/article/{articleid}',
related_url_kwargs={'articleid': '<id>'},
many=True,
include_data=True,
type_='articles',
)
@post_load
def make_person(self, data):
return Person(**data)
class ArticleSchema(Schema):
class Meta:
model = Article
type_ = 'article'
sqla_session = db.session
strict = True
id = fields.Integer(dump_only=True)
title = fields.Str()
author = fields.Relationship(
self_url='/api/article/{articleid}/relationships/author',
self_url_kwargs={'articleid': '<id>'},
related_url='/api/person/{personid}',
related_url_kwargs={'personid': '<id>'},
include_data=True,
type_='author'
)
@post_load
def make_article(self, data):
return Article(**data)
# Serializer and deserializer classes #
class MarshmallowSerializer(DefaultSerializer):
schema_class = None
def serialize(self, instance, only=None):
schema = self.schema_class(only=only)
return schema.dump(instance).data
def serialize_many(self, instances, only=None):
schema = self.schema_class(many=True, only=only)
return schema.dump(instances).data
class MarshmallowDeserializer(DefaultDeserializer):
schema_class = None
def deserialize(self, document):
schema = self.schema_class()
return schema.load(document).data
def deserialize_many(self, document):
schema = self.schema_class(many=True)
return schema.load(document).data
class PersonSerializer(MarshmallowSerializer):
schema_class = PersonSchema
class PersonDeserializer(MarshmallowDeserializer):
schema_class = PersonSchema
class ArticleSerializer(MarshmallowSerializer):
schema_class = ArticleSchema
class ArticleDeserializer(MarshmallowDeserializer):
schema_class = ArticleSchema
if __name__ == '__main__':
db.create_all()
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Person, methods=['GET', 'POST'],
serializer_class=PersonSerializer,
deserializer_class=PersonDeserializer)
manager.create_api(Article, methods=['GET', 'POST'],
serializer_class=ArticleSerializer,
deserializer_class=ArticleDeserializer)
app.run()
| 6,046
|
Python
|
.py
| 139
| 38.604317
| 79
| 0.738811
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,640
|
__main__.py
|
jfinkels_flask-restless/examples/server_configurations/authentication/__main__.py
|
"""
Authentication example using Flask-Login
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This provides a simple example of using Flask-Login as the authentication
framework which can guard access to certain API endpoints.
This requires the following Python libraries to be installed:
* Flask
* Flask-Login
* Flask-Restless
* Flask-SQLAlchemy
* Flask-WTF
To install them using ``pip``, do::
pip install Flask Flask-SQLAlchemy Flask-Restless Flask-Login Flask-WTF
To use this example, run this package from the command-line. If you are
using Python 2.7 or later::
python -m authentication
If you are using Python 2.6 or earlier::
python -m authentication.__main__
Attempts to access the URL of the API for the :class:`User` class at
``http://localhost:5000/api/user`` will fail with an :http:statuscode:`401`
because you have not yet logged in. To log in, visit
``http://localhost:5000/login`` and login with username ``example`` and
password ``example``. Once you have successfully logged in, you may now
make :http:get:`http://localhost:5000/api/user` requests.
:copyright: 2012 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>
:license: GNU AGPLv3+ or BSD
"""
import os
import os.path
from flask import flash, Flask, render_template, redirect, url_for
from flask_login import current_user, login_user, LoginManager, UserMixin
from flask_restless import APIManager, ProcessingException
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import PasswordField, SubmitField, TextField, Form
# Step 0: the database in this example is at './test.sqlite'.
DATABASE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'test.sqlite')
if os.path.exists(DATABASE):
os.unlink(DATABASE)
# Step 1: setup the Flask application.
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['TESTING'] = True
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % DATABASE
# Step 2: initialize extensions.
db = SQLAlchemy(app)
api_manager = APIManager(app, flask_sqlalchemy_db=db)
login_manager = LoginManager()
login_manager.setup_app(app)
# Step 3: create the user database model.
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Unicode)
password = db.Column(db.Unicode)
# Step 4: create the database and add a test user.
db.create_all()
user1 = User(username=u'example', password=u'example')
db.session.add(user1)
db.session.commit()
# Step 5: this is required for Flask-Login.
@login_manager.user_loader
def load_user(userid):
return User.query.get(userid)
# Step 6: create the login form.
class LoginForm(Form):
username = TextField('username')
password = PasswordField('password')
submit = SubmitField('Login')
# Step 7: create endpoints for the application, one for index and one for login
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
#
# you would check username and password here...
#
username, password = form.username.data, form.password.data
matches = User.query.filter_by(username=username,
password=password).all()
if len(matches) > 0:
login_user(matches[0])
return redirect(url_for('index'))
flash('Username and password pair not found')
return render_template('login.html', form=form)
# Step 8: create the API for User with the authentication guard.
def auth_func(**kw):
if not current_user.is_authenticated():
raise ProcessingException(description='Not Authorized', code=401)
api_manager.create_api(User, preprocessors=dict(GET_SINGLE=[auth_func],
GET_MANY=[auth_func]))
# Step 9: configure and run the application
app.run()
# Step 10: visit http://localhost:5000/api/user in a Web browser. You will
# receive a "Not Authorized" response.
#
# Step 11: visit http://localhost:5000/login and enter username "example" and
# password "example". You will then be logged in.
#
# Step 12: visit http://localhost:5000/api/user again. This time you will get a
# response showing the objects in the User table of the database.
| 4,469
|
Python
|
.py
| 104
| 38.153846
| 79
| 0.701686
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,641
|
conf.py
|
jfinkels_flask-restless/docs/conf.py
|
# -*- coding: utf-8 -*-
#
# Flask-Restless documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 2 00:35:49 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
sys.path.append(os.path.abspath('_themes'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinxcontrib.httpdomain',
'sphinx_issues',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Flask-Restless'
copyright = u'2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
#version = '0.3'
# The full version, including alpha/beta/rc tags.
#release = '0.3-dev'
import pkg_resources
try:
release = pkg_resources.get_distribution('Flask-Restless').version
except pkg_resources.DistributionNotFound:
print('To build the documentation, the distribution information of')
print('Flask-Restless has to be available. Either install the package')
print('into your development environment or run "setup.py develop"')
print('to setup the metadata. A virtualenv is recommended!')
sys.exit(1)
del pkg_resources
if 'dev' in release:
release = release.split('dev')[0] + 'dev'
version = '.'.join(release.split('.')[:3])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
#pygments_style = 'sphinx'
pygments_style = 'flask_theme_support.FlaskyStyle'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#html_theme = 'default'
html_theme = 'flask'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'index_logo': 'flask-restless.png'
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],
'**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html']
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Flask-Restlessdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Flask-Restless.tex', u'Flask-Restless Documentation',
u'Jeffrey Finkelstein', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
latex_domain_indices = False
latex_elements = {
'fontpkg': r'\usepackage{mathpazo}',
'papersize': 'a4paper',
'pointsize': '12pt',
'preamble': r'\usepackage{flaskstyle}'
}
latex_additional_files = ['flaskstyle.sty', 'logo.png']
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'flask-restless', u'Flask-Restless Documentation',
[u'Jeffrey Finkelstein'], 1)
]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'flask': ('http://flask.pocoo.org/docs', None),
'flasklogin': ('https://flask-login.readthedocs.io/en/latest', None),
'flasksqlalchemy': ('http://flask-sqlalchemy.pocoo.org', None),
'python3': ('https://docs.python.org/3', None),
'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest', None),
'werkzeug': ('http://werkzeug.pocoo.org/docs', None),
}
# fall back if theme is not there
try:
__import__('flask_theme_support')
except ImportError, e:
print('-' * 74)
print('Warning: Flask themes unavailable. Building with default theme')
print('If you want the Flask themes, run this command and build again:')
print()
print(' git submodule update --init')
print('-' * 74)
pygments_style = 'tango'
html_theme = 'default'
html_theme_options = {}
# Configuration for sphinx_issues extension.
issues_github_path = 'jfinkels/flask-restless'
| 9,382
|
Python
|
.py
| 216
| 41.356481
| 80
| 0.720659
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,642
|
test_manager.py
|
jfinkels_flask-restless/tests/test_manager.py
|
# test_manager.py - unit tests for the manager module
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for the :mod:`flask_restless.manager` module."""
from unittest2 import skip
from flask import Flask
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from flask_restless import APIManager
from flask_restless import collection_name
from flask_restless import DefaultSerializer
from flask_restless import IllegalArgumentError
from flask_restless import model_for
from flask_restless import serializer_for
from flask_restless import url_for
from .helpers import FlaskSQLAlchemyTestBase
from .helpers import force_content_type_jsonapi
from .helpers import loads
from .helpers import ManagerTestBase
from .helpers import SQLAlchemyTestBase
class TestLocalAPIManager(SQLAlchemyTestBase):
"""Provides tests for :class:`flask_restless.APIManager` when the tests
require that the instance of :class:`flask_restless.APIManager` has not
yet been instantiated.
"""
def setUp(self):
super(TestLocalAPIManager, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
self.Person = Person
self.Article = Article
self.Base.metadata.create_all()
def test_missing_session(self):
"""Tests that setting neither a session nor a Flask-SQLAlchemy
object yields an error.
"""
with self.assertRaises(ValueError):
APIManager(app=self.flaskapp)
def test_constructor_app(self):
"""Tests for providing a :class:`~flask.Flask` application in
the constructor.
"""
manager = APIManager(app=self.flaskapp, session=self.session)
manager.create_api(self.Person)
response = self.app.get('/api/person')
assert response.status_code == 200
def test_single_manager_init_single_app(self):
"""Tests for calling :meth:`~APIManager.init_app` with a single
:class:`~flask.Flask` application after calling
:meth:`~APIManager.create_api`.
"""
manager = APIManager(session=self.session)
manager.create_api(self.Person)
manager.init_app(self.flaskapp)
response = self.app.get('/api/person')
assert response.status_code == 200
def test_single_manager_init_multiple_apps(self):
"""Tests for calling :meth:`~APIManager.init_app` on multiple
:class:`~flask.Flask` applications after calling
:meth:`~APIManager.create_api`.
"""
manager = APIManager(session=self.session)
flaskapp1 = self.flaskapp
flaskapp2 = Flask(__name__)
testclient1 = self.app
testclient2 = flaskapp2.test_client()
force_content_type_jsonapi(testclient2)
manager.create_api(self.Person)
manager.init_app(flaskapp1)
manager.init_app(flaskapp2)
response = testclient1.get('/api/person')
assert response.status_code == 200
response = testclient2.get('/api/person')
assert response.status_code == 200
def test_multiple_managers_init_single_app(self):
"""Tests for calling :meth:`~APIManager.init_app` on a single
:class:`~flask.Flask` application after calling
:meth:`~APIManager.create_api` on multiple instances of
:class:`APIManager`.
"""
manager1 = APIManager(session=self.session)
manager2 = APIManager(session=self.session)
# First create the API, then initialize the Flask applications after.
manager1.create_api(self.Person)
manager2.create_api(self.Article)
manager1.init_app(self.flaskapp)
manager2.init_app(self.flaskapp)
# Tests that both endpoints are accessible on the Flask application.
response = self.app.get('/api/person')
assert response.status_code == 200
response = self.app.get('/api/article')
assert response.status_code == 200
def test_multiple_managers_init_multiple_apps(self):
"""Tests for calling :meth:`~APIManager.init_app` on multiple
:class:`~flask.Flask` applications after calling
:meth:`~APIManager.create_api` on multiple instances of
:class:`APIManager`.
"""
manager1 = APIManager(session=self.session)
manager2 = APIManager(session=self.session)
# Create the Flask applications and the test clients.
flaskapp1 = self.flaskapp
flaskapp2 = Flask(__name__)
testclient1 = self.app
testclient2 = flaskapp2.test_client()
force_content_type_jsonapi(testclient2)
# First create the API, then initialize the Flask applications after.
manager1.create_api(self.Person)
manager2.create_api(self.Article)
manager1.init_app(flaskapp1)
manager2.init_app(flaskapp2)
# Tests that only the first Flask application gets requests for
# /api/person and only the second gets requests for /api/article.
response = testclient1.get('/api/person')
assert response.status_code == 200
response = testclient1.get('/api/article')
assert response.status_code == 404
response = testclient2.get('/api/person')
assert response.status_code == 404
response = testclient2.get('/api/article')
assert response.status_code == 200
def test_universal_preprocessor(self):
"""Tests universal preprocessor and postprocessor applied to all
methods created with the API manager.
"""
class Counter:
"""An object that increments a counter on each invocation."""
def __init__(self):
self._counter = 0
def __call__(self, *args, **kw):
self._counter += 1
def __eq__(self, other):
if isinstance(other, Counter):
return self._counter == other._counter
if isinstance(other, int):
return self._counter == other
return False
increment1 = Counter()
increment2 = Counter()
preprocessors = dict(GET_COLLECTION=[increment1])
postprocessors = dict(GET_COLLECTION=[increment2])
manager = APIManager(self.flaskapp, session=self.session,
preprocessors=preprocessors,
postprocessors=postprocessors)
manager.create_api(self.Person)
manager.create_api(self.Article)
# After each request, regardless of API endpoint, both counters should
# be incremented.
self.app.get('/api/person')
self.app.get('/api/article')
self.app.get('/api/person')
assert increment1 == increment2 == 3
def test_url_prefix(self):
"""Tests for specifying a URL prefix at the manager level but
not when creating an API.
"""
manager = APIManager(self.flaskapp, session=self.session,
url_prefix='/foo')
manager.create_api(self.Person)
response = self.app.get('/foo/person')
assert response.status_code == 200
response = self.app.get('/api/person')
assert response.status_code == 404
def test_empty_url_prefix(self):
"""Tests for specifying an empty string as URL prefix at the manager
level but not when creating an API.
"""
manager = APIManager(self.flaskapp, session=self.session,
url_prefix='')
manager.create_api(self.Person)
response = self.app.get('/person')
assert response.status_code == 200
response = self.app.get('/api/person')
assert response.status_code == 404
def test_override_url_prefix(self):
"""Tests that a call to :meth:`APIManager.create_api` can
override the URL prefix provided in the constructor to the
manager class, if the new URL starts with a slash.
"""
manager = APIManager(self.flaskapp, session=self.session,
url_prefix='/foo')
manager.create_api(self.Person, url_prefix='/bar')
manager.create_api(self.Article, url_prefix='')
response = self.app.get('/bar/person')
assert response.status_code == 200
response = self.app.get('/article')
assert response.status_code == 200
response = self.app.get('/foo/person')
assert response.status_code == 404
response = self.app.get('/foo/article')
assert response.status_code == 404
# # This is a possible feature, but we will not support this for now.
# def test_append_url_prefix(self):
# """Tests that a call to :meth:`APIManager.create_api` can
# append to the URL prefix provided in the constructor to the
# manager class, if the new URL does not start with a slash.
# """
# manager = APIManager(self.flaskapp, session=self.session,
# url_prefix='/foo')
# manager.create_api(self.Person, url_prefix='bar')
# response = self.app.get('/foo/bar/person')
# assert response.status_code == 200
# response = self.app.get('/foo/person')
# assert response.status_code == 404
# response = self.app.get('/bar/person')
# assert response.status_code == 404
def test_schema_app_in_constructor(self):
manager = APIManager(self.flaskapp, session=self.session)
manager.create_api(self.Article)
manager.create_api(self.Person)
response = self.app.get('/api')
self.assertEqual(response.status_code, 200)
document = loads(response.data)
info = document['meta']['modelinfo']
self.assertEqual(sorted(info), ['article', 'person'])
self.assertTrue(info['article']['url'].endswith('/api/article'))
self.assertTrue(info['person']['url'].endswith('/api/person'))
def test_schema_init_app(self):
manager = APIManager(session=self.session)
manager.create_api(self.Article)
manager.create_api(self.Person)
manager.init_app(self.flaskapp)
response = self.app.get('/api')
self.assertEqual(response.status_code, 200)
document = loads(response.data)
info = document['meta']['modelinfo']
self.assertEqual(sorted(info), ['article', 'person'])
self.assertTrue(info['article']['url'].endswith('/api/article'))
self.assertTrue(info['person']['url'].endswith('/api/person'))
class TestAPIManager(ManagerTestBase):
"""Unit tests for the :class:`flask_restless.manager.APIManager` class."""
def setUp(self):
super(TestAPIManager, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
extra = 'foo'
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship(Person, backref=backref('articles'))
class Tag(self.Base):
__tablename__ = 'tag'
name = Column(Unicode, primary_key=True)
self.Article = Article
self.Person = Person
self.Tag = Tag
self.Base.metadata.create_all()
def test_url_for(self):
"""Tests the global :func:`flask_restless.url_for` function."""
self.manager.create_api(self.Person, collection_name='people')
self.manager.create_api(self.Article, collection_name='articles')
with self.flaskapp.test_request_context():
url1 = url_for(self.Person)
url2 = url_for(self.Person, resource_id=1)
url3 = url_for(self.Person, resource_id=1,
relation_name='articles')
url4 = url_for(self.Person, resource_id=1,
relation_name='articles', related_resource_id=2)
assert url1.endswith('/api/people')
assert url2.endswith('/api/people/1')
assert url3.endswith('/api/people/1/articles')
assert url4.endswith('/api/people/1/articles/2')
def test_url_for_explicitly_sets_primary_key_in_links(self):
"""Should use the primary_key explicitly set when generating links"""
article = self.Article(id=1, title=u'my_article')
self.session.add(article)
self.session.commit()
self.manager.create_api(self.Article, primary_key='title')
response = self.app.get('/api/article')
document = loads(response.data)
articles = document['data']
article = articles[0]
assert 'my_article' in article['links']['self']
assert '/1' not in article['links']['self']
author_links = article['relationships']['author']['links']
assert author_links['self'] == (
'/api/article/my_article/relationships/author')
def test_url_for_nonexistent(self):
"""Tests that attempting to get the URL for an unknown model yields an
error.
"""
with self.assertRaises(ValueError):
url_for(self.Person)
def test_collection_name(self):
"""Tests the global :func:`flask_restless.collection_name`
function.
"""
self.manager.create_api(self.Person, collection_name='people')
assert collection_name(self.Person) == 'people'
def test_collection_name_nonexistent(self):
"""Tests that attempting to get the collection name for an unknown
model yields an error.
"""
with self.assertRaises(ValueError):
collection_name(self.Person)
def test_serializer_for(self):
"""Tests the global :func:`flask_restless.serializer_for`
function.
"""
class MySerializer(DefaultSerializer):
pass
self.manager.create_api(self.Person, serializer_class=MySerializer)
assert isinstance(serializer_for(self.Person), MySerializer)
def test_serializer_for_nonexistent(self):
"""Tests that attempting to get the serializer for an unknown
model yields an error.
"""
with self.assertRaises(ValueError):
serializer_for(self.Person)
def test_model_for(self):
"""Tests the global :func:`flask_restless.model_for` function."""
self.manager.create_api(self.Person, collection_name='people')
assert model_for('people') is self.Person
def test_model_for_nonexistent(self):
"""Tests that attempting to get the model for a nonexistent collection
yields an error.
"""
with self.assertRaises(ValueError):
model_for('people')
def test_model_for_collection_name(self):
"""Tests that :func:`flask_restless.model_for` is the inverse of
:func:`flask_restless.collection_name`.
"""
self.manager.create_api(self.Person, collection_name='people')
assert collection_name(model_for('people')) == 'people'
assert model_for(collection_name(self.Person)) is self.Person
def test_disallowed_methods(self):
"""Tests that disallowed methods respond with :http:status:`405`."""
self.manager.create_api(self.Person, methods=[])
for method in 'get', 'post', 'patch', 'delete':
func = getattr(self.app, method)
response = func('/api/person')
assert response.status_code == 405
def test_empty_collection_name(self):
"""Tests that calling :meth:`APIManager.create_api` with an empty
collection name raises an exception.
"""
with self.assertRaises(IllegalArgumentError):
self.manager.create_api(self.Person, collection_name='')
def test_disallow_functions(self):
"""Tests that if the ``allow_functions`` keyword argument is ``False``,
no endpoint will be made available at :http:get:`/api/eval/:type`.
"""
self.manager.create_api(self.Person, allow_functions=False)
response = self.app.get('/api/eval/person')
assert response.status_code == 404
@skip('This test does not make sense anymore with JSON API')
def test_exclude_primary_key_column(self):
"""Tests that trying to create a writable API while excluding the
primary key field raises an error.
"""
with self.assertRaises(IllegalArgumentError):
self.manager.create_api(self.Person, exclude=['id'],
methods=['POST'])
def test_only_and_exclude(self):
"""Tests that attempting to use both ``only`` and ``exclude``
keyword arguments yields an error.
"""
with self.assertRaises(IllegalArgumentError):
self.manager.create_api(self.Person, only=['id'], exclude=['name'])
def test_additional_attributes_nonexistent(self):
"""Tests that an attempt to include an additional attribute that
does not exist on the model raises an exception at the time of
API creation.
"""
with self.assertRaises(AttributeError):
self.manager.create_api(self.Person,
additional_attributes=['bogus'])
def test_exclude_additional_attributes(self):
"""Tests that an attempt to exclude a field that is also
specified in ``additional_attributes`` causes an exception at
the time of API creation.
"""
with self.assertRaises(IllegalArgumentError):
self.manager.create_api(self.Person, exclude=['extra'],
additional_attributes=['extra'])
class TestFSA(FlaskSQLAlchemyTestBase):
"""Tests which use models defined using Flask-SQLAlchemy instead of pure
SQLAlchemy.
"""
def setUp(self):
"""Creates the Flask application, the APIManager, the database, and the
Flask-SQLAlchemy models.
"""
super(TestFSA, self).setUp()
class Person(self.db.Model):
id = self.db.Column(self.db.Integer, primary_key=True)
self.Person = Person
def test_init_app(self):
self.db.create_all()
manager = APIManager(flask_sqlalchemy_db=self.db)
manager.create_api(self.Person)
manager.init_app(self.flaskapp)
response = self.app.get('/api/person')
assert response.status_code == 200
def test_create_api_before_db_create_all(self):
"""Tests that we can create APIs before
:meth:`flask_sqlalchemy.SQLAlchemy.create_all` is called.
"""
manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
manager.create_api(self.Person)
self.db.create_all()
person = self.Person(id=1)
self.db.session.add(person)
self.db.session.commit()
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert '1' == person['id']
| 19,868
|
Python
|
.py
| 430
| 37.097674
| 79
| 0.64323
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,643
|
test_polymorphism.py
|
jfinkels_flask-restless/tests/test_polymorphism.py
|
# test_polymorphism.py - unit tests for polymorphic models
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for interacting with polymorphic models.
The tests in this module use models defined using `single table
inheritance`_ and `joined table inheritance`_.
.. _single table inheritance:
http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#single-table-inheritance
.. _joined table inheritance:
http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance
"""
from operator import itemgetter
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Enum
from sqlalchemy import ForeignKey
from sqlalchemy import Unicode
from flask_restless import DefaultSerializer
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import loads
from .helpers import ManagerTestBase
class SingleTableInheritanceSetupMixin(object):
"""Mixin for setting up single table inheritance in test cases."""
def setUp(self):
"""Creates polymorphic models using single table inheritance."""
super(SingleTableInheritanceSetupMixin, self).setUp()
class Employee(self.Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
type = Column(Enum('employee', 'manager'), nullable=False)
name = Column(Unicode)
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': 'employee'
}
# This model inherits directly from the `Employee` class, so
# there is only one table being used.
class Manager(Employee):
__mapper_args__ = {
'polymorphic_identity': 'manager'
}
self.Employee = Employee
self.Manager = Manager
self.Base.metadata.create_all()
class JoinedTableInheritanceSetupMixin(object):
"""Mixin for setting up joined table inheritance in test cases."""
def setUp(self):
"""Creates polymorphic models using joined table inheritance."""
super(JoinedTableInheritanceSetupMixin, self).setUp()
class Employee(self.Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
type = Column(Enum('employee', 'manager'), nullable=False)
name = Column(Unicode)
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': 'employee'
}
# This model inherits directly from the `Employee` class, so
# there is only one table being used.
class Manager(Employee):
__tablename__ = 'manager'
id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
__mapper_args__ = {
'polymorphic_identity': 'manager'
}
self.Employee = Employee
self.Manager = Manager
self.Base.metadata.create_all()
class FetchingTestMixinBase(object):
"""Base class for test cases for fetching resources."""
def setUp(self):
super(FetchingTestMixinBase, self).setUp()
# Create the APIs for the Employee and Manager.
self.apimanager = self.manager
self.apimanager.create_api(self.Employee)
self.apimanager.create_api(self.Manager)
# Populate the database. Store a reference to the actual
# instances so that test methods in subclasses can access them.
self.employee = self.Employee(id=1)
self.manager = self.Manager(id=2)
self.session.add_all([self.employee, self.manager])
self.session.commit()
class FetchCollectionTestMixin(FetchingTestMixinBase):
"""Tests for fetching a collection of resources defined using single
table inheritance.
"""
def test_subclass(self):
"""Tests that fetching a collection at the subclass endpoint
yields only instance of the subclass.
"""
response = self.app.get('/api/manager')
assert response.status_code == 200
document = loads(response.data)
managers = document['data']
assert len(managers) == 1
manager = managers[0]
assert 'manager' == manager['type']
assert '2' == manager['id']
def test_superclass(self):
"""Tests that fetching a collection at the superclass endpoint
yields instances of both the subclass and the superclass.
"""
response = self.app.get('/api/employee')
assert response.status_code == 200
document = loads(response.data)
employees = document['data']
employees = sorted(employees, key=itemgetter('id'))
employee_types = list(map(itemgetter('type'), employees))
employee_ids = list(map(itemgetter('id'), employees))
assert ['employee', 'manager'] == employee_types
assert ['1', '2'] == employee_ids
def test_heterogeneous_serialization(self):
"""Tests that each object is serialized using the serializer
specified in :meth:`APIManager.create_api`.
"""
class EmployeeSerializer(DefaultSerializer):
def serialize(self, instance, *args, **kw):
superserialize = super(EmployeeSerializer, self).serialize
result = superserialize(instance, *args, **kw)
result['data']['attributes']['foo'] = 'bar'
return result
class ManagerSerializer(DefaultSerializer):
def serialize(self, instance, *args, **kw):
superserialize = super(ManagerSerializer, self).serialize
result = superserialize(instance, *args, **kw)
result['data']['attributes']['baz'] = 'xyzzy'
return result
self.apimanager.create_api(self.Employee, url_prefix='/api2',
serializer_class=EmployeeSerializer)
self.apimanager.create_api(self.Manager, url_prefix='/api2',
serializer_class=ManagerSerializer)
response = self.app.get('/api/employee')
assert response.status_code == 200
document = loads(response.data)
employees = document['data']
assert len(employees) == 2
employees = sorted(employees, key=itemgetter('id'))
assert employees[0]['attributes']['foo'] == 'bar'
assert employees[1]['attributes']['baz'] == 'xyzzy'
class FetchResourceTestMixin(FetchingTestMixinBase):
"""Tests for fetching a single resource defined using single table
inheritance.
"""
def test_subclass_at_subclass(self):
"""Tests for fetching a resource of the subclass type at the URL
for the subclass.
"""
response = self.app.get('/api/employee/1')
assert response.status_code == 200
document = loads(response.data)
resource = document['data']
assert resource['type'] == 'employee'
assert resource['id'] == str(self.employee.id)
def superclass_at_superclass(self):
"""Tests for fetching a resource of the superclass type at the
URL for the superclass.
"""
response = self.app.get('/api/manager/2')
assert response.status_code == 200
document = loads(response.data)
resource = document['data']
assert resource['type'] == 'manager'
assert resource['id'] == str(self.manager.id)
def test_superclass_at_subclass(self):
"""Tests that attempting to fetch a resource of the superclass
type at the subclass endpoint causes an exception.
"""
response = self.app.get('/api/manager/1')
assert response.status_code == 404
def test_subclass_at_superclass(self):
"""Tests that attempting to fetch a resource of the subclass
type at the superclass endpoint causes an exception.
"""
response = self.app.get('/api/employee/2')
assert response.status_code == 404
class CreatingTestMixin(object):
"""Tests for APIs created for polymorphic models defined using
single table inheritance.
"""
def setUp(self):
super(CreatingTestMixin, self).setUp()
self.manager.create_api(self.Employee, methods=['POST'])
self.manager.create_api(self.Manager, methods=['POST'])
def test_subclass_at_subclass(self):
"""Tests for creating a resource of the subclass type at the URL
for the subclass.
"""
data = {
'data': {
'type': 'manager'
}
}
response = self.app.post('/api/manager', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
manager = document['data']
manager_in_db = self.session.query(self.Manager).first()
assert manager['id'] == str(manager_in_db.id)
assert manager['type'] == 'manager'
def test_superclass_at_superclass(self):
"""Tests for creating a resource of the superclass type at the
URL for the superclass.
"""
data = {
'data': {
'type': 'employee'
}
}
response = self.app.post('/api/employee', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
employee = document['data']
employee_in_db = self.session.query(self.Employee).first()
assert employee['id'] == str(employee_in_db.id)
assert employee['type'] == 'employee'
def test_subclass_at_superclass(self):
"""Tests that attempting to create a resource of the subclass
type at the URL for the superclass causes an error.
"""
data = {
'data': {
'type': 'manager'
}
}
response = self.app.post('/api/employee', data=dumps(data))
check_sole_error(response, 409, ['Failed', 'deserialize', 'expected',
'type', 'employee', 'manager'])
def test_superclass_at_subclass(self):
"""Tests that attempting to create a resource of the superclass
type at the URL for the subclass causes an error.
"""
data = {
'data': {
'type': 'employee'
}
}
response = self.app.post('/api/manager', data=dumps(data))
check_sole_error(response, 409, ['Failed', 'deserialize', 'expected',
'type', 'manager', 'employee'])
class DeletingTestMixin(object):
"""Tests for deleting resources."""
def setUp(self):
super(DeletingTestMixin, self).setUp()
# Create the APIs for the Employee and Manager.
self.manager.create_api(self.Employee, methods=['DELETE'])
self.manager.create_api(self.Manager, methods=['DELETE'])
# Populate the database. Store a reference to the actual
# instances so that test methods in subclasses can access them.
self.employee = self.Employee(id=1)
self.manager = self.Manager(id=2)
self.all_employees = [self.employee, self.manager]
self.session.add_all(self.all_employees)
self.session.commit()
def test_subclass_at_subclass(self):
"""Tests for deleting a resource of the subclass type at the URL
for the subclass.
"""
response = self.app.delete('/api/manager/2')
assert response.status_code == 204
assert self.session.query(self.Manager).count() == 0
assert self.session.query(self.Employee).all() == [self.employee]
def test_superclass_at_superclass(self):
"""Tests for deleting a resource of the superclass type at the
URL for the superclass.
"""
response = self.app.delete('/api/employee/1')
assert response.status_code == 204
assert self.session.query(self.Manager).all() == [self.manager]
assert self.session.query(self.Employee).all() == [self.manager]
def test_subclass_at_superclass(self):
"""Tests that attempting to delete a resource of the subclass
type at the URL for the superclass causes an error.
"""
response = self.app.delete('/api/employee/2')
check_sole_error(response, 404, ['No resource found', 'type',
'employee', 'ID', '2'])
assert self.session.query(self.Manager).all() == [self.manager]
assert self.session.query(self.Employee).all() == self.all_employees
def test_superclass_at_subclass(self):
"""Tests that attempting to delete a resource of the superclass
type at the URL for the subclass causes an error.
"""
response = self.app.delete('/api/manager/1')
check_sole_error(response, 404, ['No resource found', 'type',
'manager', 'ID', '1'])
assert self.session.query(self.Manager).all() == [self.manager]
assert self.session.query(self.Employee).all() == self.all_employees
class UpdatingTestMixin(object):
"""Tests for updating resources."""
def setUp(self):
super(UpdatingTestMixin, self).setUp()
# Create the APIs for the Employee and Manager.
self.manager.create_api(self.Employee, methods=['PATCH'])
self.manager.create_api(self.Manager, methods=['PATCH'])
# Populate the database. Store a reference to the actual
# instances so that test methods in subclasses can access them.
self.employee = self.Employee(id=1, name=u'foo')
self.manager = self.Manager(id=2, name=u'foo')
self.session.add_all([self.employee, self.manager])
self.session.commit()
def test_subclass_at_subclass(self):
"""Tests for updating a resource of the subclass type at the URL
for the subclass.
"""
data = {
'data': {
'type': 'manager',
'id': '2',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/manager/2', data=dumps(data))
assert response.status_code == 204
assert self.manager.name == u'bar'
def test_superclass_at_superclass(self):
"""Tests for updating a resource of the superclass type at the
URL for the superclass.
"""
data = {
'data': {
'type': 'employee',
'id': '1',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/employee/1', data=dumps(data))
assert response.status_code == 204
assert self.employee.name == u'bar'
def test_subclass_at_superclass(self):
"""Tests that attempting to update a resource of the subclass
type at the URL for the superclass causes an error.
"""
# In this test, the JSON document has the correct type and ID,
# but the URL has the wrong type. Even though "manager" is a
# subtype of "employee" Flask-Restless doesn't allow a mismatch
# of types when updating.
data = {
'data': {
'type': 'manager',
'id': '2',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/employee/2', data=dumps(data))
check_sole_error(response, 404, ['No resource found', 'type',
'employee', 'ID', '2'])
def test_superclass_at_subclass(self):
"""Tests that attempting to update a resource of the superclass
type at the URL for the subclass causes an error.
"""
# In this test, the JSON document has the correct type and ID,
# but the URL has the wrong type.
data = {
'data': {
'type': 'employee',
'id': '1',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/manager/1', data=dumps(data))
check_sole_error(response, 404, ['No resource found', 'type',
'manager', 'ID', '1'])
class TestFetchCollectionSingle(FetchCollectionTestMixin,
SingleTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for fetching a collection of resources defined using single
table inheritance.
"""
class TestFetchCollectionJoined(FetchCollectionTestMixin,
JoinedTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for fetching a collection of resources defined using joined
table inheritance.
"""
class TestFetchResourceSingle(FetchResourceTestMixin,
SingleTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for fetching a single resource defined using single table
inheritance.
"""
class TestFetchResourceJoined(FetchResourceTestMixin,
JoinedTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for fetching a single resource defined using joined table
inheritance.
"""
class TestCreatingSingle(CreatingTestMixin, SingleTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for creating a resource defined using single table inheritance."""
class TestCreatingJoined(CreatingTestMixin, JoinedTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for creating a resource defined using joined table inheritance."""
class TestDeletingSingle(DeletingTestMixin, SingleTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for deleting a resource defined using single table inheritance."""
class TestDeletingJoined(DeletingTestMixin, JoinedTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for deleting a resource defined using joined table inheritance."""
class TestUpdatingSingle(UpdatingTestMixin, SingleTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for updating a resource defined using single table inheritance."""
class TestUpdatingJoined(UpdatingTestMixin, JoinedTableInheritanceSetupMixin,
ManagerTestBase):
"""Tests for updating a resource defined using joined table inheritance."""
| 19,077
|
Python
|
.py
| 422
| 35.004739
| 85
| 0.619446
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,644
|
test_deleting.py
|
jfinkels_flask-restless/tests/test_deleting.py
|
# test_deleting.py - unit tests for deleting resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for deleting resources from endpoints generated by
Flask-Restless.
This module includes tests for additional functionality that is not
already tested by :mod:`test_jsonapi`, the package that guarantees
Flask-Restless meets the minimum requirements of the JSON API
specification.
"""
from unittest2 import skip
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.orm import relationship
from flask_restless import APIManager
from flask_restless import ProcessingException
from .helpers import dumps
from .helpers import loads
from .helpers import FlaskSQLAlchemyTestBase
from .helpers import ManagerTestBase
from .helpers import MSIE8_UA
from .helpers import MSIE9_UA
class TestDeleting(ManagerTestBase):
"""Tests for deleting resources."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestDeleting, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author = relationship('Person')
author_id = Column(Integer, ForeignKey('person.id'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article, methods=['DELETE'])
self.manager.create_api(Person, methods=['DELETE'])
def test_wrong_accept_header(self):
"""Tests that if a client specifies only :http:header:`Accept`
headers with non-JSON API media types, then the server responds
with a :http:status:`406`.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
headers = {'Accept': 'application/json'}
response = self.app.delete('/api/person/1', headers=headers)
assert response.status_code == 406
assert self.session.query(self.Person).all() == [person]
def test_related_resource_url_forbidden(self):
"""Tests that :http:method:`delete` requests to a related resource URL
are forbidden.
"""
article = self.Article(id=1)
person = self.Person(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(type='person', id=1))
response = self.app.delete('/api/article/1/author', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
assert article.author is person
def test_msie8(self):
"""Tests for compatibility with Microsoft Internet Explorer 8.
According to issue #267, making requests using JavaScript from MSIE8
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
headers = {'User-Agent': MSIE8_UA}
content_type = 'text/html'
response = self.app.delete('/api/person/1', headers=headers,
content_type=content_type)
assert response.status_code == 204
def test_msie9(self):
"""Tests for compatibility with Microsoft Internet Explorer 9.
According to issue #267, making requests using JavaScript from MSIE9
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
headers = {'User-Agent': MSIE9_UA}
content_type = 'text/html'
response = self.app.delete('/api/person/1', headers=headers,
content_type=content_type)
assert response.status_code == 204
def test_disallow_delete_many(self):
"""Tests that deleting an entire collection is disallowed by default.
Deleting an entire collection is not discussed in the JSON API
specification.
"""
response = self.app.delete('/api/person')
assert response.status_code == 405
@skip('Not sure how to implement this.')
def test_integrity_error(self):
"""Tests that an :exc:`IntegrityError` raised in a
:http:method:`delete` request is caught and returned to the client
safely.
"""
assert False, 'Not implemented'
def test_nonexistent_instance(self):
"""Tests that a request to delete a nonexistent resource yields a
:http:status:`404 response.
"""
response = self.app.delete('/api/person/1')
assert response.status_code == 404
def test_related_resource_url(self):
"""Tests that attempting to delete from a related resource URL (instead
of a relationship URL) yields an error response.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.delete('/api/article/1/author')
assert response.status_code == 405
# TODO check error message here
class TestProcessors(ManagerTestBase):
"""Tests for pre- and postprocessors."""
def setUp(self):
super(TestProcessors, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Person = Person
self.Base.metadata.create_all()
def test_resource(self):
"""Tests for running a preprocessor on a request to delete a
single resource.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'DELETE_RESOURCE': [update_data]}
self.manager.create_api(self.Person, methods=['DELETE'],
preprocessors=preprocessors)
self.app.delete('/api/person/1')
assert data['triggered']
def test_change_id(self):
"""Tests that a return value from a preprocessor overrides the ID of
the resource to fetch as given in the request URL.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
def increment_id(resource_id=None, **kw):
if resource_id is None:
raise ProcessingException
return int(resource_id) + 1
preprocessors = dict(DELETE_RESOURCE=[increment_id])
self.manager.create_api(self.Person, methods=['DELETE'],
preprocessors=preprocessors)
response = self.app.delete('/api/person/0')
assert response.status_code == 204
assert self.session.query(self.Person).count() == 0
def test_processing_exception(self):
"""Tests for a preprocessor that raises a :exc:`ProcessingException`
when deleting a single resource.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
def forbidden(**kw):
raise ProcessingException(status=403, detail='forbidden')
preprocessors = dict(DELETE_RESOURCE=[forbidden])
self.manager.create_api(self.Person, methods=['DELETE'],
preprocessors=preprocessors)
response = self.app.delete('/api/person/1')
assert response.status_code == 403
document = loads(response.data)
errors = document['errors']
assert len(errors) == 1
error = errors[0]
assert 'forbidden' == error['detail']
# Ensure that the person has not been deleted.
assert self.session.query(self.Person).first() == person
def test_postprocessor(self):
"""Tests that a postprocessor is invoked when deleting a resource."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
def assert_deletion(was_deleted=False, **kw):
assert was_deleted
postprocessors = dict(DELETE_RESOURCE=[assert_deletion])
self.manager.create_api(self.Person, methods=['DELETE'],
postprocessors=postprocessors)
response = self.app.delete('/api/person/1')
assert response.status_code == 204
def test_postprocessor_no_commit_on_error(self):
"""Tests that a processing exception causes the session to be
flushed but not committed.
"""
def raise_error(**kw):
raise ProcessingException(status=500)
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
postprocessors = dict(DELETE_RESOURCE=[raise_error])
self.manager.create_api(self.Person, methods=['DELETE'],
postprocessors=postprocessors)
response = self.app.delete('/api/person/1')
assert response.status_code == 500
people = self.session.query(self.Person).all()
assert people == []
self.session.rollback()
people = self.session.query(self.Person).all()
assert people == [person]
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
"""Tests for deleting resources defined as Flask-SQLAlchemy models instead
of pure SQLAlchemy models.
"""
def setUp(self):
"""Creates the Flask-SQLAlchemy database and models."""
super(TestFlaskSQLAlchemy, self).setUp()
class Person(self.db.Model):
id = self.db.Column(self.db.Integer, primary_key=True)
self.Person = Person
self.db.create_all()
self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
self.manager.create_api(self.Person, methods=['DELETE'])
def test_delete(self):
"""Tests for deleting a resource."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.delete('/api/person/1')
assert response.status_code == 204
assert self.Person.query.count() == 0
| 11,290
|
Python
|
.py
| 255
| 35.513725
| 79
| 0.649407
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,645
|
test_functions.py
|
jfinkels_flask-restless/tests/test_functions.py
|
# test_functions.py - unit tests for function evaluation endpoints
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for function evaluation endpoints."""
from sqlalchemy import Column
from sqlalchemy import Integer
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import loads
from .helpers import ManagerTestBase
class TestFunctionEvaluation(ManagerTestBase):
"""Unit tests for the :class:`flask_restless.views.FunctionAPI` class."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`testapp.Person` and
:class:`testapp.Computer` models.
"""
super(TestFunctionEvaluation, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
age = Column(Integer)
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Person, allow_functions=True)
def test_multiple_functions(self):
"""Test that the :http:get:`/api/eval/person` endpoint returns the
result of evaluating multiple functions.
"""
person1 = self.Person(age=10)
person2 = self.Person(age=15)
person3 = self.Person(age=20)
self.session.add_all([person1, person2, person3])
self.session.commit()
functions = [dict(name='sum', field='age'),
dict(name='avg', field='age'),
dict(name='count', field='id')]
query_string = {'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
results = document['data']
assert [45.0, 15.0, 3] == results
def test_no_query(self):
"""Tests that a request to the function evaluation endpoint with no
query parameter yields an error response.
"""
response = self.app.get('/api/eval/person')
check_sole_error(response, 400, ['functions', 'provide',
'query parameter'])
def test_empty_query(self):
"""Tests that a request to the function evaluation endpoint with an
empty functions query yields an error response.
"""
query_string = {'functions': ''}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['Unable', 'decode', 'JSON',
'functions'])
def test_no_functions(self):
"""Tests that if no functions are defined, an empty response is
returned.
"""
functions = []
query_string = {'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
results = document['data']
assert results == []
def test_missing_function_name(self):
functions = [dict(field='age')]
query_string = {'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['Missing', 'name', 'function'])
def test_missing_field_name(self):
functions = [dict(name='sum')]
query_string = {'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['Missing', 'field', 'function'])
def test_bad_field_name(self):
functions = [dict(name='sum', field='bogus')]
query_string = {'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['unknown', 'field', 'bogus'])
def test_bad_function_name(self):
"""Tests that an unknown function name yields an error response."""
functions = [dict(name='bogus', field='age')]
query_string = {'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['unknown', 'function', 'bogus'])
def test_jsonp(self):
"""Test for JSON-P callbacks."""
person = self.Person(age=10)
self.session.add(person)
self.session.commit()
functions = [dict(name='sum', field='age')]
query_string = {'functions': dumps(functions), 'callback': 'foo'}
response = self.app.get('/api/eval/person', query_string=query_string)
assert response.status_code == 200
assert response.mimetype == 'application/javascript'
assert response.data.startswith(b'foo(')
assert response.data.endswith(b')')
document = loads(response.data[4:-1])
results = document['data']
assert [10.0] == results
def test_filter_before_functions(self):
"""Tests that filters are applied before functions are called.
"""
person1 = self.Person(age=5)
person2 = self.Person(age=10)
person3 = self.Person(age=15)
person4 = self.Person(age=20)
self.session.add_all([person1, person2, person3, person4])
self.session.commit()
# This filter should exclude `person4`.
filters = [{'name': 'age', 'op': '<', 'val': 20}]
# Get the sum of the ages and the mean of the ages, in that order.
functions = [
{'name': 'sum', 'field': 'age'},
{'name': 'avg', 'field': 'age'},
]
query_string = {'filter[objects]': dumps(filters),
'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
results = document['data']
assert [30, 10.0] == results
def test_bad_filter_json(self):
"""Tests for invalid JSON in the ``filter[objects]`` query parameter.
"""
functions = [{'name': 'sum', 'field': 'age'}]
query_string = {'filter[objects]': 'bogus',
'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['Unable', 'decode', 'filter objects'])
def test_invalid_filter_object(self):
"""Tests that providing an incorrectly formatted argument to
``filter[objects]`` yields an error response.
"""
functions = [{'name': 'sum', 'field': 'age'}]
filters = [{'name': 'bogus', 'op': 'eq', 'val': 'foo'}]
query_string = {'filter[objects]': dumps(filters),
'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['invalid', 'filter', 'object',
'bogus'])
def test_bad_single(self):
"""Tests that providing an incorrectly formatted argument to
``filter[single]`` yields an error response.
"""
functions = [{'name': 'sum', 'field': 'age'}]
query_string = {'filter[single]': 'bogus',
'functions': dumps(functions)}
response = self.app.get('/api/eval/person', query_string=query_string)
check_sole_error(response, 400, ['Invalid', 'format', 'single',
'query parameter'])
| 8,092
|
Python
|
.py
| 166
| 39.39759
| 79
| 0.614206
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,646
|
test_filtering_postgresql.py
|
jfinkels_flask-restless/tests/test_filtering_postgresql.py
|
# test_filtering_postgresql.py - filtering tests for PostgreSQL
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for PostgreSQL-specific filtering operators."""
# The psycopg2cffi import is required for testing on PyPy. CPython can
# use psycopg2, but PyPy can only use psycopg2cffi.
try:
import psycopg2 # noqa
except ImportError:
from psycopg2cffi import compat
compat.register()
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy.dialects.postgresql import INET
from sqlalchemy.exc import OperationalError
from .helpers import loads
from .test_filtering import SearchTestBase
class TestNetworkOperators(SearchTestBase):
"""Unit tests for the network address operators in PostgreSQL.
For more information, see `Network Address Functions and Operators`_
in the PostgreSQL documentation.
.. _Network Address Functions and Operators:
http://www.postgresql.org/docs/current/interactive/functions-net.html
"""
def setUp(self):
super(TestNetworkOperators, self).setUp()
class Network(self.Base):
__tablename__ = 'network'
id = Column(Integer, primary_key=True)
address = Column(INET)
self.Network = Network
# This try/except skips the tests if we are unable to create the
# tables in the PostgreSQL database.
try:
self.Base.metadata.create_all()
except OperationalError:
self.skipTest('error creating tables in PostgreSQL database')
self.manager.create_api(Network)
def database_uri(self):
"""Return a PostgreSQL connection URI.
Since this test case is for operators specific to PostgreSQL, we
return a PostgreSQL connection URI. The particular
Python-to-PostgreSQL adapter we are using is currently
`Psycopg`_.
.. _Psycopg: http://initd.org/psycopg/
"""
return 'postgresql+psycopg2://postgres@localhost:5432/testdb'
def test_is_not_equal(self):
"""Test for the ``<>`` ("is not equal") operator.
For example:
.. sourcecode:: postgresql
inet '192.168.1.5' <> inet '192.168.1.4'
"""
network1 = self.Network(id=1, address='192.168.1.5')
network2 = self.Network(id=2, address='192.168.1.4')
self.session.add_all([network1, network2])
self.session.commit()
filters = [dict(name='address', op='<>', val='192.168.1.4')]
response = self.search('/api/network', filters)
document = loads(response.data)
networks = document['data']
assert ['1'] == sorted(network['id'] for network in networks)
def test_is_contained_by(self):
"""Test for the ``<<`` ("is contained by") operator.
For example:
.. sourcecode:: postgresql
inet '192.168.1.5' << inet '192.168.1/24'
"""
network1 = self.Network(id=1, address='192.168.1.5')
network2 = self.Network(id=2, address='192.168.2.1')
self.session.add_all([network1, network2])
self.session.commit()
filters = [dict(name='address', op='<<', val='192.168.1/24')]
response = self.search('/api/network', filters)
document = loads(response.data)
networks = document['data']
assert ['1'] == sorted(network['id'] for network in networks)
def test_is_contained_by_or_equals(self):
"""Test for the ``<<=`` ("is contained by or equals") operator.
For example:
.. sourcecode:: postgresql
inet '192.168.1/24' <<= inet '192.168.1/24'
"""
network1 = self.Network(id=1, address='192.168.1/24')
network2 = self.Network(id=2, address='192.168.1.5')
network3 = self.Network(id=3, address='192.168.2.1')
self.session.add_all([network1, network2, network3])
self.session.commit()
filters = [dict(name='address', op='<<=', val='192.168.1/24')]
response = self.search('/api/network', filters)
document = loads(response.data)
networks = document['data']
assert ['1', '2'] == sorted(network['id'] for network in networks)
def test_contains(self):
"""Test for the ``>>`` ("contains") operator.
For example:
.. sourcecode:: postgresql
inet '192.168.1/24' >> inet '192.168.1.5'
"""
network1 = self.Network(id=1, address='192.168.1/24')
network2 = self.Network(id=2, address='192.168.2/24')
self.session.add_all([network1, network2])
self.session.commit()
filters = [dict(name='address', op='>>', val='192.168.1.5')]
response = self.search('/api/network', filters)
document = loads(response.data)
networks = document['data']
assert ['1'] == sorted(network['id'] for network in networks)
def test_contains_or_equals(self):
"""Test for the ``>>=`` ("contains or equals") operator.
For example:
.. sourcecode:: postgresql
inet '192.168.1/24' >>= inet '192.168.1/24'
"""
network1 = self.Network(id=1, address='192.168.1/24')
network2 = self.Network(id=2, address='192.168/16')
network3 = self.Network(id=3, address='192.168.2/24')
self.session.add_all([network1, network2, network3])
self.session.commit()
filters = [dict(name='address', op='>>=', val='192.168.1/24')]
response = self.search('/api/network', filters)
document = loads(response.data)
networks = document['data']
assert ['1', '2'] == sorted(network['id'] for network in networks)
def test_contains_or_is_contained_by(self):
"""Test for the ``&&`` ("contains or is contained by") operator.
.. warning::
This operation is only available in PostgreSQL 9.4 or later.
For example:
.. sourcecode:: postgresql
inet '192.168.1/24' && inet '192.168.1.80/28'
"""
# network1 contains the queried subnet
network1 = self.Network(id=1, address='192.168.1/24')
# network2 is contained by the queried subnet
network2 = self.Network(id=2, address='192.168.1.81/28')
# network3 is neither
network3 = self.Network(id=3, address='192.168.2.1')
self.session.add_all([network1, network2, network3])
self.session.commit()
filters = [dict(name='address', op='&&', val='192.168.1.80/28')]
response = self.search('/api/network', filters)
document = loads(response.data)
networks = document['data']
assert ['1', '2'] == sorted(network['id'] for network in networks)
| 7,057
|
Python
|
.py
| 153
| 38.183007
| 76
| 0.632983
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,647
|
test_updating.py
|
jfinkels_flask-restless/tests/test_updating.py
|
# test_updating.py - unit tests for updating resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for updating resources from endpoints generated by
Flask-Restless.
This module includes tests for additional functionality that is not
already tested by :mod:`test_jsonapi`, the package that guarantees
Flask-Restless meets the minimum requirements of the JSON API
specification.
"""
from __future__ import division
from datetime import datetime
from unittest2 import skip
try:
from flask_sqlalchemy import SQLAlchemy
except ImportError:
has_flask_sqlalchemy = False
else:
has_flask_sqlalchemy = True
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import Time
from sqlalchemy import Unicode
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from flask_restless import APIManager
from flask_restless import JSONAPI_MIMETYPE
from flask_restless import ProcessingException
from .helpers import BetterJSONEncoder as JSONEncoder
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import FlaskSQLAlchemyTestBase
from .helpers import loads
from .helpers import MSIE8_UA
from .helpers import MSIE9_UA
from .helpers import ManagerTestBase
from .helpers import raise_s_exception as raise_exception
class TestUpdating(ManagerTestBase):
"""Tests for updating resources."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestUpdating, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author = relationship('Person', backref=backref('articles'))
author_id = Column(Integer, ForeignKey('person.id'))
type = Column(Unicode)
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode, unique=True)
bedtime = Column(Time)
date_created = Column(Date)
birth_datetime = Column(DateTime)
def foo(self):
return u'foo'
# This example comes from the SQLAlchemy documentation.
#
# The SQLAlchemy documentation is licensed under the MIT license.
class Interval(self.Base):
__tablename__ = 'interval'
id = Column(Integer, primary_key=True)
start = Column(Integer, nullable=False)
end = Column(Integer, nullable=False)
@hybrid_property
def length(self):
return self.end - self.start
@length.setter
def length(self, value):
self.end = self.start + value
@hybrid_property
def radius(self):
return self.length / 2
@radius.expression
def radius(cls):
return cls.length / 2
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
updated_at = Column(DateTime, server_default=func.now(),
onupdate=func.current_timestamp())
self.Article = Article
self.Interval = Interval
self.Person = Person
self.Tag = Tag
self.Base.metadata.create_all()
self.manager.create_api(Article, methods=['PATCH'])
self.manager.create_api(Interval, methods=['PATCH'])
self.manager.create_api(Person, methods=['PATCH'])
def test_wrong_content_type(self):
"""Tests that if a client specifies only :http:header:`Accept`
headers with non-JSON API media types, then the server responds
with a :http:status:`415`.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
headers = {'Content-Type': 'application/json'}
data = {
'data': {
'type': 'person',
'id': 1,
'attributes': {
'name': 'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data),
headers=headers)
assert response.status_code == 415
assert person.name == u'foo'
def test_wrong_accept_header(self):
"""Tests that if a client specifies only :http:header:`Accept`
headers with non-JSON API media types, then the server responds
with a :http:status:`406`.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
headers = {'Accept': 'application/json'}
data = {
'data': {
'type': 'person',
'id': 1,
'attributes': {
'name': 'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data),
headers=headers)
assert response.status_code == 406
assert person.name == u'foo'
def test_related_resource_url_forbidden(self):
"""Tests that :http:method:`patch` requests to a related resource URL
are forbidden.
"""
article = self.Article(id=1)
person = self.Person(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(type='person', id=1))
response = self.app.patch('/api/article/1/author', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
assert article.author is None
def test_deserializing_time(self):
"""Test for deserializing a JSON representation of a time field."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
bedtime = datetime.now().time()
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'bedtime': bedtime
}
}
}
# Python's built-in JSON encoder doesn't serialize date/time objects by
# default.
data = dumps(data, cls=JSONEncoder)
response = self.app.patch('/api/person/1', data=data)
assert response.status_code == 204
assert person.bedtime == bedtime
def test_deserializing_date(self):
"""Test for deserializing a JSON representation of a date field."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
today = datetime.now().date()
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'date_created': today
}
}
}
# Python's built-in JSON encoder doesn't serialize date/time objects by
# default.
data = dumps(data, cls=JSONEncoder)
response = self.app.patch('/api/person/1', data=data)
assert response.status_code == 204
assert person.date_created == today
def test_deserializing_datetime(self):
"""Test for deserializing a JSON representation of a date field."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
now = datetime.now()
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'birth_datetime': now
}
}
}
# Python's built-in JSON encoder doesn't serialize date/time objects by
# default.
data = dumps(data, cls=JSONEncoder)
response = self.app.patch('/api/person/1', data=data)
assert response.status_code == 204
assert person.birth_datetime == now
def test_correct_content_type(self):
"""Tests that the server responds with :http:status:`201` if the
request has the correct JSON API content type.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=dict(type='person', id='1'))
response = self.app.patch('/api/person/1', data=dumps(data),
content_type=JSONAPI_MIMETYPE)
assert response.status_code == 204
assert response.headers['Content-Type'] == JSONAPI_MIMETYPE
def test_no_content_type(self):
"""Tests that the server responds with :http:status:`415` if the
request has no content type.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=dict(type='person', id='1'))
response = self.app.patch('/api/person/1', data=dumps(data),
content_type=None)
assert response.status_code == 415
assert response.headers['Content-Type'] == JSONAPI_MIMETYPE
def test_msie8(self):
"""Tests for compatibility with Microsoft Internet Explorer 8.
According to issue #267, making requests using JavaScript from MSIE8
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
headers = {'User-Agent': MSIE8_UA}
content_type = 'text/html'
data = dict(data=dict(type='person', id='1'))
response = self.app.patch('/api/person/1', data=dumps(data),
headers=headers, content_type=content_type)
assert response.status_code == 204
def test_msie9(self):
"""Tests for compatibility with Microsoft Internet Explorer 9.
According to issue #267, making requests using JavaScript from MSIE9
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
headers = {'User-Agent': MSIE9_UA}
content_type = 'text/html'
data = dict(data=dict(type='person', id='1'))
response = self.app.patch('/api/person/1', data=dumps(data),
headers=headers, content_type=content_type)
assert response.status_code == 204
def test_rollback_on_integrity_error(self):
"""Tests that an integrity error in the database causes a session
rollback, and that the server can still process requests correctly
after this rollback.
"""
person1 = self.Person(id=1, name=u'foo')
person2 = self.Person(id=2, name=u'bar')
self.session.add_all([person1, person2])
self.session.commit()
data = {
'data': {
'type': 'person',
'id': '2',
'attributes': {
'name': u'foo'
}
}
}
response = self.app.patch('/api/person/2', data=dumps(data))
assert response.status_code == 409 # Conflict
assert self.session.is_active, 'Session is in `partial rollback` state'
data = {
'data': {
'type': 'person',
'id': '2',
'attributes': {
'name': 'baz'
}
}
}
response = self.app.patch('/api/person/2', data=dumps(data))
assert response.status_code == 204
assert person2.name == 'baz'
def test_empty_request(self):
"""Test for making a :http:method:`patch` request with no data."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.patch('/api/person/1')
assert response.status_code == 400
# TODO check the error message here
def test_empty_string(self):
"""Test for making a :http:method:`patch` request with an empty string,
which is invalid JSON.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.patch('/api/person/1', data='')
assert response.status_code == 400
# TODO check the error message here
def test_invalid_json(self):
"""Tests that a request with invalid JSON yields an error response."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.patch('/api/person/1', data='Invalid JSON string')
assert response.status_code == 400
# TODO check error message here
def test_nonexistent_attribute(self):
"""Tests that attempting to make a :http:method:`patch` request on an
attribute that does not exist on the specified model yields an error
response.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'bogus': 0
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert 400 == response.status_code
def test_read_only_hybrid_property(self):
"""Tests that an attempt to set a read-only hybrid property causes an
error.
For more information, see issue #171.
"""
interval = self.Interval(id=1, start=5, end=10)
self.session.add(interval)
self.session.commit()
data = {
'data': {
'type': 'interval',
'id': '1',
'attributes': {
'radius': 1
}
}
}
response = self.app.patch('/api/interval/1', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
def test_set_hybrid_property(self):
"""Tests that a hybrid property can be correctly set by a client."""
interval = self.Interval(id=1, start=5, end=10)
self.session.add(interval)
self.session.commit()
data = {
'data': {
'type': 'interval',
'id': '1',
'attributes': {
'length': 4
}
}
}
response = self.app.patch('/api/interval/1', data=dumps(data))
assert response.status_code == 204
assert interval.start == 5
assert interval.end == 9
assert interval.radius == 2
def test_collection_name(self):
"""Tests for updating a resource with an alternate collection name."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
collection_name='people')
data = {
'data': {
'type': 'people',
'id': '1',
'attributes': {
'name': u'foo'
}
}
}
response = self.app.patch('/api/people/1', data=dumps(data))
assert response.status_code == 204
assert person.name == u'foo'
def test_different_endpoints(self):
"""Tests for updating the same resource from different endpoints."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2')
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'name': u'foo'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 204
assert person.name == u'foo'
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
assert response.status_code == 204
assert person.name == 'bar'
# TODO This is not required by JSON API, and it was a little bit flimsy
# anyway.
#
# def test_patch_update_relations(self):
# """Test for posting a new model and simultaneously adding related
# instances *and* updating information on those instances.
# For more information see issue #164.
# """
# # First, create a new computer object with an empty `name` field and
# # a new person with no related computers.
# response = self.app.post('/api/computer', data=dumps({}))
# assert 201 == response.status_code
# response = self.app.post('/api/person', data=dumps({}))
# assert 201 == response.status_code
# # Second, patch the person by setting its list of related computer
# # instances to include the previously created computer, *and*
# # simultaneously update the `name` attribute of that computer.
# data = dict(computers=[dict(id=1, name='foo')])
# response = self.app.patch('/api/person/1', data=dumps(data))
# assert 200 == response.status_code
# # Check that the computer now has its `name` field set.
# response = self.app.get('/api/computer/1')
# assert 200 == response.status_code
# assert 'foo' == loads(response.data)['name']
# # Add a new computer by patching person
# data = {'computers': [{'id': 1},
# {'name': 'iMac', 'vendor': 'Apple',
# 'programs': [{'program':{'name':'iPhoto'}}]}]}
# response = self.app.patch('/api/person/1', data=dumps(data))
# assert 200 == response.status_code
# response = self.app.get('/api/computer/2/programs')
# programs = loads(response.data)['objects']
# assert programs[0]['program']['name'] == 'iPhoto'
# # Add a program to the computer through the person
# data = {'computers': [{'id': 1},
# {'id': 2,
# 'programs': [{'program_id': 1},
# {'program':{'name':'iMovie'}}]}]}
# response = self.app.patch('/api/person/1', data=dumps(data))
# assert 200 == response.status_code
# response = self.app.get('/api/computer/2/programs')
# programs = loads(response.data)['objects']
# assert programs[1]['program']['name'] == 'iMovie'
# TODO this is not required by the JSON API spec.
#
# def test_put_same_as_patch(self):
# """Tests that :http:method:`put` requests are the same as
# :http:method:`patch` requests.
# """
# # recreate the api to allow patch many at /api/v2/person
# self.manager.create_api(self.Person, methods=['GET', 'POST', 'PUT'],
# allow_patch_many=True, url_prefix='/api/v2')
# # Creating some people
# self.app.post('/api/v2/person',
# data=dumps({'name': u'Lincoln', 'age': 23}))
# self.app.post('/api/v2/person',
# data=dumps({'name': u'Lucy', 'age': 23}))
# self.app.post('/api/v2/person',
# data=dumps({'name': u'Mary', 'age': 25}))
# # change a single entry
# resp = self.app.put('/api/v2/person/1', data=dumps({'age': 24}))
# assert resp.status_code == 200
# resp = self.app.get('/api/v2/person/1')
# assert resp.status_code == 200
# assert loads(resp.data)['age'] == 24
# # Changing the birth date field of the entire collection
# day, month, year = 15, 9, 1986
# birth_date = date(year, month, day).strftime('%d/%m/%Y') # iso8601
# form = {'birth_date': birth_date}
# self.app.put('/api/v2/person', data=dumps(form))
# # Finally, testing if the change was made
# response = self.app.get('/api/v2/person')
# loaded = loads(response.data)['objects']
# for i in loaded:
# expected = '{0:4d}-{1:02d}-{2:02d}'.format(year, month, day)
# assert i['birth_date'] == expected
# TODO no longer supported
#
# def test_patch_autodelete_submodel(self):
# """Tests the automatic deletion of entries marked with the
# ``__delete__`` flag on an update operation.
# It also tests adding an already created instance as a related item.
# """
# # Creating all rows needed in our test
# person_data = {'name': u'Lincoln', 'age': 23}
# resp = self.app.post('/api/person', data=dumps(person_data))
# assert resp.status_code == 201
# comp_data = {'name': u'lixeiro', 'vendor': u'Lemote'}
# resp = self.app.post('/api/computer', data=dumps(comp_data))
# assert resp.status_code == 201
# # updating person to add the computer
# update_data = {'computers': {'add': [{'id': 1}]}}
# self.app.patch('/api/person/1', data=dumps(update_data))
# # Making sure that everything worked properly
# resp = self.app.get('/api/person/1')
# assert resp.status_code == 200
# loaded = loads(resp.data)
# assert len(loaded['computers']) == 1
# assert loaded['computers'][0]['name'] == u'lixeiro'
# # Now, let's remove it and delete it
# update2_data = {
# 'computers': {
# 'remove': [
# {'id': 1, '__delete__': True},
# ],
# },
# }
# resp = self.app.patch('/api/person/1', data=dumps(update2_data))
# assert resp.status_code == 200
# # Testing to make sure it was removed from the related field
# resp = self.app.get('/api/person/1')
# assert resp.status_code == 200
# loaded = loads(resp.data)
# assert len(loaded['computers']) == 0
# # Making sure it was removed from the database
# resp = self.app.get('/api/computer/1')
# assert resp.status_code == 404
def test_to_one_related_resource_url(self):
"""Tests that attempting to update a to-one related resource URL
(instead of a relationship URL) yields an error response.
"""
article = self.Article(id=1)
person = self.Person(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(id=1, type='person'))
response = self.app.patch('/api/article/1/author', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_to_many_related_resource_url(self):
"""Tests that attempting to update a to-many related resource URL
(instead of a relationship URL) yields an error response.
"""
article = self.Article(id=1)
person = self.Person(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.patch('/api/person/1/articles', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_to_many_null(self):
"""Tests that attempting to set a to-many relationship to null
yields an error response.
The JSON API protocol requires that a to-many relationship can
only be updated (if allowed) with a list.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, url_prefix='/api2',
methods=['PATCH'],
allow_to_many_replacement=True)
data = {
'data': {
'type': 'person',
'id': '1',
'relationships': {
'articles': {
'data': None
}
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
check_sole_error(response, 400, ['articles', 'data', 'empty list'])
def test_missing_type(self):
"""Tests that attempting to update a resource without providing a
resource type yields an error.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
data = {
'data': {
'id': '1',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
assert person.name == u'foo'
def test_missing_id(self):
"""Tests that attempting to update a resource without providing an ID
yields an error.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'person',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
assert person.name == u'foo'
def test_nonexistent_to_one_link(self):
"""Tests that an attempt to update a to-one relationship with a
resource that doesn't exist yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
'relationships': {
'author': {
'data': {
'type': 'person',
'id': '1'
}
}
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
check_sole_error(response, 404, ['found', 'person', '1'])
def test_conflicting_type_to_one_link(self):
"""Tests that an attempt to update a to-one relationship with a linkage
object whose type does not match the expected resource type yields an
error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
'relationships': {
'author': {
'data': {
'type': 'bogus',
'id': '1'
}
}
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
assert response.status_code == 409
# TODO check error message here
def test_conflicting_type_to_many_link(self):
"""Tests that an attempt to update a to-many relationship with a
linkage object whose type does not match the expected resource type
yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_to_many_replacement=True)
data = {
'data': {
'type': 'person',
'id': '1',
'relationships': {
'articles': {
'data': [
{'type': 'bogus', 'id': '1'}
]
}
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
assert response.status_code == 409
# TODO check error message here
def test_relationship_empty_object(self):
"""Tests for an error response on a missing ``'data'`` key in a
relationship object.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
'relationships': {
'author': {}
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
def test_relationship_missing_object(self):
"""Tests that a request document missing a relationship object
causes an error response.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = {
'data': {
'id': '1',
'type': 'article',
'relationships': {
'author': None
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
check_sole_error(response, 400, ['missing', 'relationship object',
'author'])
# Check that the article was not updated to None.
assert article.author is person
def test_serialization_exception(self):
"""Tests that serialization exceptions are caught when
responding with content.
A representation of the modified resource is returned to the
client when an update causes additional changes in the resource
in ways other than those specified by the client.
"""
tag = self.Tag(id=1)
self.session.add(tag)
self.session.commit()
self.manager.create_api(self.Tag, methods=['PATCH'],
serializer_class=raise_exception)
data = {
'data': {
'type': 'tag',
'id': '1',
'attributes': {
'name': u'foo'
}
}
}
response = self.app.patch('/api/tag/1', data=dumps(data))
check_sole_error(response, 500, ['Failed to serialize', 'type', 'tag',
'ID', '1'])
def test_dont_assign_to_method(self):
"""Tests that if a certain method is to be included in a
resource, that method is not assigned to when updating the
resource.
For more information, see issue #253.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, additional_attributes=['foo'],
url_prefix='/api2', methods=['PATCH'])
data = {
'data': {
'type': 'person',
'id': '1',
'attributes': {
'foo': u'bar'
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
check_sole_error(response, 400, ['does not have', 'field', 'foo'])
assert person.foo != u'bar'
assert person.foo() == u'foo'
def test_special_field_names(self):
"""Test that an attribute can have the name "type".
For more information, see issue #559.
"""
article = self.Article(id=1, type=u'foo')
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
'attributes': {
'type': u'bar'
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
assert response.status_code == 204
assert article.type == u'bar'
def test_integer_id_error_message(self):
"""Test that an integer ID in the JSON request yields an error.
For more information, see GitHub issue #534.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'person',
'id': 1,
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
check_sole_error(response, 409, ['"id" element', 'resource object',
'must be a JSON string'])
class TestProcessors(ManagerTestBase):
"""Tests for pre- and postprocessors."""
def setUp(self):
super(TestProcessors, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Person = Person
self.Base.metadata.create_all()
def test_change_id(self):
"""Tests that a return value from a preprocessor overrides the ID of
the resource to fetch as given in the request URL.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
def increment_id(resource_id=None, **kw):
if resource_id is None:
raise ProcessingException
return str(int(resource_id) + 1)
preprocessors = dict(PATCH_RESOURCE=[increment_id])
self.manager.create_api(self.Person, methods=['PATCH'],
preprocessors=preprocessors)
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'name': u'foo'
}
}
}
response = self.app.patch('/api/person/0', data=dumps(data))
assert response.status_code == 204
assert person.name == u'foo'
def test_single_resource_processing_exception(self):
"""Tests for a preprocessor that raises a :exc:`ProcessingException`
when updating a single resource.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
def forbidden(**kw):
raise ProcessingException(status=403, detail='forbidden')
preprocessors = dict(PATCH_RESOURCE=[forbidden])
self.manager.create_api(self.Person, methods=['PATCH'],
preprocessors=preprocessors)
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 403
document = loads(response.data)
errors = document['errors']
assert len(errors) == 1
error = errors[0]
assert 'forbidden' == error['detail']
assert person.name == u'foo'
def test_single_resource(self):
"""Tests :http:method:`patch` requests for a single resource with a
preprocessor function.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
def set_name(data=None, **kw):
"""Sets the name attribute of the incoming data object, regardless
of the value requested by the client.
"""
if data is not None:
data['data']['attributes']['name'] = u'bar'
preprocessors = dict(PATCH_RESOURCE=[set_name])
self.manager.create_api(self.Person, methods=['PATCH'],
preprocessors=preprocessors)
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'name': u'baz'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 204
assert person.name == 'bar'
def test_postprocessor(self):
"""Tests that a request to update a resource invokes a postprocessor.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
temp = []
def modify_result(result=None, **kw):
temp.append('baz')
postprocessors = dict(PATCH_RESOURCE=[modify_result])
self.manager.create_api(self.Person, methods=['PATCH'],
postprocessors=postprocessors)
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 204
assert person.name == 'bar'
assert temp == ['baz']
def test_postprocessor_no_commit_on_error(self):
"""Tests that a processing exception causes the session to be
flushed but not committed.
"""
def raise_error(**kw):
raise ProcessingException(status=500)
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
postprocessors = dict(PATCH_RESOURCE=[raise_error])
self.manager.create_api(self.Person, methods=['PATCH'],
postprocessors=postprocessors)
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 500
assert person.name == u'bar'
self.session.rollback()
assert person.name == u'foo'
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
"""Tests for updating resources defined as Flask-SQLAlchemy models instead
of pure SQLAlchemy models.
"""
def setUp(self):
"""Creates the Flask-SQLAlchemy database and models."""
super(TestFlaskSQLAlchemy, self).setUp()
# HACK During testing, we don't want the session to expire, so that we
# can access attributes of model instances *after* a request has been
# made (that is, after Flask-Restless does its work and commits the
# session).
session_options = dict(expire_on_commit=False)
# Overwrite the `db` and `session` attributes from the superclass.
self.db = SQLAlchemy(self.flaskapp, session_options=session_options)
self.session = self.db.session
class Person(self.db.Model):
id = self.db.Column(self.db.Integer, primary_key=True)
name = self.db.Column(self.db.Unicode)
self.Person = Person
self.db.create_all()
self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
self.manager.create_api(self.Person, methods=['PATCH'])
def test_create(self):
"""Tests for creating a resource."""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'name': u'bar'
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 204
assert person.name == 'bar'
| 41,634
|
Python
|
.py
| 1,041
| 29.353506
| 79
| 0.546425
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,648
|
test_server_responsibilities.py
|
jfinkels_flask-restless/tests/test_server_responsibilities.py
|
# test_server_responsibilities.py - tests JSON API server responsibilities
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Tests for server-side content negotiation responsibilities."""
from sqlalchemy import Column
from sqlalchemy import Integer
from .helpers import loads
from .helpers import ManagerTestBase
class TestServerResponsibilities(ManagerTestBase):
"""Tests for server-side content negotiation responsibilities."""
def setUp(self):
super(TestServerResponsibilities, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Person)
def test_accept_star_star(self):
""""Test for the Accept: */* header.
For more information, see GitHub issue #548.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
headers = {'Accept': '*/*'}
response = self.app.get('/api/person/1', headers=headers)
self.assertEqual(response.status_code, 200)
document = loads(response.data)
person = document['data']
self.assertEqual(person['id'], '1')
self.assertEqual(person['type'], 'person')
def test_no_duplicate_headers(self):
"""Test that each header appears only once in the response.
For more information, see GitHub issue #479.
"""
response = self.app.get('/api/person')
self.assertIn('Content-Type', response.headers)
self.assertIn('Link', response.headers)
headers_list = response.headers.to_wsgi_list()
# TODO In Python 2.7+, this should be a set comprehension.
headers_set = set(k for k, v in headers_list)
self.assertEqual(len(headers_list), len(headers_set))
def test_jsonp_content_type(self):
"""Test that the Content-Type for JSONP is application/javascript."""
response = self.app.get('/api/person?callback=foo')
self.assertEqual(response.content_type, 'application/javascript')
def test_jsonp_one_content_type(self):
"""Test that a JSONP response has only one Content-Type header.
For more information, see GitHub issue #479.
"""
response = self.app.get('/api/person?callback=foo')
headers_list = response.headers.to_wsgi_list()
# TODO In Python 2.7+, this should be a set comprehension.
headers_set = set(k for k, v in headers_list)
self.assertEqual(len(headers_list), len(headers_set))
| 2,980
|
Python
|
.py
| 64
| 39.6875
| 77
| 0.68
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,649
|
test_metadata.py
|
jfinkels_flask-restless/tests/test_metadata.py
|
# test_metadata.py - unit tests for response metadata
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for metadata in server responses."""
from unittest2 import skip
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from flask_restless import JSONAPI_MIMETYPE
from .helpers import loads
from .helpers import ManagerTestBase
class TestMetadata(ManagerTestBase):
"""Tests for receiving metadata in responses."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`.
"""
super(TestMetadata, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Person = Person
self.Base.metadata.create_all()
def test_total(self):
"""Tests that a request for (a subset of) all instances of a model
includes the total number of results as part of the JSON response.
"""
people = [self.Person() for n in range(15)]
self.session.add_all(people)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person')
document = loads(response.data)
assert document['meta']['total'] == 15
@skip('Not sure whether this should be implemented')
def test_http_headers(self):
"""Tests that HTTP headers appear as elements in the JSON metadata."""
self.manager.create_api(self.Person)
response = self.app.get('/api/person')
document = loads(response.data)
meta = document['meta']
assert meta['Content-Type'] == JSONAPI_MIMETYPE
def test_model_info(self):
"""Test for getting schema metadata.
For more information, see GitHub issue #625.
"""
self.manager.create_api(self.Person)
response = self.app.get('/api')
document = loads(response.data)
info = document['meta']['modelinfo']
self.assertEqual(list(info.keys()), ['person'])
self.assertEqual(sorted(info['person']), ['primarykey', 'url'])
self.assertEqual(info['person']['primarykey'], 'id')
self.assertTrue(info['person']['url'].endswith('/api/person'))
def test_model_info_custom_primary_key(self):
"""Test for getting schema metadata with custom primary key.
For more information, see GitHub issue #625.
"""
self.manager.create_api(self.Person, primary_key='name')
response = self.app.get('/api')
document = loads(response.data)
info = document['meta']['modelinfo']
self.assertEqual(info['person']['primarykey'], 'name')
| 3,261
|
Python
|
.py
| 73
| 37.835616
| 78
| 0.670662
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,650
|
test_serialization.py
|
jfinkels_flask-restless/tests/test_serialization.py
|
# test_serialization.py - unit tests for serializing resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for serializing resources.
This module complements the tests in :mod:`test_fetching` module; tests
in this class should still be testing the behavior of Flask-Restless by
making requests to endpoints created by :meth:`APIManager.create_api`,
not by calling the serialization functions directly. This helps keep the
testing code decoupled from the serialization implementation.
"""
from datetime import datetime
from datetime import time
from datetime import timedelta
from unittest2 import skipUnless
from uuid import UUID
from uuid import uuid1
import warnings
try:
# HACK The future package uses code that is pending deprecation in
# Python 3.4 or later. We catch the warning here so that the test
# suite does not complain about it.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=PendingDeprecationWarning)
from future.standard_library import install_aliases
install_aliases()
except ImportError:
is_future_available = False
else:
is_future_available = True
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Interval
from sqlalchemy import Time
from sqlalchemy import TypeDecorator
from sqlalchemy import Unicode
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from flask_restless import DefaultSerializer
from flask_restless import MultipleExceptions
from flask_restless import SerializationException
from .helpers import check_sole_error
from .helpers import GUID
from .helpers import loads
from .helpers import ManagerTestBase
from .helpers import raise_s_exception as raise_exception
class DecoratedDateTime(TypeDecorator):
impl = DateTime
class DecoratedInterval(TypeDecorator):
impl = Interval
class TestFetchCollection(ManagerTestBase):
"""Tests for serializing when fetching from a collection endpoint."""
def setUp(self):
super(TestFetchCollection, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Person = Person
self.Base.metadata.create_all()
def test_custom_serializer(self):
"""Tests for a custom serializer for serializing many resources.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
class MySerializer(DefaultSerializer):
def serialize_many(self, *args, **kw):
result = super(MySerializer, self).serialize_many(*args, **kw)
for resource in result['data']:
if 'attributes' not in resource:
resource['attributes'] = {}
resource['attributes']['foo'] = resource['id']
return result
self.manager.create_api(self.Person, serializer_class=MySerializer)
response = self.app.get('/api/person')
document = loads(response.data)
people = document['data']
attributes = sorted(person['attributes']['foo'] for person in people)
assert ['1', '2'] == attributes
def test_multiple_exceptions(self):
"""Tests that multiple exceptions are caught when serializing
many instances.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
class raise_exceptions(DefaultSerializer):
def serialize_many(self, instances, *args, **kw):
instance1, instance2 = instances[:2]
exception1 = SerializationException(instance1, message='foo')
exception2 = SerializationException(instance2, message='bar')
exceptions = [exception1, exception2]
raise MultipleExceptions(exceptions)
self.manager.create_api(self.Person, serializer_class=raise_exceptions)
response = self.app.get('/api/person')
document = loads(response.data)
assert response.status_code == 500
errors = document['errors']
assert len(errors) == 2
error1, error2 = errors
detail1 = error1['detail']
assert 'foo' in detail1
detail2 = error2['detail']
assert 'bar' in detail2
def test_multiple_exceptions_from_dump(self):
"""Tests that multiple exceptions are caught from the
:meth:`DefaultSerializer._dump` method when serializing many
instances.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
class raise_exceptions(DefaultSerializer):
def _dump(self, instance, *args, **kw):
message = 'failed on {0}'.format(instance.id)
raise SerializationException(instance, message=message)
self.manager.create_api(self.Person, serializer_class=raise_exceptions)
response = self.app.get('/api/person')
document = loads(response.data)
assert response.status_code == 500
errors = document['errors']
assert len(errors) == 2
error1, error2 = errors
detail1 = error1['detail']
detail2 = error2['detail']
# There is no guarantee on the order in which the error objects
# are supplied in the response, so we check which is which.
if '1' not in detail1:
detail1, detail2 = detail2, detail1
assert u'failed on 1' in detail1
assert u'failed on 2' in detail2
def test_exception_single(self):
"""Tests for a serialization exception on a filtered single
response.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, serializer_class=raise_exception)
query_string = {'filter[single]': 1}
response = self.app.get('/api/person', query_string=query_string)
check_sole_error(response, 500, ['Failed to serialize', 'type',
'person', 'ID', '1'])
class TestFetchResource(ManagerTestBase):
"""Tests for serializing when fetching from a resource endpoint."""
def setUp(self):
super(TestFetchResource, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
uuid = Column(GUID)
name = Column(Unicode)
birthday = Column(Date)
bedtime = Column(Time)
birth_datetime = Column(DateTime)
decorated_datetime = Column(DecoratedDateTime)
decorated_interval = Column(DecoratedInterval)
# These class attributes are *not* columns, just hard-coded values.
uuid_attribute = UUID(hex='f' * 32)
datetime_attribute = datetime(1, 1, 1)
@hybrid_property
def has_early_bedtime(self):
if not hasattr(self, 'bedtime') or self.bedtime is None:
return False
nine_oclock = time(21)
return self.bedtime < nine_oclock
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('comments'))
article_id = Column(Integer, ForeignKey('article.id'))
article = relationship('Article', backref=backref('comments'))
class Tag(self.Base):
__tablename__ = 'tag'
tagid = Column(Integer, primary_key=True)
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Tag = Tag
self.Base.metadata.create_all()
def test_hybrid_property(self):
"""Tests for fetching a resource with a hybrid property attribute."""
person1 = self.Person(id=1, bedtime=time(20))
person2 = self.Person(id=2, bedtime=time(22))
self.session.add_all([person1, person2])
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert person['attributes']['has_early_bedtime']
response = self.app.get('/api/person/2')
document = loads(response.data)
person = document['data']
assert not person['attributes']['has_early_bedtime']
def test_uuid(self):
"""Tests for serializing a (non-primary key) UUID field."""
uuid = uuid1()
person = self.Person(id=1, uuid=uuid)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['attributes']['uuid'] == str(uuid)
def test_uuid_as_additional_attribute(self):
"""Tests that a UUID is serialized as a string when it is an
attribute of the model but *not* a SQLAlchemy column.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person,
additional_attributes=['uuid_attribute'])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
attributes = person['attributes']
assert attributes['uuid_attribute'] == str(self.Person.uuid_attribute)
def test_time(self):
"""Test for getting the JSON representation of a time field."""
now = datetime.now().time()
person = self.Person(id=1, bedtime=now)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['attributes']['bedtime'] == now.isoformat()
def test_datetime(self):
"""Test for getting the JSON representation of a datetime field."""
now = datetime.now()
person = self.Person(id=1, birth_datetime=now)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['attributes']['birth_datetime'] == now.isoformat()
def test_datetime_as_additional_attribute(self):
"""Tests that a datetime is serialized as a string when it is an
attribute of the model but *not* a SQLAlchemy column.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person,
additional_attributes=['datetime_attribute'])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
attributes = person['attributes']
expected = self.Person.datetime_attribute
assert attributes['datetime_attribute'] == expected.isoformat()
def test_date(self):
"""Test for getting the JSON representation of a date field."""
now = datetime.now().date()
person = self.Person(id=1, birthday=now)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['attributes']['birthday'] == now.isoformat()
def test_type_decorator_datetime(self):
"""Tests for serializing "subtypes" of the SQLAlchemy
:class:`sqlalchemy.DateTime` class.
"""
now = datetime.now()
person = self.Person(id=1, decorated_datetime=now)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['attributes']['decorated_datetime'] == now.isoformat()
def test_type_decorator_interval(self):
"""Tests for serializing "subtypes" of the SQLAlchemy
:class:`sqlalchemy.Interval` class.
"""
# This timedelta object represents an interval of ten seconds.
interval = timedelta(0, 10)
person = self.Person(id=1, decorated_interval=interval)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['attributes']['decorated_interval'] == 10
def test_custom_serialize(self):
"""Tests for a custom serialization function."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
class MySerializer(DefaultSerializer):
def serialize(self, *args, **kw):
result = super(MySerializer, self).serialize(*args, **kw)
result['data']['attributes']['foo'] = 'bar'
return result
self.manager.create_api(self.Person, serializer_class=MySerializer)
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert person['attributes']['foo'] == 'bar'
def test_per_model_serializer_on_included(self):
"""Tests that a response that includes resources of multiple
types respects the model-specific serializers provided to the
:meth:`APIManager.create_api` method when called with different
model classes.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
class MySerializer(DefaultSerializer):
secret = None
def serialize(self, *args, **kw):
result = super(MySerializer, self).serialize(*args, **kw)
if 'attributes' not in result['data']:
result['data']['attributes'] = {}
result['data']['attributes'][self.secret] = self.secret
return result
class FooSerializer(MySerializer):
secret = 'foo'
class BarSerializer(MySerializer):
secret = 'bar'
self.manager.create_api(self.Person, serializer_class=FooSerializer)
self.manager.create_api(self.Article, serializer_class=BarSerializer)
query_string = {'include': 'author'}
response = self.app.get('/api/article/1', query_string=query_string)
document = loads(response.data)
# First, the article resource should have an extra 'bar' attribute.
article = document['data']
assert article['attributes']['bar'] == 'bar'
assert 'foo' not in article['attributes']
# Second, there should be a single included resource, a person
# with a 'foo' attribute.
included = document['included']
assert len(included) == 1
author = included[0]
assert author['attributes']['foo'] == 'foo'
assert 'bar' not in author['attributes']
def test_exception(self):
"""Tests that exceptions are caught when a custom serialization method
raises an exception.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, serializer_class=raise_exception)
response = self.app.get('/api/person/1')
check_sole_error(response, 500, ['Failed to serialize', 'type',
'person', 'ID', '1'])
def test_exception_on_included(self):
"""Tests that exceptions are caught when a custom serialization method
raises an exception when serializing an included resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
self.manager.create_api(self.Person)
self.manager.create_api(self.Article, serializer_class=raise_exception)
query_string = {'include': 'articles'}
response = self.app.get('/api/person/1', query_string=query_string)
check_sole_error(response, 500, ['Failed to serialize', 'type',
'article', 'ID', '1'])
def test_multiple_exceptions_on_included(self):
"""Tests that multiple serialization exceptions are caught when
a custom serialization method raises an exception when
serializing an included resource.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
article1.author = person1
article2.author = person2
self.session.add_all([article1, article2, person1, person2])
self.session.commit()
self.manager.create_api(self.Article)
self.manager.create_api(self.Person, serializer_class=raise_exception)
query_string = {'include': 'author'}
response = self.app.get('/api/article', query_string=query_string)
assert response.status_code == 500
document = loads(response.data)
errors = document['errors']
assert len(errors) == 2
error1, error2 = errors
assert error1['status'] == 500
assert error2['status'] == 500
assert 'Failed to serialize included resource' in error1['detail']
assert 'Failed to serialize included resource' in error2['detail']
assert 'ID 1' in error1['detail'] or 'ID 1' in error2['detail']
assert 'ID 2' in error1['detail'] or 'ID 2' in error2['detail']
def test_circular_includes(self):
"""Tests that circular includes are only included once."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
comment1.article = article1
comment2.article = article2
comment1.author = person1
comment2.author = person2
article1.author = person1
article2.author = person1
resources = [article1, article2, comment1, comment2, person1, person2]
self.session.add_all(resources)
self.session.commit()
self.manager.create_api(self.Article)
self.manager.create_api(self.Comment)
self.manager.create_api(self.Person)
# The response to this request should include person1 once (for
# the first 'author') and person 2 once (for the last 'author').
query_string = {'include': 'author.articles.comments.author'}
response = self.app.get('/api/comment/1', query_string=query_string)
document = loads(response.data)
included = document['included']
# Sort the included resources, first by type, then by ID.
resources = sorted(included, key=lambda x: (x['type'], x['id']))
resource_types = [resource['type'] for resource in resources]
resource_ids = [resource['id'] for resource in resources]
# We expect two articles, two persons, and one comment (since
# the other comment is the primary data in the response
# document).
expected_types = ['article', 'article', 'comment', 'person', 'person']
expected_ids = ['1', '2', '2', '1', '2']
assert expected_types == resource_types
assert expected_ids == resource_ids
def test_exception_message(self):
"""Tests that a message specified in the
:exc:`~flask_restless.SerializationException` constructor
appears in an error response.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
class raise_with_msg(DefaultSerializer):
def serialize(self, instance, *args, **kw):
raise SerializationException(instance, message='foo')
self.manager.create_api(self.Person, serializer_class=raise_with_msg)
response = self.app.get('/api/person/1')
check_sole_error(response, 500, ['foo'])
def test_non_id_primary_key(self):
"""Test for a primary key field that is not named "id".
For more information, see issue #540.
"""
tag = self.Tag(tagid=1)
self.session.add(tag)
self.session.commit()
self.manager.create_api(self.Tag)
response = self.app.get('/api/tag/1')
document = loads(response.data)
tag = document['data']
self.assertEqual(tag['id'], '1')
self.assertEqual(tag['type'], 'tag')
self.assertEqual(tag['attributes']['tagid'], 1)
@skipUnless(is_future_available, 'required "future" library')
def test_unicode_self_link(self):
"""Test that serializing the "self" link handles unicode on Python 2.
This is a specific test for code using the :mod:`future` library.
For more information, see GitHub issue #594.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
self.app.get('/api/person/1')
class TestFetchRelation(ManagerTestBase):
def setUp(self):
super(TestFetchRelation, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_exception_to_many(self):
"""Tests that exceptions are caught when a custom serialization method
raises an exception on a to-many relation.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Person)
self.manager.create_api(self.Article, serializer_class=raise_exception)
response = self.app.get('/api/person/1/articles')
check_sole_error(response, 500, ['Failed to serialize', 'type',
'article', 'ID', '1'])
def test_exception_to_one(self):
"""Tests that exceptions are caught when a custom serialization method
raises an exception on a to-one relation.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Person, serializer_class=raise_exception)
self.manager.create_api(self.Article)
response = self.app.get('/api/article/1/author')
check_sole_error(response, 500, ['Failed to serialize', 'type',
'person', 'ID', '1'])
def test_exception_on_included(self):
"""Tests that exceptions are caught when a custom serialization method
raises an exception when serializing an included resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
self.manager.create_api(self.Person, serializer_class=raise_exception)
self.manager.create_api(self.Article)
params = {'include': 'author'}
response = self.app.get('/api/person/1/articles', query_string=params)
assert response.status_code == 500
check_sole_error(response, 500, ['Failed to serialize',
'included resource', 'type', 'person',
'ID', '1'])
class TestFetchRelatedResource(ManagerTestBase):
"""Tests for serializing when fetching from a related resource endpoint."""
def setUp(self):
super(TestFetchRelatedResource, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
def test_exception(self):
"""Tests that serialization exceptions are caught when fetching
a related resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Person)
self.manager.create_api(self.Article, serializer_class=raise_exception)
response = self.app.get('/api/person/1/articles/1')
check_sole_error(response, 500, ['Failed to serialize', 'type',
'article', 'ID', '1'])
def test_exception_on_included(self):
"""Tests that serialization exceptions are caught for included
resource on a request to fetch a related resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
self.manager.create_api(self.Person, serializer_class=raise_exception)
self.manager.create_api(self.Article)
query_string = {'include': 'author'}
response = self.app.get('/api/person/1/articles/1',
query_string=query_string)
check_sole_error(response, 500, ['Failed to serialize',
'included resource', 'type', 'person',
'ID', '1'])
| 28,153
|
Python
|
.py
| 612
| 36.410131
| 79
| 0.633279
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,651
|
__init__.py
|
jfinkels_flask-restless/tests/__init__.py
|
# __init__.py - indicates that this directory is a Python package
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for Flask-Restless.
The :mod:`test_jsonapi` package contains explicit tests for nearly all
of the requirements of the JSON API specification. The modules
:mod:`test_bulk` and :mod:`test_jsonpatch` test the default JSON API
extensions. Other modules such as :mod:`test_fetching` and
:mod:`test_updating` test features specific to the JSON API
implementation provided by Flask-Restless, as well as additional
features not discussed in the specification.
Run the full test suite from the command-line using ``nosetests`` (or
``python setup.py test``).
"""
import sys
import warnings
# Convert Python warnings into errors on tests, but only if Python
# version 2.7 or greater; on Python 2.6, unittest2 gives a
# RuntimeWarning when trying to skip a test.
if sys.version_info >= (2, 7):
warnings.simplefilter('error')
| 1,311
|
Python
|
.py
| 29
| 43.931034
| 72
| 0.776995
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,652
|
test_fetching.py
|
jfinkels_flask-restless/tests/test_fetching.py
|
# test_fetching.py - unit tests for fetching resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for fetching resources from endpoints generated by
Flask-Restless.
This module includes tests for additional functionality that is not
already tested by :mod:`test_jsonapi`, the package that guarantees
Flask-Restless meets the minimum requirements of the JSON API
specification.
"""
from itertools import product
from operator import itemgetter
from unittest2 import skip
# In Python 3...
try:
from urllib.parse import unquote
# In Python 2...
except ImportError:
from urlparse import unquote
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import select
from sqlalchemy import Unicode
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from flask_restless import APIManager
from flask_restless import DefaultSerializer
from flask_restless import ProcessingException
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import FlaskSQLAlchemyTestBase
from .helpers import loads
from .helpers import MSIE8_UA
from .helpers import MSIE9_UA
from .helpers import ManagerTestBase
class TestFetchCollection(ManagerTestBase):
def setUp(self):
super(TestFetchCollection, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
age = Column(Integer)
name = Column(Unicode)
@hybrid_property
def is_minor(self):
if not hasattr(self, 'age') or self.age is None:
return False
return self.age <= 18
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
comments = relationship('Comment')
@hybrid_property
def num_comments(self):
return len(self.comments)
@num_comments.expression
def num_comments(cls):
return select([func.count(self.Comment.id)]).\
where(self.Comment.article_id == cls.id).\
label('numcomments')
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
article_id = Column(Integer, ForeignKey(Article.id))
@classmethod
def query(cls):
return self.session.query(cls).filter(cls.id < 2)
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
self.manager.create_api(Comment)
def test_wrong_accept_header(self):
"""Tests that if a client specifies only :http:header:`Accept`
headers with non-JSON API media types, then the server responds
with a :http:status:`406`.
"""
headers = {'Accept': 'application/json'}
response = self.app.get('/api/person', headers=headers)
assert response.status_code == 406
def test_jsonp(self):
"""Test for a JSON-P callback on a collection of resources."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
response = self.app.get('/api/person?callback=foo')
assert response.data.startswith(b'foo(')
assert response.data.endswith(b')')
document = loads(response.data[4:-1])
people = document['data']
assert ['1', '2'] == sorted(person['id'] for person in people)
def test_msie8(self):
"""Tests for compatibility with Microsoft Internet Explorer 8.
According to issue #267, making requests using JavaScript from MSIE8
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
headers = {'User-Agent': MSIE8_UA}
content_type = 'text/html'
response = self.app.get('/api/person', headers=headers,
content_type=content_type)
assert response.status_code == 200
def test_msie9(self):
"""Tests for compatibility with Microsoft Internet Explorer 9.
According to issue #267, making requests using JavaScript from MSIE9
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
headers = {'User-Agent': MSIE9_UA}
content_type = 'text/html'
response = self.app.get('/api/person', headers=headers,
content_type=content_type)
assert response.status_code == 200
def test_callable_query(self):
"""Tests for making a query with a custom callable ``query`` attribute.
For more information, see pull request #133.
"""
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
self.session.add_all([comment1, comment2])
self.session.commit()
response = self.app.get('/api/comment')
document = loads(response.data)
comments = document['data']
assert ['1'] == sorted(comment['id'] for comment in comments)
def test_collection_name_multiple(self):
"""Tests for fetching multiple resources with an alternate collection
name.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, collection_name='people')
response = self.app.get('/api/people')
assert response.status_code == 200
document = loads(response.data)
people = document['data']
assert len(people) == 1
person = people[0]
assert person['id'] == '1'
assert person['type'] == 'people'
def test_group_by(self):
"""Tests for grouping results."""
person1 = self.Person(id=1, name=u'foo')
person2 = self.Person(id=2, name=u'foo')
person3 = self.Person(id=3, name=u'bar')
self.session.add_all([person1, person2, person3])
self.session.commit()
query_string = {'group': 'name'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
assert ['bar', 'foo'] == sorted(person['attributes']['name']
for person in people)
def test_group_by_related(self):
"""Tests for grouping results by a field on a related model."""
person1 = self.Person(id=1, name=u'foo')
person2 = self.Person(id=2, name=u'bar')
article1 = self.Article(id=1)
article2 = self.Article(id=2)
article3 = self.Article(id=3)
article1.author = person1
article2.author = person1
article3.author = person2
self.session.add_all([person1, person2, article1, article2, article3])
self.session.commit()
query_string = {'group': 'author.name'}
response = self.app.get('/api/article', query_string=query_string)
document = loads(response.data)
articles = document['data']
author_ids = sorted(article['relationships']['author']['data']['id']
for article in articles)
assert ['1', '2'] == author_ids
def test_group_by_mutiple_relationship_attributes(self):
"""Tests for grouping results by multiple fields of a related model."""
names = [u'foo', u'bar']
ages = [10, 20]
# There are two people with each combination of name and age.
for i, (name, age) in enumerate(product(names, ages), start=1):
person1 = self.Person(id=2 * i - 1, name=name, age=age)
person2 = self.Person(id=2 * i, name=name, age=age)
article1 = self.Article(author=person1)
article2 = self.Article(author=person2)
self.session.add_all([article1, article2, person1, person2])
self.session.commit()
query_string = {'group': ','.join(['author.name', 'author.age'])}
response = self.app.get('/api/article', query_string=query_string)
document = loads(response.data)
articles = document['data']
author_ids = sorted(article['relationships']['author']['data']['id']
for article in articles)
assert ['2', '4', '6', '8'] == author_ids
def test_pagination_links_empty_collection(self):
"""Tests that pagination links work correctly for an empty
collection.
"""
base_url = '/api/person'
response = self.app.get(base_url)
assert response.status_code == 200
document = loads(response.data)
pagination = document['links']
base_url = '{0}?'.format(base_url)
first = unquote(pagination['first'])
self.assertIn(base_url, first)
self.assertIn('page[number]=1', first)
last = unquote(pagination['last'])
self.assertIn(base_url, last)
self.assertIn('page[number]=1', last)
self.assertIs(pagination['prev'], None)
self.assertIs(pagination['next'], None)
def test_link_headers_empty_collection(self):
"""Tests that :http:header:`Link` headers work correctly for an
empty collection.
"""
base_url = '/api/person'
response = self.app.get(base_url)
self.assertEqual(response.status_code, 200)
base_url = '{0}?'.format(base_url)
# There should be exactly two, one for the first page and one
# for the last page; there are no previous or next pages, so
# there cannot be any valid Link headers for them.
links = response.headers['Link'].split(',')
self.assertEqual(len(links), 2)
# Decide which link is for the first page and which is for the last.
first, last = links
if 'last' in links[0]:
first, last = last, first
first = unquote(first)
self.assertIn(base_url, first)
self.assertIn('rel="first"', first)
self.assertIn('page[number]=1', first)
last = unquote(last)
self.assertIn(base_url, last)
self.assertIn('rel="last"', last)
self.assertIn('page[number]=1', last)
def test_pagination_with_query_parameter(self):
"""Tests that the URLs produced for pagination links include
non-pagination query parameters from the original request URL.
"""
query_string = {'foo': 'bar'}
base_url = '/api/person'
response = self.app.get(base_url, query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
pagination = document['links']
base_url = '{0}?'.format(base_url)
# There are no previous and next links in this case, so we only
# check the first and last links.
assert base_url in pagination['first']
assert 'foo=bar' in pagination['first']
assert base_url in pagination['last']
assert 'foo=bar' in pagination['last']
def test_sorting_null_field(self):
"""Tests that sorting by a nullable field causes resources with
a null attribute value to appear first.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2, name=u'foo')
person3 = self.Person(id=3, name=u'bar')
person4 = self.Person(id=4)
self.session.add_all([person1, person2, person3, person4])
self.session.commit()
query_string = {'sort': 'name'}
response = self.app.get('/api/person', query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
people = document['data']
assert len(people) == 4
person_ids = list(map(itemgetter('id'), people))
assert ['3', '2'] == person_ids[-2:]
# TODO In Python 2.7 or later, this should be a set literal.
assert set(['1', '4']) == set(person_ids[:2])
def test_sorting_hybrid_property(self):
"""Test for sorting on a hybrid property."""
person1 = self.Person(id=1, age=10)
person2 = self.Person(id=2, age=20)
self.session.add_all([person1, person2])
self.session.commit()
query_string = {'sort': 'is_minor'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
self.assertEqual(['2', '1'], list(map(itemgetter('id'), people)))
query_string = {'sort': '-is_minor'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
self.assertEqual(['1', '2'], list(map(itemgetter('id'), people)))
def test_sorting_hybrid_expression(self):
"""Test for sorting on a hybrid property with a separate expression.
For more information, see GitHub issue #562.
"""
article1 = self.Article(id=1)
article2 = self.Article(id=2)
comment = self.Comment(id=1)
article1.comments = [comment]
self.session.add_all([article1, article2, comment])
self.session.commit()
query_string = {'sort': 'num_comments'}
response = self.app.get('/api/article', query_string=query_string)
document = loads(response.data)
articles = document['data']
self.assertEqual(['2', '1'], list(map(itemgetter('id'), articles)))
query_string = {'sort': '-num_comments'}
response = self.app.get('/api/article', query_string=query_string)
document = loads(response.data)
articles = document['data']
self.assertEqual(['1', '2'], list(map(itemgetter('id'), articles)))
def test_case_insensitive_sorting(self):
"""Test for case-insensitive sorting.
For more information, see GitHub issue #626.
"""
person1 = self.Person(id=1, name=u'B')
person2 = self.Person(id=2, name=u'a')
self.session.add_all([person1, person2])
self.session.commit()
query_string = {'sort': 'name', 'ignorecase': 1}
response = self.app.get('/api/person', query_string=query_string)
# The ASCII character code for the uppercase letter 'B' comes
# before the ASCII character code for the lowercase letter 'a',
# but in case-insensitive sorting, the 'a' should precede the
# 'B'.
document = loads(response.data)
person1, person2 = document['data']
self.assertEqual(person1['id'], u'2')
self.assertEqual(person1['attributes']['name'], u'a')
self.assertEqual(person2['id'], u'1')
self.assertEqual(person2['attributes']['name'], u'B')
def test_case_insensitive_sorting_relationship_attributes(self):
"""Test for case-insensitive sorting on relationship attributes."""
person1 = self.Person(id=1, name=u'B')
person2 = self.Person(id=2, name=u'a')
article1 = self.Article(id=1, author=person1)
article2 = self.Article(id=2, author=person2)
self.session.add_all([article1, article2, person1, person2])
self.session.commit()
query_string = {'sort': 'author.name', 'ignorecase': 1}
response = self.app.get('/api/article', query_string=query_string)
# The ASCII character code for the uppercase letter 'B' comes
# before the ASCII character code for the lowercase letter 'a',
# but in case-insensitive sorting, the 'a' should precede the
# 'B'.
document = loads(response.data)
article1, article2 = document['data']
self.assertEqual(article1['id'], u'2')
self.assertEqual(article2['id'], u'1')
class TestFetchResource(ManagerTestBase):
def setUp(self):
super(TestFetchResource, self).setUp()
# class Article(self.Base):
# __tablename__ = 'article'
# id = Column(Integer, primary_key=True)
# title = Column(Unicode, primary_key=True)
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
# class Tag(self.Base):
# __tablename__ = 'tag'
# name = Column(Unicode, primary_key=True)
# self.Article = Article
self.Person = Person
# self.Tag = Tag
self.Base.metadata.create_all()
# self.manager.create_api(Article)
self.manager.create_api(Person)
# self.manager.create_api(Tag)
def test_jsonp(self):
"""Test for a JSON-P callback on a single resource request."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1?callback=foo')
assert response.data.startswith(b'foo(')
assert response.data.endswith(b')')
document = loads(response.data[4:-1])
person = document['data']
assert person['id'] == '1'
@skip('Currently not supported')
def test_alternate_primary_key(self):
"""Tests that models with primary keys that are not named ``id`` are
are still accessible via their primary keys.
"""
tag = self.Tag(name=u'foo')
self.session.add(tag)
self.session.commit()
response = self.app.get('/api/tag/foo')
document = loads(response.data)
tag = document['data']
assert tag['id'] == 'foo'
@skip('Currently not supported')
def test_primary_key_int_string(self):
"""Tests for getting a resource that has a string primary key,
including the possibility of a string representation of a number.
"""
tag = self.Tag(name=u'1')
self.session.add(tag)
self.session.commit()
response = self.app.get('/api/tag/1')
document = loads(response.data)
tag = document['data']
assert tag['attributes']['name'] == '1'
assert tag['id'] == '1'
@skip('Currently not supported')
def test_specified_primary_key(self):
"""Tests that models with more than one primary key are accessible via
a primary key specified by the server.
"""
article = self.Article(id=1, title=u'foo')
self.session.add(article)
self.session.commit()
self.manager.create_api(self.Article, url_prefix='/api2',
primary_key='title')
response = self.app.get('/api2/article/1')
assert response.status_code == 404
response = self.app.get('/api2/article/foo')
assert response.status_code == 200
document = loads(response.data)
resource = document['data']
# Resource objects must have string IDs.
assert resource['id'] == str(article.id)
assert resource['title'] == article.title
def test_collection_name(self):
"""Tests for fetching a single resource with an alternate collection
name.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, collection_name='people',
url_prefix='/api2')
response = self.app.get('/api2/people/1')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['id'] == '1'
assert person['type'] == 'people'
def test_attributes_in_url(self):
"""Tests that a user attempting to access an attribute in the
URL instead of a relation yields a meaningful error response.
For more information, see issue #213.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person)
response = self.app.get('/api/person/1/id')
check_sole_error(response, 404, ['No such relation', 'id'])
class TestFetchRelation(ManagerTestBase):
def setUp(self):
super(TestFetchRelation, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_nonexistent_resource(self):
"""Tests that a request for a relation on a nonexistent resource yields
an error.
"""
response = self.app.get('/api/person/bogus/articles')
assert response.status_code == 404
# TODO Check error message here.
def test_nonexistent_relation(self):
"""Tests that a request for a nonexistent relation yields an error."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1/bogus')
assert response.status_code == 404
# TODO Check error message here.
def test_to_many_pagination(self):
"""Tests that fetching a to-many relation obeys pagination.
For more information, see the `Pagination`_ section of the JSON
API specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
person = self.Person(id=1)
articles = [self.Article(id=i) for i in range(10)]
person.articles = articles
self.session.add(person)
self.session.add_all(articles)
self.session.commit()
params = {'page[number]': 3, 'page[size]': 2}
base_url = '/api/person/1/articles'
response = self.app.get(base_url, query_string=params)
document = loads(response.data)
articles = document['data']
article_types = [article['type'] for article in articles]
self.assertTrue(all(t == 'article' for t in article_types))
self.assertEqual(['4', '5'], sorted(map(itemgetter('id'), articles)))
pagination = document['links']
base_url = '{0}?'.format(base_url)
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
prev = unquote(pagination['prev'])
self.assertIn(base_url, first)
self.assertIn('page[number]=1', first)
self.assertIn(base_url, last)
self.assertIn('page[number]=5', last)
self.assertIn(base_url, prev)
self.assertIn('page[number]=2', prev)
self.assertIn(base_url, next_)
self.assertIn('page[number]=4', next_)
def test_to_many_sorting(self):
"""Tests for sorting a to-many relation."""
person = self.Person(id=1)
article1 = self.Article(id=1, title=u'b')
article2 = self.Article(id=2, title=u'c')
article3 = self.Article(id=3, title=u'a')
articles = [article1, article2, article3]
person.articles = articles
self.session.add(person)
self.session.add_all(articles)
self.session.commit()
params = {'sort': '-title'}
response = self.app.get('/api/person/1/articles', query_string=params)
document = loads(response.data)
articles = document['data']
assert ['c', 'b', 'a'] == [article['attributes']['title']
for article in articles]
assert ['2', '1', '3'] == [article['id'] for article in articles]
def test_to_many_grouping(self):
"""Tests for grouping a to-many relation."""
person = self.Person(id=1)
article1 = self.Article(id=1, title=u'b')
article2 = self.Article(id=2, title=u'a')
article3 = self.Article(id=3, title=u'b')
articles = [article1, article2, article3]
person.articles = articles
self.session.add(person)
self.session.add_all(articles)
self.session.commit()
params = {'group': 'title'}
response = self.app.get('/api/person/1/articles', query_string=params)
document = loads(response.data)
articles = document['data']
assert ['a', 'b'] == sorted(article['attributes']['title']
for article in articles)
class TestFetchRelatedResource(ManagerTestBase):
def setUp(self):
super(TestFetchRelatedResource, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_nonexistent_related_resource(self):
"""Tests that a request for a nonexistent related resource yields an
error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1/articles/1')
assert response.status_code == 404
# TODO Check error message here.
def test_nonexistent_related_model(self):
"""Tests that a request for a nonexistent related model yields
an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1/bogus/1')
check_sole_error(response, 404, ['No such relation', 'bogus'])
def test_to_one_with_id(self):
"""Tests that a request to fetch a resource by its ID from a to-one
relation yields an error.
"""
article = self.Article(id=1)
person = self.Person(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
response = self.app.get('/api/article/1/author/1')
check_sole_error(response, 404, ['Cannot access', 'to-one',
'related resource'])
def test_related_resource(self):
"""Tests for fetching a single resource from a to-many relation.
This is not required by the JSON API specification.
"""
article = self.Article(id=1)
person = self.Person(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
response = self.app.get('/api/person/1/articles/1')
assert response.status_code == 200
document = loads(response.data)
article = document['data']
assert article['id'] == '1'
assert article['type'] == 'article'
author = article['relationships']['author']['data']
assert author['id'] == '1'
assert author['type'] == 'person'
def test_nonexistent_resource(self):
"""Tests that a request for a relation on a nonexistent resource yields
an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/person/foo/articles/1')
assert response.status_code == 404
# TODO Check error message here.
def test_nonexistent_relation(self):
"""Tests that a request for a nonexistent relation on a resource yields
an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1/bogus/1')
assert response.status_code == 404
# TODO Check error message here.
class TestFetchRelationship(ManagerTestBase):
"""Tests for fetching from a relationship URL."""
def setUp(self):
super(TestFetchRelationship, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_relationship_url_nonexistent_instance(self):
"""Tests that an attempt to fetch from a relationship URL for a
resource that doesn't exist yields an error.
"""
response = self.app.get('/api/person/bogus/relationships/articles')
assert response.status_code == 404
# TODO check error message here
def test_relationship_url_nonexistent_relation(self):
"""Tests that an attempt to fetch from a relationship URL without
specifying a relationship yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1/relationships')
assert response.status_code == 404
# TODO check error message here
class TestServerSparseFieldsets(ManagerTestBase):
"""Tests for specifying default sparse fieldsets on the server."""
def setUp(self):
super(TestServerSparseFieldsets, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
age = Column(Integer)
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship(Person, backref=backref('articles'))
comments = relationship('Comment')
def first_comment(self):
return min(self.comments, key=lambda c: c.id)
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
article_id = Column(Integer, ForeignKey('article.id'))
article = relationship(Article)
class Photo(self.Base):
__tablename__ = 'photo'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
def website(self):
return 'example.com'
@property
def year(self):
return 2015
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Photo = Photo
self.Base.metadata.create_all()
def test_only_column(self):
"""Tests for specifying that responses should only include certain
column fields.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, only=['name'])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert ['attributes', 'id', 'type'] == sorted(person)
assert ['name'] == sorted(person['attributes'])
def test_only_relationship(self):
"""Tests for specifying that response should only include certain
relationships.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, only=['articles'])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert ['id', 'relationships', 'type'] == sorted(person)
assert ['articles'] == sorted(person['relationships'])
# # TODO This doesn't exactly make sense anymore; each type of included
# # resource should really determine its own sparse fieldsets.
# def test_only_on_included(self):
# """Tests for specifying that response should only include certain
# attributes of related models.
# """
# person = self.Person(id=1)
# article = self.Article(title='foo')
# article.author = person
# self.session.add_all([person, article])
# self.session.commit()
# only = ['articles', 'articles.title']
# self.manager.create_api(self.Person, only=only)
# response = self.app.get('/api/person/1?include=articles')
# document = loads(response.data)
# person = document['data']
# assert person['id'] == '1'
# assert person['type'] == 'person'
# assert 'name' not in person
# articles = person['relationships']['articles']['data']
# included = document['included']
# expected_ids = sorted(article['id'] for article in articles)
# actual_ids = sorted(article['id'] for article in included)
# assert expected_ids == actual_ids
# assert all('title' not in article for article in included)
# assert all('comments' in article['relationships']
# for article in included)
def test_only_as_objects(self):
"""Test for specifying included columns as SQLAlchemy column objects
instead of strings.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, only=[self.Person.name])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert ['attributes', 'id', 'type'] == sorted(person)
assert ['name'] == sorted(person['attributes'])
def test_only_none(self):
"""Tests that providing an empty list as the list of fields to include
in responses causes responses to have only the ``id`` and ``type``
elements.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, only=[])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert ['id', 'type'] == sorted(person)
def test_additional_attributes(self):
"""Tests that additional attributes other than SQLAlchemy columns can
be included in responses by default.
"""
self.Person.foo = 'bar'
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, additional_attributes=['foo'])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert person['attributes']['foo'] == 'bar'
def test_additional_attributes_not_related(self):
"""Tests that we do not try to include additional attributes when
requesting a related resource.
For more information, see pull request #257.
"""
self.Article.foo = 'bar'
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Article, additional_attributes=['foo'])
self.manager.create_api(self.Person)
response = self.app.get('/api/article/1/author')
document = loads(response.data)
person = document['data']
assert 'foo' not in person['attributes']
def test_additional_attributes_callable(self):
"""Tests that callable attributes can be included using the
``additional_attributes`` keyword argument.
"""
photo = self.Photo(id=1)
self.session.add(photo)
self.session.commit()
self.manager.create_api(self.Photo, additional_attributes=['website'])
response = self.app.get('/api/photo/1')
document = loads(response.data)
photo = document['data']
assert photo['attributes']['website'] == 'example.com'
def test_additional_attributes_property(self):
"""Tests that class properties can be included using the
``additional_attributes`` keyword argument.
"""
photo = self.Photo(id=1)
self.session.add(photo)
self.session.commit()
self.manager.create_api(self.Photo, additional_attributes=['year'])
response = self.app.get('/api/photo/1')
document = loads(response.data)
photo = document['data']
assert photo['attributes']['year'] == 2015
def test_additional_attributes_object(self):
"""Tests that an additional attribute is serialized if it is an
instance of a SQLAlchemy model.
Technically, a resource's attribute MAY contain any valid JSON object,
so this is allowed by the `JSON API specification`_.
.. _JSON API specification:
http://jsonapi.org/format/#document-structure-resource-object-attributes
"""
article = self.Article(id=1)
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
article.comments = [comment1, comment2]
self.session.add_all([article, comment1, comment2])
self.session.commit()
class MySerializer(DefaultSerializer):
def serialize(self, *args, **kw):
result = super(MySerializer, self).serialize(*args, **kw)
if 'attributes' not in result['data']:
result['data']['attributes'] = {}
result['data']['attributes']['foo'] = 'foo'
return result
self.manager.create_api(self.Article,
additional_attributes=['first_comment'])
# Ensure that the comment object has a custom serialization
# function, so we can test that it is serialized using this
# function in particular.
self.manager.create_api(self.Comment, serializer_class=MySerializer)
# HACK Need to create an API for this model because otherwise
# we're not able to create the link URLs to them.
self.manager.create_api(self.Person)
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
first_comment = article['attributes']['first_comment']
assert first_comment['id'] == '1'
assert first_comment['type'] == 'comment'
assert first_comment['attributes']['foo'] == 'foo'
def test_exclude(self):
"""Test for excluding columns from a resource's representation."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, exclude=['name'])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert 'name' not in person['attributes']
# # TODO This doesn't exactly make sense anymore; each type of included
# # resource should really determine its own sparse fieldsets.
# def test_exclude_on_included(self):
# """Tests for specifying that response should exclude certain
# attributes of related models.
#
# """
# person = self.Person(id=1)
# article = self.Article(title='foo')
# article.author = person
# self.session.add_all([person, article])
# self.session.commit()
# self.manager.create_api(self.Person, exclude=['articles.title'])
# response = self.app.get('/api/person/1?include=articles')
# document = loads(response.data)
# person = document['data']
# articles = person['relationships']['articles']['data']
# included = document['included']
# expected_ids = sorted(article['id'] for article in articles)
# actual_ids = sorted(article['id'] for article in included)
# assert expected_ids == actual_ids
# assert all('title' not in article for article in included)
def test_exclude_as_objects(self):
"""Test for specifying excluded columns as SQLAlchemy column
attributes.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, exclude=[self.Person.name])
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert 'name' not in person['attributes']
def test_exclude_relations(self):
"""Tests for excluding relationships of a resource."""
article = self.Article(id=1)
comment = self.Comment()
person = self.Person()
article.author = person
comment.article = article
self.session.add_all([article, comment, person])
self.session.commit()
self.manager.create_api(self.Article, exclude=['comments'])
# Create the APIs for the other models, just so they have URLs.
self.manager.create_api(self.Person)
self.manager.create_api(self.Comment)
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
assert 'comments' not in article['relationships']
author = article['relationships']['author']['data']
assert '1' == author['id']
assert 'person' == author['type']
class TestProcessors(ManagerTestBase):
"""Tests for pre- and postprocessors."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestProcessors, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
articles = relationship('Article')
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship(Person)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
def test_single_resource_processing_exception(self):
"""Tests for a preprocessor that raises a :exc:`ProcessingException`
when fetching a single resource.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
def forbidden(**kw):
raise ProcessingException(status=403, detail='forbidden')
preprocessors = dict(GET_RESOURCE=[forbidden])
self.manager.create_api(self.Person, preprocessors=preprocessors)
response = self.app.get('/api/person/1')
assert response.status_code == 403
document = loads(response.data)
errors = document['errors']
assert len(errors) == 1
error = errors[0]
assert 'forbidden' == error['detail']
def test_collection_processing_exception(self):
"""Tests for a preprocessor that raises a :exc:`ProcessingException`
when fetching a collection of resources.
"""
def forbidden(**kw):
raise ProcessingException(status=403, detail='forbidden')
preprocessors = dict(GET_COLLECTION=[forbidden])
self.manager.create_api(self.Person, preprocessors=preprocessors)
response = self.app.get('/api/person')
assert response.status_code == 403
document = loads(response.data)
errors = document['errors']
assert len(errors) == 1
error = errors[0]
assert 'forbidden' == error['detail']
def test_resource(self):
"""Tests for running a preprocessor on a request to fetch a
single resource.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'GET_RESOURCE': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
self.app.get('/api/person/1')
assert data['triggered']
def test_change_id(self):
"""Tests that a return value from a preprocessor overrides the ID of
the resource to fetch as given in the request URL.
"""
person = self.Person(id=1, name=u'foo')
self.session.add(person)
self.session.commit()
def increment_id(resource_id=None, **kw):
if resource_id is None:
raise ProcessingException
return int(resource_id) + 1
preprocessors = dict(GET_RESOURCE=[increment_id])
self.manager.create_api(self.Person, preprocessors=preprocessors)
response = self.app.get('/api/person/0')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['id'] == '1'
assert person['attributes']['name'] == 'foo'
def test_change_relation(self):
"""Tests for changing the resource ID when fetching a relation.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_id(*args, **kw):
# We will change the primary resource ID.
return 1
preprocessors = {'GET_RELATION': [change_id]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
response = self.app.get('/api/person/bogus/articles')
document = loads(response.data)
articles = document['data']
assert len(articles) == 1
article = articles[0]
assert 'article' == article['type']
assert '1' == article['id']
def test_relationship(self):
"""Tests for running a preprocessor on a request to fetch a
relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'GET_RELATIONSHIP': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
self.app.get('/api/person/1/relationships/articles')
assert data['triggered']
def test_change_id_relationship(self):
"""Tests for changing the resource ID when fetching a
relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_id(*args, **kw):
# We will change the primary resource ID.
return 1
preprocessors = {'GET_RELATIONSHIP': [change_id]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
response = self.app.get('/api/person/bogus/relationships/articles')
document = loads(response.data)
articles = document['data']
assert len(articles) == 1
article = articles[0]
assert 'article' == article['type']
assert '1' == article['id']
def test_relation(self):
"""Tests that a preprocessor is executed when fetching a
relation.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'GET_RELATION': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
self.app.get('/api/person/1/articles')
assert data['triggered']
def test_change_relation_2(self):
"""Tests for changing the primary resource ID and the relation
name in a preprocessor for fetching a relation.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_two(*args, **kw):
# We will change the primary resource ID and the relation name.
return 1, 'articles'
preprocessors = {'GET_RELATION': [change_two]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
response = self.app.get('/api/person/foo/bar')
document = loads(response.data)
articles = document['data']
assert len(articles) == 1
article = articles[0]
assert 'article' == article['type']
assert '1' == article['id']
def test_related_resource(self):
"""Tests that a preprocessor is executed when fetching a
related resource from a to-many relation.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'GET_RELATED_RESOURCE': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
self.app.get('/api/person/1/articles/1')
assert data['triggered']
def test_change_related_resource_1(self):
"""Tests for changing the primary resource ID in a preprocessor
for fetching a related resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_one(*args, **kw):
# We will change the primary resource ID only.
return 1
preprocessors = {'GET_RELATED_RESOURCE': [change_one]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
response = self.app.get('/api/person/foo/articles/1')
document = loads(response.data)
resource = document['data']
assert 'article' == resource['type']
assert '1' == resource['id']
def test_change_related_resource_2(self):
"""Tests for changing the primary resource ID and the relation
name in a preprocessor for fetching a related resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_two(*args, **kw):
# We will change the primary resource ID and the relation name.
return 1, 'articles'
preprocessors = {'GET_RELATED_RESOURCE': [change_two]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
response = self.app.get('/api/person/foo/bar/1')
document = loads(response.data)
resource = document['data']
assert 'article' == resource['type']
assert '1' == resource['id']
def test_change_related_resource_3(self):
"""Tests for changing the primary resource ID, the relation
name, and the related resource ID in a preprocessor for fetching
a related resource.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_three(*args, **kw):
# We will change the primary resource ID, the relation name,
# and the related resource ID.
return 1, 'articles', 1
preprocessors = {'GET_RELATED_RESOURCE': [change_three]}
self.manager.create_api(self.Person, preprocessors=preprocessors)
# Need to create an API for Article resources so that each
# Article has a URL.
self.manager.create_api(self.Article)
response = self.app.get('/api/person/foo/bar/baz')
document = loads(response.data)
resource = document['data']
assert 'article' == resource['type']
assert '1' == resource['id']
def test_last_preprocessor_changes_id(self):
"""Tests that a return value from the last preprocessor in the list
overrides the ID of the resource to fetch as given in the request URL.
"""
person = self.Person(id=2, name=u'foo')
self.session.add(person)
self.session.commit()
def increment_id(resource_id=None, **kw):
if resource_id is None:
raise ProcessingException
return int(resource_id) + 1
preprocessors = dict(GET_RESOURCE=[increment_id, increment_id])
self.manager.create_api(self.Person, preprocessors=preprocessors)
response = self.app.get('/api/person/0')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['id'] == '2'
assert person['attributes']['name'] == 'foo'
def test_no_client_filters(self):
"""Tests that a preprocessor can modify the filter objects in a
request, even if the client did not specify any ``filter[objects]``
query parameter.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
def restrict_ids(filters=None, **kw):
"""Adds an additional filter to any existing filters that restricts
which resources appear in the response.
"""
if filters is None:
raise ProcessingException
filt = dict(name='id', op='lt', val=2)
filters.append(filt)
preprocessors = dict(GET_COLLECTION=[restrict_ids])
self.manager.create_api(self.Person, preprocessors=preprocessors)
response = self.app.get('/api/person')
assert response.status_code == 200
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_add_filters(self):
"""Tests that a preprocessor can modify the filter objects provided by
the client in the ``filter[objects]`` query parameter.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
def restrict_ids(filters=None, **kw):
"""Adds an additional filter to any existing filters that restricts
which resources appear in the response.
"""
if filters is None:
raise ProcessingException
filt = dict(name='id', op='lt', val=2)
filters.append(filt)
preprocessors = dict(GET_COLLECTION=[restrict_ids])
self.manager.create_api(self.Person, preprocessors=preprocessors)
filters = [dict(name='id', op='in', val=[1, 3])]
query = {'filter[objects]': dumps(filters)}
response = self.app.get('/api/person', query_string=query)
assert response.status_code == 200
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_collection_postprocessor(self):
"""Tests that a postprocessor for a collection endpoint has access to
the filters specified by the client.
"""
client_filters = [dict(name='id', op='eq', val=1)]
def check_filters(filters=None, **kw):
"""Assert that the filters that Flask-Restless understood from the
request are the same filter objects provided by the client.
"""
assert filters == client_filters
postprocessors = dict(GET_COLLECTION=[check_filters])
self.manager.create_api(self.Person, postprocessors=postprocessors)
query_string = {'filter[objects]': dumps(client_filters)}
response = self.app.get('/api/person', query_string=query_string)
assert response.status_code == 200
def test_resource_postprocessor(self):
"""Tests for a postprocessor for a single resource."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
def modify_result(result=None, **kw):
result['foo'] = 'bar'
postprocessors = dict(GET_RESOURCE=[modify_result])
self.manager.create_api(self.Person, postprocessors=postprocessors)
response = self.app.get('/api/person/1')
assert response.status_code == 200
document = loads(response.data)
assert document['foo'] == 'bar'
class TestDynamicRelationships(ManagerTestBase):
"""Tests for fetching resources from dynamic to-many relationships."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestDynamicRelationships, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
articles = relationship(Article, lazy='dynamic')
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_to_many(self):
"""Tests for fetching a resource with a dynamic link to a to-many
relation.
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
article1.author = person
article2.author = person
self.session.add_all([person, article1, article2])
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
articles = person['relationships']['articles']['data']
assert ['1', '2'] == sorted(article['id'] for article in articles)
def test_related_resource_url(self):
"""Tests for fetching a resource with a dynamic link to a to-many
relation from the related resource URL.
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
response = self.app.get('/api/person/1/articles')
assert response.status_code == 200
document = loads(response.data)
articles = document['data']
assert ['1', '2'] == sorted(article['id'] for article in articles)
assert all(article['type'] == 'article' for article in articles)
def test_relationship_url(self):
"""Tests for fetching a resource with a dynamic link to a to-many
relation from the relationship URL.
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
response = self.app.get('/api/person/1/relationships/articles')
assert response.status_code == 200
document = loads(response.data)
articles = document['data']
assert ['1', '2'] == sorted(article['id'] for article in articles)
assert all(article['type'] == 'article' for article in articles)
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
"""Tests for fetching resources defined as Flask-SQLAlchemy models
instead of pure SQLAlchemy models.
"""
def setUp(self):
"""Creates the Flask-SQLAlchemy database and models."""
super(TestFlaskSQLAlchemy, self).setUp()
class Person(self.db.Model):
id = self.db.Column(self.db.Integer, primary_key=True)
self.Person = Person
self.db.create_all()
self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
self.manager.create_api(self.Person)
def test_fetch_resource(self):
"""Test for fetching a resource."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert person['id'] == '1'
assert person['type'] == 'person'
def test_fetch_collection(self):
"""Test for fetching a collection of resource."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
response = self.app.get('/api/person')
document = loads(response.data)
people = document['data']
assert ['1', '2'] == sorted(person['id'] for person in people)
| 64,767
|
Python
|
.py
| 1,442
| 35.753121
| 83
| 0.622155
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,653
|
test_creating.py
|
jfinkels_flask-restless/tests/test_creating.py
|
# -*- encoding: utf-8 -*-
# test_creating.py - unit tests for creating resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for creating resources from endpoints generated by
Flask-Restless.
This module includes tests for additional functionality that is not
already tested by :mod:`test_jsonapi`, the package that guarantees
Flask-Restless meets the minimum requirements of the JSON API
specification.
"""
from __future__ import division
from datetime import datetime
import dateutil
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Interval
from sqlalchemy import Time
from sqlalchemy import Unicode
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from flask_restless import APIManager
from flask_restless import JSONAPI_MIMETYPE
from flask_restless import DefaultDeserializer
from flask_restless import DefaultSerializer
from flask_restless import ProcessingException
from .helpers import BetterJSONEncoder as JSONEncoder
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import loads
from .helpers import FlaskSQLAlchemyTestBase
from .helpers import ManagerTestBase
from .helpers import MSIE8_UA
from .helpers import MSIE9_UA
from .helpers import raise_s_exception
from .helpers import raise_d_exception
class TestCreating(ManagerTestBase):
"""Tests for creating resources."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestCreating, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
date_created = Column(Date)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
type = Column(Unicode)
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
age = Column(Integer)
name = Column(Unicode, unique=True)
birth_datetime = Column(DateTime, nullable=True)
bedtime = Column(Time)
hangtime = Column(Interval)
articles = relationship('Article')
@hybrid_property
def is_minor(self):
if hasattr(self, 'age'):
if self.age is None:
return None
return self.age < 18
return None
class Tag(self.Base):
__tablename__ = 'tag'
name = Column(Unicode, primary_key=True)
# TODO this dummy column is required to create an API for this
# object.
id = Column(Integer)
self.Article = Article
self.Person = Person
self.Tag = Tag
self.Base.metadata.create_all()
self.manager.create_api(Person, methods=['POST'])
self.manager.create_api(Article, methods=['POST'])
self.manager.create_api(Tag, methods=['POST'])
def test_wrong_content_type(self):
"""Tests that if a client specifies only
:http:header:`Content-Type` headers with non-JSON API media
types, then the server responds with a :http:status:`415`.
"""
headers = {'Content-Type': 'application/json'}
data = {
'data': {
'type': 'person'
}
}
response = self.app.post('/api/person', data=dumps(data),
headers=headers)
assert response.status_code == 415
assert self.session.query(self.Person).count() == 0
def test_wrong_accept_header(self):
"""Tests that if a client specifies only :http:header:`Accept`
headers with non-JSON API media types, then the server responds
with a :http:status:`406`.
"""
headers = {'Accept': 'application/json'}
data = {
'data': {
'type': 'person'
}
}
response = self.app.post('/api/person', data=dumps(data),
headers=headers)
assert response.status_code == 406
assert self.session.query(self.Person).count() == 0
def test_related_resource_url_forbidden(self):
"""Tests that :http:method:`post` requests to a related resource URL
are forbidden.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([person, article])
self.session.commit()
data = dict(data=dict(type='article', id=1))
response = self.app.post('/api/person/1/articles', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
assert person.articles == []
def test_deserializing_time(self):
"""Test for deserializing a JSON representation of a time field."""
bedtime = datetime.now().time()
data = dict(data=dict(type='person', attributes=dict(bedtime=bedtime)))
data = dumps(data, cls=JSONEncoder)
response = self.app.post('/api/person', data=data)
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['attributes']['bedtime'] == bedtime.isoformat()
def test_deserializing_date(self):
"""Test for deserializing a JSON representation of a date field."""
date_created = datetime.now().date()
data = dict(data=dict(type='article',
attributes=dict(date_created=date_created)))
data = dumps(data, cls=JSONEncoder)
response = self.app.post('/api/article', data=data)
assert response.status_code == 201
document = loads(response.data)
article = document['data']
received_date = article['attributes']['date_created']
assert received_date == date_created.isoformat()
def test_deserializing_datetime(self):
"""Test for deserializing a JSON representation of a date field."""
birth_datetime = datetime.now()
data = dict(data=dict(type='person',
attributes=dict(birth_datetime=birth_datetime)))
data = dumps(data, cls=JSONEncoder)
response = self.app.post('/api/person', data=data)
assert response.status_code == 201
document = loads(response.data)
person = document['data']
received_time = person['attributes']['birth_datetime']
assert received_time == birth_datetime.isoformat()
def test_correct_content_type(self):
"""Tests that the server responds with :http:status:`201` if the
request has the correct JSON API content type.
"""
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data),
content_type=JSONAPI_MIMETYPE)
assert response.status_code == 201
assert response.headers['Content-Type'] == JSONAPI_MIMETYPE
def test_no_content_type(self):
"""Tests that the server responds with :http:status:`415` if the
request has no content type.
"""
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data),
content_type=None)
assert response.status_code == 415
assert response.headers['Content-Type'] == JSONAPI_MIMETYPE
def test_msie8(self):
"""Tests for compatibility with Microsoft Internet Explorer 8.
According to issue #267, making requests using JavaScript from MSIE8
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
headers = {'User-Agent': MSIE8_UA}
content_type = 'text/html'
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data),
headers=headers, content_type=content_type)
assert response.status_code == 201
def test_msie9(self):
"""Tests for compatibility with Microsoft Internet Explorer 9.
According to issue #267, making requests using JavaScript from MSIE9
does not allow changing the content type of the request (it is always
``text/html``). Therefore Flask-Restless should ignore the content type
when a request is coming from this client.
"""
headers = {'User-Agent': MSIE9_UA}
content_type = 'text/html'
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data),
headers=headers, content_type=content_type)
assert response.status_code == 201
def test_no_data(self):
"""Tests that a request with no data yields an error response."""
response = self.app.post('/api/person')
assert response.status_code == 400
# TODO check the error message here
def test_invalid_json(self):
"""Tests that a request with an invalid JSON causes an error response.
"""
response = self.app.post('/api/person', data='Invalid JSON string')
assert response.status_code == 400
# TODO check the error message here
def test_conflicting_attributes(self):
"""Tests that an attempt to create a resource with a non-unique
attribute value where uniqueness is required causes a
:http:status:`409` response.
"""
person = self.Person(name=u'foo')
self.session.add(person)
self.session.commit()
data = dict(data=dict(type='person', attributes=dict(name=u'foo')))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 409 # Conflict
# TODO check error message here
def test_rollback_on_integrity_error(self):
"""Tests that an integrity error in the database causes a session
rollback, and that the server can still process requests correctly
after this rollback.
"""
person = self.Person(name=u'foo')
self.session.add(person)
self.session.commit()
data = dict(data=dict(type='person', attributes=dict(name=u'foo')))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 409 # Conflict
assert self.session.is_active, 'Session is in `partial rollback` state'
person = dict(data=dict(type='person', attributes=dict(name=u'bar')))
response = self.app.post('/api/person', data=dumps(person))
assert response.status_code == 201
def test_nonexistent_attribute(self):
"""Tests that the server rejects an attempt to create a resource with
an attribute that does not exist in the resource.
"""
data = dict(data=dict(type='person', attributes=dict(bogus=0)))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
def test_nonexistent_relationship(self):
"""Tests that the server rejects an attempt to create a resource
with a relationship that does not exist in the resource.
"""
data = {
'data': {
'type': 'person',
'relationships': {
'bogus': {
'data': None
}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
def test_invalid_relationship(self):
"""Tests that the server rejects an attempt to create a resource
with an invalid relationship linnkage object.
"""
# In this request, the `articles` linkage object is missing the
# `data` element.
data = {
'data': {
'type': 'person',
'relationships':
{
'articles': {}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 400
keywords = ['deserialize', 'missing', '"data"', 'element',
'linkage object', 'relationship', '"articles"']
check_sole_error(response, 400, keywords)
def test_hybrid_property(self):
"""Tests that an attempt to set a read-only hybrid property causes an
error.
See issue #171.
"""
data = dict(data=dict(type='person', attributes=dict(is_minor=True)))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
def test_nullable_datetime(self):
"""Tests for creating a model with a nullable datetime field.
For more information, see issue #91.
"""
data = dict(data=dict(type='person',
attributes=dict(birth_datetime=None)))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['attributes']['birth_datetime'] is None
def test_empty_date(self):
"""Tests that attempting to assign an empty date string to a date field
actually assigns a value of ``None``.
For more information, see issue #91.
"""
data = dict(data=dict(type='person',
attributes=dict(birth_datetime='')))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['attributes']['birth_datetime'] is None
def test_current_timestamp(self):
"""Tests that the string ``'CURRENT_TIMESTAMP'`` gets converted into a
datetime object when making a request to set a date or time field.
"""
CURRENT = 'CURRENT_TIMESTAMP'
data = dict(data=dict(type='person',
attributes=dict(birth_datetime=CURRENT)))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
birth_datetime = person['attributes']['birth_datetime']
assert birth_datetime is not None
birth_datetime = dateutil.parser.parse(birth_datetime)
diff = datetime.utcnow() - birth_datetime
# Check that the total number of seconds from the server creating the
# Person object to (about) now is not more than about a minute.
assert diff.days == 0
assert (diff.seconds + diff.microseconds / 1000000) < 3600
def test_timedelta(self):
"""Tests for creating an object with a timedelta attribute."""
data = dict(data=dict(type='person', attributes=dict(hangtime=300)))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['attributes']['hangtime'] == 300
def test_to_many(self):
"""Tests the creation of a model with a to-many relation."""
article1 = self.Article(id=1)
article2 = self.Article(id=2)
self.session.add_all([article1, article2])
self.session.commit()
data = {
'data': {
'type': 'person',
'relationships': {
'articles': {
'data': [
{'type': 'article', 'id': '1'},
{'type': 'article', 'id': '2'}
]
}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
articles = person['relationships']['articles']['data']
assert ['1', '2'] == sorted(article['id'] for article in articles)
assert all(article['type'] == 'article' for article in articles)
def test_to_one(self):
"""Tests the creation of a model with a to-one relation."""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'article',
'relationships': {
'author': {
'data': {'type': 'person', 'id': '1'}
}
}
}
}
response = self.app.post('/api/article', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
article = document['data']
person = article['relationships']['author']['data']
assert person['type'] == 'person'
assert person['id'] == '1'
def test_unicode_primary_key(self):
"""Test for creating a resource with a unicode primary key."""
data = dict(data=dict(type='tag', attributes=dict(name=u'Юникод')))
response = self.app.post('/api/tag', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
tag = document['data']
assert tag['attributes']['name'] == u'Юникод'
def test_primary_key_as_id(self):
"""Tests the even if a primary key is not named ``id``, it still
appears in an ``id`` key in the response.
"""
data = dict(data=dict(type='tag', attributes=dict(name=u'foo')))
response = self.app.post('/api/tag', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
tag = document['data']
assert tag['id'] == u'foo'
# TODO Not supported right now.
#
# def test_treat_as_id(self):
# """Tests for specifying one attribute in a compound primary key by
# which to create a resource.
# """
# manager = APIManager(self.flaskapp, session=self.session)
# manager.create_api(self.User, primary_key='email')
# data = dict(data=dict(type='user', id=1))
# response = self.app.post('/api/user', data=dumps(data))
# document = loads(response.data)
# user = document['data']
# assert user['id'] == '1'
# assert user['type'] == 'user'
# assert user['email'] == 'foo'
def test_collection_name(self):
"""Tests for creating a resource with an alternate collection name."""
self.manager.create_api(self.Person, methods=['POST'],
collection_name='people')
data = dict(data=dict(type='people'))
response = self.app.post('/api/people', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['type'] == 'people'
# TODO This behavior is no longer supported
#
# def test_nested_relations(self):
# # Test with nested objects
# data = {'name': 'Rodriguez', 'age': 70,
# 'computers': [{'name': 'iMac', 'vendor': 'Apple',
# 'programs': [{'program':{'name':'iPhoto'}}]}]}
# response = self.app.post('/api/person', data=dumps(data))
# assert 201 == response.status_code
# response = self.app.get('/api/computer/2/programs')
# programs = loads(response.data)['objects']
# assert programs[0]['program']['name'] == 'iPhoto'
def test_custom_serialization(self):
"""Tests for custom deserialization."""
temp = []
class MySerializer(DefaultSerializer):
def serialize(self, *args, **kw):
result = super(MySerializer, self).serialize(*args, **kw)
result['data']['attributes']['foo'] = temp.pop()
return result
class MyDeserializer(DefaultDeserializer):
def deserialize(self, document, *args, **kw):
# Remove the extra 'foo' attribute and stash it in the
# `temp` list.
temp.append(document['data']['attributes'].pop('foo'))
super_deserialize = super(MyDeserializer, self).deserialize
return super_deserialize(document, *args, **kw)
# POST will deserialize once and serialize once
self.manager.create_api(self.Person, methods=['POST'],
url_prefix='/api2',
serializer_class=MySerializer,
deserializer_class=MyDeserializer)
data = dict(data=dict(type='person', attributes=dict(foo='bar')))
response = self.app.post('/api2/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['attributes']['foo'] == 'bar'
def test_serialization_exception_included(self):
"""Tests that exceptions are caught when trying to serialize
included resources.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Article, methods=['POST'],
url_prefix='/api2')
self.manager.create_api(self.Person,
serializer_class=raise_s_exception)
data = {
'data': {
'type': 'article',
'relationships': {
'author': {
'data': {
'type': 'person',
'id': 1
}
}
}
}
}
query_string = {'include': 'author'}
response = self.app.post('/api/article', data=dumps(data),
query_string=query_string)
check_sole_error(response, 500, ['Failed to serialize',
'included resource', 'type', 'person',
'ID', '1'])
def test_deserialization_exception(self):
"""Tests that exceptions are caught when a custom deserialization
method raises an exception.
"""
self.manager.create_api(self.Person, methods=['POST'],
url_prefix='/api2',
deserializer_class=raise_d_exception)
data = dict(data=dict(type='person'))
response = self.app.post('/api2/person', data=dumps(data))
assert response.status_code == 400
# TODO check error message here
def test_serialization_exception(self):
"""Tests that exceptions are caught when a custom serialization
method raises an exception.
"""
self.manager.create_api(self.Person, methods=['POST'],
url_prefix='/api2',
serializer_class=raise_s_exception)
data = dict(data=dict(type='person'))
response = self.app.post('/api2/person', data=dumps(data))
check_sole_error(response, 500, ['Failed to serialize', 'type',
'person', 'ID', '1'])
def test_to_one_related_resource_url(self):
"""Tests that attempting to add to a to-one related resource URL
(instead of a relationship URL) yields an error response.
"""
article = self.Article(id=1)
person = self.Person(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(id=1, type='person'))
response = self.app.post('/api/article/1/author', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_to_many_related_resource_url(self):
"""Tests that attempting to add to a to-many related resource URL
(instead of a relationship URL) yields an error response.
"""
article = self.Article(id=1)
person = self.Person(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.post('/api/person/1/articles', data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_missing_data(self):
"""Tests that an attempt to update a resource without providing a
"data" element yields an error.
"""
data = dict(type='person')
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 400
keywords = ['deserialize', 'missing', '"data"', 'element']
check_sole_error(response, 400, keywords)
def test_to_one_relationship_missing_data(self):
"""Tests that the server rejects a request to create a resource
with a to-one relationship when the relationship object is
missing a ``data`` element.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'article',
'relationships': {
'author': {
'type': 'person'
}
}
}
}
response = self.app.post('/api/article', data=dumps(data))
keywords = ['deserialize', 'missing', '"data"', 'element',
'linkage object', 'relationship', '"author"']
check_sole_error(response, 400, keywords)
def test_to_one_relationship_missing_id(self):
"""Tests that the server rejects a request to create a resource
with a to-one relationship when the relationship linkage object
is missing an ``id`` element.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'article',
'relationships': {
'author': {
'data': {
'type': 'person'
}
}
}
}
}
response = self.app.post('/api/article', data=dumps(data))
keywords = ['deserialize', 'missing', '"id"', 'element',
'linkage object', 'relationship', '"author"']
check_sole_error(response, 400, keywords)
def test_to_one_relationship_missing_type(self):
"""Tests that the server rejects a request to create a resource
with a to-one relationship when the relationship linkage object
is missing a ``type`` element.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'article',
'relationships': {
'author': {
'data': {
'id': '1'
}
}
}
}
}
response = self.app.post('/api/article', data=dumps(data))
keywords = ['deserialize', 'missing', '"type"', 'element',
'linkage object', 'relationship', '"author"']
check_sole_error(response, 400, keywords)
def test_to_one_relationship_conflicting_type(self):
"""Tests that the server rejects a request to create a resource
with a to-one relationship when the relationship linkage object
has a ``type`` element that conflicts with the actual type of
the related resource.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'article',
'relationships': {
'author': {
'data': {
'id': '1',
'type': 'article'
}
}
}
}
}
response = self.app.post('/api/article', data=dumps(data))
keywords = ['deserialize', 'expected', 'type', '"person"', '"article"',
'linkage object', 'relationship', '"author"']
check_sole_error(response, 409, keywords)
def test_to_many_relationship_missing_id(self):
"""Tests that the server rejects a request to create a resource
with a to-many relationship when any of the relationship linkage
objects is missing an ``id`` element.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'person',
'relationships': {
'articles': {
'data': [
{'type': 'article'}
]
}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
keywords = ['deserialize', 'missing', '"id"', 'element',
'linkage object', 'relationship', '"articles"']
check_sole_error(response, 400, keywords)
def test_to_many_relationship_missing_type(self):
"""Tests that the server rejects a request to create a resource
with a to-many relationship when any of the relationship linkage
objects is missing a ``type`` element.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'person',
'relationships': {
'articles': {
'data': [
{'id': '1'}
]
}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
keywords = ['deserialize', 'missing', '"type"', 'element',
'linkage object', 'relationship', '"articles"']
check_sole_error(response, 400, keywords)
def test_to_many_relationship_not_a_list(self):
"""Tests that the server rejects a request to create a resource
with a to-many relationship when the relationship is not a list.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'person',
'relationships': {
'articles': {
'data': {
'id': '1'
}
}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
keywords = ['data', 'in linkage', 'relationship', '"articles"',
'must be a list']
check_sole_error(response, 400, keywords)
def test_to_many_relationship_conflicting_type(self):
"""Tests that the server rejects a request to create a resource
with a to-many relationship when any of the relationship linkage
objects has a ``type`` element that conflicts with the actual
type of the related resource.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'person',
'relationships': {
'articles': {
'data': [
{
'id': '1',
'type': 'person'
}
]
}
}
}
}
response = self.app.post('/api/person', data=dumps(data))
keywords = ['deserialize', 'expected', 'type', '"article"', '"person"',
'linkage object', 'relationship', '"articles"']
check_sole_error(response, 409, keywords)
def test_special_field_names(self):
"""Test that an attribute can have the name "type".
For more information, see issue #559.
"""
data = {
'data': {
'type': 'article',
'attributes': {
'type': u'fluff'
}
}
}
response = self.app.post('/api/article', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
article = document['data']
assert article['type'] == 'article'
assert article['attributes']['type'] == u'fluff'
class TestProcessors(ManagerTestBase):
"""Tests for pre- and postprocessors."""
def setUp(self):
super(TestProcessors, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Person = Person
self.Base.metadata.create_all()
def test_preprocessor(self):
"""Tests :http:method:`post` requests with a preprocessor function."""
def set_name(data=None, **kw):
"""Sets the name attribute of the incoming data object, regardless
of the value requested by the client.
"""
if data is not None:
data['data']['attributes']['name'] = u'bar'
preprocessors = dict(POST_RESOURCE=[set_name])
self.manager.create_api(self.Person, methods=['POST'],
preprocessors=preprocessors)
data = dict(data=dict(type='person', attributes=dict(name=u'foo')))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
assert person['attributes']['name'] == 'bar'
def test_postprocessor(self):
"""Tests that a postprocessor is invoked when creating a resource."""
def modify_result(result=None, **kw):
result['foo'] = 'bar'
postprocessors = dict(POST_RESOURCE=[modify_result])
self.manager.create_api(self.Person, methods=['POST'],
postprocessors=postprocessors)
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
assert document['foo'] == 'bar'
def test_postprocessor_no_commit_on_error(self):
"""Tests that a processing exception causes the session to be
flushed but not committed.
"""
def raise_error(**kw):
raise ProcessingException(status=500)
postprocessors = dict(POST_RESOURCE=[raise_error])
self.manager.create_api(self.Person, methods=['POST'],
postprocessors=postprocessors)
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 500
person_count = self.session.query(self.Person).count()
assert person_count == 1
self.session.rollback()
person_count = self.session.query(self.Person).count()
assert person_count == 0
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
"""Tests for creating resources defined as Flask-SQLAlchemy models instead
of pure SQLAlchemy models.
"""
def setUp(self):
"""Creates the Flask-SQLAlchemy database and models."""
super(TestFlaskSQLAlchemy, self).setUp()
class Person(self.db.Model):
id = self.db.Column(self.db.Integer, primary_key=True)
self.Person = Person
self.db.create_all()
self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
self.manager.create_api(self.Person, methods=['POST'])
def test_create(self):
"""Tests for creating a resource."""
data = dict(data=dict(type='person'))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
person = document['data']
# TODO To make this test more robust, should query for person objects.
assert person['id'] == '1'
assert person['type'] == 'person'
| 37,830
|
Python
|
.py
| 861
| 32.708479
| 79
| 0.572658
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,654
|
test_associationproxy.py
|
jfinkels_flask-restless/tests/test_associationproxy.py
|
# -*- encoding: utf-8 -*-
# test_creating.py - unit tests for creating resources
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for interacting with association proxies.
The tests in this module use model attributes defined using `association
proxies`_.
.. _association proxies:
http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html
"""
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import ForeignKey
from sqlalchemy import Table
from sqlalchemy import Unicode
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relationship
from .helpers import dumps
from .helpers import loads
from .helpers import ManagerTestBase
class TestAssociationObject(ManagerTestBase):
"""Tests for association proxy with an association object."""
def setUp(self):
super(TestAssociationObject, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
articletags = relationship('ArticleTag',
cascade='all, delete-orphan')
tags = association_proxy('articletags', 'tag',
creator=lambda tag: ArticleTag(tag=tag))
class ArticleTag(self.Base):
__tablename__ = 'articletag'
article_id = Column(Integer, ForeignKey('article.id'),
primary_key=True)
tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True)
tag = relationship('Tag')
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Article = Article
self.ArticleTag = ArticleTag
self.Tag = Tag
self.Base.metadata.create_all()
def test_fetching(self):
"""Test for fetching a resource that has a many-to-many relation that
uses an association object with an association proxy.
We serialize an association proxy that proxies a collection of
model instances via an association object as a relationship.
"""
self.manager.create_api(self.Article)
self.manager.create_api(self.ArticleTag)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag = self.Tag(id=1)
article.tags = [tag]
self.session.add_all([article, tag])
self.session.commit()
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
articletags = article['relationships']['articletags']['data']
self.assertEqual(len(articletags), 1)
articletag = articletags[0]
self.assertEqual(articletag['type'], 'articletag')
self.assertEqual(articletag['id'], '1')
tags = article['relationships']['tags']['data']
self.assertEqual(len(tags), 1)
tag = tags[0]
self.assertEqual(tag['type'], 'tag')
self.assertEqual(tag['id'], '1')
def test_creating(self):
"""Test for creating a resource with an assocation object."""
self.manager.create_api(self.Article, methods=['POST'],
exclude=['articletags'])
self.manager.create_api(self.Tag)
tag = self.Tag(id=1)
self.session.add(tag)
self.session.commit()
data = {
'data': {
'type': 'article',
'relationships': {
'tags': {
'data': [
{'type': 'tag', 'id': '1'},
]
}
}
}
}
response = self.app.post('/api/article', data=dumps(data))
self.assertEqual(response.status_code, 201)
# Check that the response includes the resource identifiers for
# the `tags` relationship.
document = loads(response.data)
article = document['data']
tags = article['relationships']['tags']['data']
self.assertEqual(tags, [{'type': 'tag', 'id': '1'}])
# Check that the Article object has been created and has the
# appropriate tags.
self.assertEqual(self.session.query(self.Article).count(), 1)
article = self.session.query(self.Article).first()
self.assertEqual(article.tags, [tag])
def test_updating(self):
"""Test for updating a to-many relationship via association proxy."""
self.manager.create_api(self.Article, methods=['PATCH'],
allow_to_many_replacement=True)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag = self.Tag(id=1)
self.session.add_all([article, tag])
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
'relationships': {
'tags': {
'data': [
{'type': 'tag', 'id': '1'},
]
}
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [tag])
def test_deleting(self):
"""Test for deleting a resource with a to-many relationship."""
self.manager.create_api(self.Article, methods=['DELETE'])
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag = self.Tag(id=1)
article.tags = [tag]
self.session.add_all([article, tag])
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
}
}
response = self.app.delete('/api/article/1', data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual([tag], self.session.query(self.Tag).all())
def test_fetch_relationships(self):
"""Test for fetching to-many relationship resource identifiers."""
self.manager.create_api(self.Article)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag = self.Tag(id=1)
article.tags = [tag]
self.session.add_all([article, tag])
self.session.commit()
response = self.app.get('/api/article/1/relationships/tags')
document = loads(response.data)
tags = document['data']
self.assertEqual(['1'], sorted(tag['id'] for tag in tags))
def test_adding_to_relationship(self):
"""Test for adding to a to-many relationship via association proxy."""
self.manager.create_api(self.Article, methods=['PATCH'])
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag = self.Tag(id=1)
self.session.add_all([article, tag])
self.session.commit()
data = {
'data': [
{'type': 'tag', 'id': '1'},
]
}
response = self.app.post('/api/article/1/relationships/tags',
data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [tag])
def test_removing_from_relationship(self):
"""Test for removing from a to-many relationship."""
self.manager.create_api(self.Article, methods=['PATCH'],
allow_delete_from_to_many_relationships=True)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag = self.Tag(id=1)
article.tags = [tag]
self.session.add_all([article, tag])
self.session.commit()
data = {
'data': [
{'type': 'tag', 'id': '1'},
]
}
response = self.app.delete('/api/article/1/relationships/tags',
data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [])
def test_replacing_relationship(self):
"""Test for replacing a to-many relationship via association proxy."""
self.manager.create_api(self.Article, methods=['PATCH'],
allow_to_many_replacement=True)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag1 = self.Tag(id=1)
tag2 = self.Tag(id=2)
article.tags = [tag1]
self.session.add_all([article, tag1, tag2])
self.session.commit()
data = {
'data': [
{'type': 'tag', 'id': '2'},
]
}
response = self.app.patch('/api/article/1/relationships/tags',
data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [tag2])
class TestAssociationTable(ManagerTestBase):
"""Tests for association proxy with an association table."""
def setUp(self):
super(TestAssociationTable, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
tags = relationship('Tag', secondary=lambda: articletags_table)
tag_names = association_proxy('tags', 'name',
creator=lambda s: Tag(name=s))
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
articletags_table = \
Table('articletags', self.Base.metadata,
Column('article_id', Integer, ForeignKey('article.id'),
primary_key=True),
Column('tag_id', Integer, ForeignKey('tag.id'),
primary_key=True))
self.Article = Article
self.Tag = Tag
self.Base.metadata.create_all()
def test_fetching(self):
"""Tests for fetching an association proxy to scalars as a list
attribute instead of a link object.
We serialize an association proxy that proxies a collection of
scalar values via an association table as a JSON list.
"""
self.manager.create_api(self.Article)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
article.tag_names = [u'foo', u'bar']
self.session.add(article)
self.session.commit()
# By default, both the `tags` relationship and the `tag_names`
# attributes are exposed.
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
tag_names = sorted(article['attributes']['tag_names'])
self.assertEqual(tag_names, [u'bar', u'foo'])
tags = article['relationships']['tags']['data']
self.assertEqual([u'1', u'2'], sorted(tag['id'] for tag in tags))
self.assertTrue(all(tag['type'] == u'tag' for tag in tags))
def test_creating(self):
"""Tests for creating with an association proxy to a scalar list."""
self.manager.create_api(self.Article, methods=['POST'])
self.manager.create_api(self.Tag)
data = {
'data': {
'type': 'article',
'attributes': {
'tag_names': [u'foo', u'bar']
}
}
}
response = self.app.post('/api/article', data=dumps(data))
self.assertEqual(response.status_code, 201)
# Check that the response includes the `tag_names` attribute.
document = loads(response.data)
article = document['data']
self.assertEqual(article['attributes']['tag_names'], [u'foo', u'bar'])
# Check that the Article object has been created and has the tag names.
self.assertEqual(self.session.query(self.Article).count(), 1)
article = self.session.query(self.Article).first()
self.assertEqual(article.tag_names, [u'foo', u'bar'])
def test_updating(self):
"""Tests for updating an association proxy to a scalar list."""
self.manager.create_api(self.Article, methods=['PATCH'])
article = self.Article(id=1)
article.tag_names = [u'foo', u'bar']
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
'attributes': {
'tag_names': [u'baz', u'xyzzy']
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tag_names, [u'baz', u'xyzzy'])
def test_deleting(self):
"""Test for deleting a resource with a to-many relationship."""
self.manager.create_api(self.Article, methods=['DELETE'])
article = self.Article(id=1)
article.tag_names = [u'foo', u'bar']
self.session.add(article)
self.session.commit()
data = {
'data': {
'type': 'article',
'id': '1',
}
}
response = self.app.delete('/api/article/1', data=dumps(data))
self.assertEqual(response.status_code, 204)
tags = self.session.query(self.Tag).all()
self.assertEqual([u'bar', u'foo'], sorted(tag.name for tag in tags))
def test_fetch_relationships(self):
"""Test for fetching to-many relationship resource identifiers."""
self.manager.create_api(self.Article)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
article.tag_names = [u'foo', u'bar']
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1/relationships/tags')
self.assertEqual(response.status_code, 200)
document = loads(response.data)
tags = document['data']
self.assertEqual([u'1', u'2'], sorted(tag['id'] for tag in tags))
self.assertTrue(all(tag['type'] == u'tag' for tag in tags))
def test_adding_to_relationship(self):
"""Test for adding to a to-many relationship via association proxy."""
self.manager.create_api(self.Article, methods=['PATCH'])
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag1 = self.Tag(id=1)
tag2 = self.Tag(id=2)
self.session.add_all([article, tag1, tag2])
self.session.commit()
data = {
'data': [
{'type': 'tag', 'id': '1'},
{'type': 'tag', 'id': '2'},
]
}
response = self.app.post('/api/article/1/relationships/tags',
data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [tag1, tag2])
def test_removing_from_relationship(self):
"""Test for removing from a to-many relationship."""
self.manager.create_api(self.Article, methods=['PATCH'],
allow_delete_from_to_many_relationships=True)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag1 = self.Tag(id=1)
tag2 = self.Tag(id=2)
article.tags = [tag1, tag2]
self.session.add_all([article, tag1, tag2])
self.session.commit()
data = {
'data': [
{'type': 'tag', 'id': '1'},
]
}
response = self.app.delete('/api/article/1/relationships/tags',
data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [tag2])
def test_replacing_relationship(self):
"""Test for replacing a to-many relationship via association proxy."""
self.manager.create_api(self.Article, methods=['PATCH'],
allow_to_many_replacement=True)
self.manager.create_api(self.Tag)
article = self.Article(id=1)
tag1 = self.Tag(id=1)
tag2 = self.Tag(id=2)
article.tags = [tag1]
self.session.add_all([article, tag1, tag2])
self.session.commit()
data = {
'data': [
{'type': 'tag', 'id': '2'},
]
}
response = self.app.patch('/api/article/1/relationships/tags',
data=dumps(data))
self.assertEqual(response.status_code, 204)
self.assertEqual(article.tags, [tag2])
| 17,128
|
Python
|
.py
| 401
| 31.778055
| 79
| 0.574637
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,655
|
test_validation.py
|
jfinkels_flask-restless/tests/test_validation.py
|
# test_validation.py - unit tests for model validation
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for SQLAlchemy models that include some validation
functionality and therefore raise validation errors on requests to
update resources.
Validation is not provided by Flask-Restless itself, but we still need
to test that it captures validation errors and returns them to the
client.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalchemy.orm import validates
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import loads
from .helpers import ManagerTestBase
class CoolValidationError(Exception):
"""Raised when there is a validation error.
This is used for testing validation errors only.
"""
pass
class TestSimpleValidation(ManagerTestBase):
"""Tests for validation errors raised by the SQLAlchemy's simple built-in
validation.
For more information about this functionality, see the documentation for
:func:`sqlalchemy.orm.validates`.
"""
def setUp(self):
"""Create APIs for the validated models."""
super(TestSimpleValidation, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
age = Column(Integer, nullable=False)
@validates('age')
def validate_age(self, key, number):
if not 0 <= number <= 150:
exception = CoolValidationError()
exception.errors = dict(age='Must be between 0 and 150')
raise exception
return number
@validates('articles')
def validate_articles(self, key, article):
if article.title is not None and len(article.title) == 0:
exception = CoolValidationError()
exception.errors = {'articles': 'empty title not allowed'}
raise exception
return article
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
article_id = Column(Integer, ForeignKey('article.id'),
nullable=False)
article = relationship(Article)
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Comment, methods=['PATCH'])
self.manager.create_api(Person, methods=['POST', 'PATCH'],
validation_exceptions=[CoolValidationError])
def test_create_valid(self):
"""Tests that an attempt to create a valid resource yields no error
response.
"""
data = {
'data': {
'type': 'person',
'attributes': {
'age': 1
}
}
}
response = self.app.post('/api/person', data=dumps(data))
self.assertEqual(response.status_code, 201)
document = loads(response.data)
person = document['data']
self.assertEqual(person['attributes']['age'], 1)
def test_create_invalid(self):
"""Tests that an attempt to create an invalid resource yields an error
response.
"""
data = {
'data': {
'type': 'person',
'attributes': {
'age': -1
}
}
}
response = self.app.post('/api/person', data=dumps(data))
check_sole_error(response, 400, ['age', 'Must be between'])
self.assertEqual(self.session.query(self.Person).count(), 0)
def test_update_valid(self):
"""Tests that an attempt to update a resource with valid data yields no
error response.
"""
person = self.Person(id=1, age=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'age': 2
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 204
assert person.age == 2
def test_update_invalid(self):
"""Tests that an attempt to update a resource with an invalid
attribute yields an error response.
"""
person = self.Person(id=1, age=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'id': '1',
'type': 'person',
'attributes': {
'age': -1
}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
check_sole_error(response, 400, ['age', 'Must be between'])
# Check that the person was not updated.
assert person.age == 1
def test_update_relationship_invalid(self):
"""Tests that an attempt to update a resource with an invalid
relationship yields an error response.
"""
article = self.Article(id=1)
comment = self.Comment(id=1)
comment.article = article
self.session.add_all([comment, article])
self.session.commit()
data = {
'data': {
'id': '1',
'type': 'comment',
'relationships': {
'article': {
'data': None
}
}
}
}
response = self.app.patch('/api/comment/1', data=dumps(data))
assert response.status_code == 400
document = loads(response.data)
errors = document['errors']
assert len(errors) == 1
error = errors[0]
assert error['title'] == 'Integrity Error'
assert 'null' in error['detail'].lower()
# Check that the relationship was not updated.
assert comment.article == article
def test_adding_to_relationship_invalid(self):
"""Tests that an attempt to add to a relationship with invalid
data yields an error response.
"""
person = self.Person(id=1, age=1)
article = self.Article(id=1, title=u'')
self.session.add_all([person, article])
self.session.commit()
data = {'data': [{'type': 'article', 'id': 1}]}
response = self.app.post('/api/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 400
document = loads(response.data)
errors = document['errors']
error = errors[0]
assert 'validation' in error['title'].lower()
assert 'empty title not allowed' in error['detail'].lower()
# Check that the relationship was not updated.
assert article.author is None
def test_updating_relationship_invalid(self):
"""Tests that an attempt to update a relationship with invalid
data yields an error response.
"""
person = self.Person(id=1, age=1)
article = self.Article(id=1, title=u'')
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
allow_to_many_replacement=True,
url_prefix='/api2',
validation_exceptions=[CoolValidationError])
data = {'data': [{'type': 'article', 'id': 1}]}
response = self.app.patch('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 400
document = loads(response.data)
errors = document['errors']
error = errors[0]
assert 'validation' in error['title'].lower()
assert 'empty title not allowed' in error['detail'].lower()
# Check that the relationship was not updated.
assert person.articles == []
| 8,987
|
Python
|
.py
| 224
| 29.660714
| 79
| 0.581491
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,656
|
test_updatingrelationship.py
|
jfinkels_flask-restless/tests/test_updatingrelationship.py
|
# test_updatingrelationship.py - unit tests for updating relationships
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for updating relationships via relationship URLs.
This module includes tests for additional functionality that is not
already tested by :mod:`test_jsonapi`, the package that guarantees
Flask-Restless meets the minimum requirements of the JSON API
specification.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from flask_restless import ProcessingException
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import ManagerTestBase
class TestAdding(ManagerTestBase):
"""Tests for adding to a resource's to-many relationship via the
relationship URL.
"""
def setUp(self):
super(TestAdding, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person, methods=['PATCH'])
def test_nonexistent_instance(self):
"""Tests that an attempt to POST to a relationship URL for a resource
that doesn't exist yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
data = dumps(data)
response = self.app.post('/api/person/bogus/relationships/articles',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_nonexistent_relation(self):
"""Tests that an attempt to POST to a relationship URL for a
nonexistent relation yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=dict(id=1, type='bogus'))
response = self.app.post('/api/person/1/relationships/bogus',
data=dumps(data))
assert response.status_code == 404
# TODO check error message here
def test_missing_relation(self):
"""Tests that an attempt to POST to a relationship URL without
specifying a relationship yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.post('/api/person/1/relationships',
data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_missing_id(self):
"""Tests that providing a linkage object without an ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(type='article')])
data = dumps(data)
response = self.app.post('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_missing_type(self):
"""Tests that providing a linkage object without a resource type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1)])
data = dumps(data)
response = self.app.post('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_conflicting_type(self):
"""Tests that providing a linkage object with an incorrect type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='bogus')])
data = dumps(data)
response = self.app.post('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 409
# TODO check error message here
def test_nonexistent_linkage(self):
"""Tests that an attempt to POST to a relationship URL with a linkage
object that has an unknown ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id='bogus', type='article')])
data = dumps(data)
response = self.app.post('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_empty_request(self):
"""Test that attempting to POST to a relationship URL with no data
yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.post('/api/person/1/relationships/articles')
assert response.status_code == 400
# TODO check the error message here
def test_empty_string(self):
"""Test that attempting to POST to a relationship URL with an empty
string (which is invalid JSON) yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.post('/api/person/1/relationships/articles',
data='')
assert response.status_code == 400
# TODO check the error message here
def test_invalid_json(self):
"""Test that attempting to POST to a relationship URL with invalid JSON
yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = 'Invalid JSON string'
response = self.app.post('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_preprocessor(self):
"""Test that a preprocessor is triggered on a request to add to
a to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'POST_RELATIONSHIP': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors,
url_prefix='/api2', methods=['PATCH'])
data = {'data': [{'type': 'article', 'id': '1'}]}
# The preprocessor will change the resource ID and the
# relationship name.
self.app.post('/api2/person/1/relationships/articles',
data=dumps(data))
assert data['triggered']
def test_change_two_preprocessor(self):
"""Test for a preprocessor that changes both the primary
resource ID and the relation name from the ones given in the
requested URL.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
def change_two(*args, **kw):
return 1, 'articles'
preprocessors = {'POST_RELATIONSHIP': [change_two]}
self.manager.create_api(self.Person, preprocessors=preprocessors,
url_prefix='/api2', methods=['PATCH'])
data = {'data': [{'type': 'article', 'id': '1'}]}
# The preprocessor will change the resource ID and the
# relationship name.
response = self.app.post('/api2/person/bogus1/relationships/bogus2',
data=dumps(data))
assert response.status_code == 204
assert article.author is person
def test_postprocessor(self):
"""Tests that a postprocessor gets executing when adding a link
to a to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
has_run = []
def enable_flag(*args, **kw):
has_run.append(True)
postprocessors = {'POST_RELATIONSHIP': [enable_flag]}
self.manager.create_api(self.Person, postprocessors=postprocessors,
url_prefix='/api2', methods=['PATCH'])
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.post('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert has_run == [True]
def test_postprocessor_no_commit_on_error(self):
"""Tests that a processing exception causes the session to be
flushed but not committed.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
def raise_error(**kw):
raise ProcessingException(status=500)
postprocessors = {'POST_RELATIONSHIP': [raise_error]}
self.manager.create_api(self.Person, postprocessors=postprocessors,
url_prefix='/api2', methods=['PATCH'])
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.post('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 500
assert article.author is person
self.session.rollback()
assert article.author is not person
class TestDeleting(ManagerTestBase):
"""Tests for deleting a link from a resource's to-many relationship via the
relationship URL.
"""
def setUp(self):
super(TestDeleting, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Person, methods=['PATCH'],
allow_delete_from_to_many_relationships=True)
self.manager.create_api(Article)
def test_nonexistent_instance(self):
"""Tests that an attempt to delete from a relationship URL for a
resource that doesn't exist yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.delete('/api/person/bogus/relationships/articles',
data=dumps(data))
assert response.status_code == 404
# TODO check error message here
def test_nonexistent_relation(self):
"""Tests that an attempt to delete from a relationship URL for a
nonexistent relation yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=dict(id=1, type='bogus'))
data = dumps(data)
response = self.app.delete('/api/person/1/relationships/bogus',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_missing_relation(self):
"""Tests that an attempt to delete from a relationship URL without
specifying a relationship yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.delete('/api/person/1/relationships',
data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_missing_id(self):
"""Tests that providing a linkage object without an ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(type='article')])
data = dumps(data)
response = self.app.delete('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_missing_type(self):
"""Tests that providing a linkage object without a resource type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1)])
data = dumps(data)
response = self.app.delete('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_conflicting_type(self):
"""Tests that providing a linkage object with an incorrect type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='bogus')])
data = dumps(data)
response = self.app.delete('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 409
# TODO check error message here
def test_nonexistent_linkage(self):
"""Tests that an attempt to delete from a relationship URL with a
linkage object that has an unknown ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id='bogus', type='article')])
data = dumps(data)
response = self.app.delete('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_empty_request(self):
"""Test that attempting to delete from a relationship URL with no data
yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.delete('/api/person/1/relationships/articles')
assert response.status_code == 400
# TODO check the error message here
def test_empty_string(self):
"""Test that attempting to delete from a relationship URL with an empty
string (which is invalid JSON) yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.delete('/api/person/1/relationships/articles',
data='')
assert response.status_code == 400
# TODO check the error message here
def test_invalid_json(self):
"""Test that attempting to delete from a relationship URL with invalid
JSON yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = 'Invalid JSON string'
response = self.app.delete('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_preprocessor(self):
"""Test that a preprocessor is triggered on a request to delete
from a to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'DELETE_RELATIONSHIP': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_delete_from_to_many_relationships=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
# The preprocessor will change the resource ID and the
# relationship name.
self.app.delete('/api2/person/1/relationships/articles',
data=dumps(data))
assert data['triggered']
def test_change_id_preprocessor(self):
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def change_id(*args, **kw):
return 1
preprocessors = {'DELETE_RELATIONSHIP': [change_id]}
self.manager.create_api(self.Person, preprocessors=preprocessors,
allow_delete_from_to_many_relationships=True,
url_prefix='/api2', methods=['PATCH'])
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.delete('/api2/person/bogus/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert article.author is None
def test_postprocessor(self):
"""Tests that a postprocessor gets executing when deleting from
a to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
has_run = []
def enable_flag(was_deleted=None, *args, **kw):
has_run.append(was_deleted)
postprocessors = {'DELETE_RELATIONSHIP': [enable_flag]}
self.manager.create_api(self.Person, postprocessors=postprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_delete_from_to_many_relationships=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.delete('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert has_run == [True]
def test_postprocessor_no_commit_on_error(self):
"""Tests that a processing exception causes the session to be
flushed but not committed.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
def raise_error(**kw):
raise ProcessingException(status=500)
postprocessors = {'DELETE_RELATIONSHIP': [raise_error]}
self.manager.create_api(self.Person, postprocessors=postprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_delete_from_to_many_relationships=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.delete('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 500
assert article.author is not person
self.session.rollback()
assert article.author is person
class TestUpdatingToMany(ManagerTestBase):
"""Tests for updating a resource's to-many relationship via the
relationship URL.
"""
def setUp(self):
super(TestUpdatingToMany, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Person, methods=['PATCH'],
allow_to_many_replacement=True)
self.manager.create_api(Article)
def test_nonexistent_instance(self):
"""Tests that an attempt to update a relationship for a resource that
doesn't exist yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.patch('/api/person/bogus/relationships/articles',
data=dumps(data))
assert response.status_code == 404
# TODO check error message here
def test_nonexistent_relation(self):
"""Tests that an attempt to update a relationship for a nonexistent
relation yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=[dict(id=1, type='bogus')])
data = dumps(data)
response = self.app.patch('/api/person/1/relationships/bogus',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_missing_relation(self):
"""Tests that an attempt to update a relationship without specifying a
relationship in the URL yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='article')])
response = self.app.patch('/api/person/1/relationships',
data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_missing_id(self):
"""Tests that providing a linkage object without an ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(type='article')])
data = dumps(data)
response = self.app.patch('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_missing_type(self):
"""Tests that providing a linkage object without a resource type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1)])
data = dumps(data)
response = self.app.patch('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_conflicting_type(self):
"""Tests that providing a linkage object with an incorrect type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id=1, type='bogus')])
data = dumps(data)
response = self.app.patch('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 409
# TODO check error message here
def test_nonexistent_linkage(self):
"""Tests that an attempt to update a relationship with a linkage object
that has an unknown ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=[dict(id='bogus', type='article')])
data = dumps(data)
response = self.app.patch('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_empty_request(self):
"""Test that attempting to delete from a relationship URL with no data
yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.patch('/api/person/1/relationships/articles')
assert response.status_code == 400
# TODO check the error message here
def test_empty_string(self):
"""Test that attempting to update a relationship with an empty string
(which is invalid JSON) yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.patch('/api/person/1/relationships/articles',
data='')
assert response.status_code == 400
# TODO check the error message here
def test_invalid_json(self):
"""Test that attempting to update a relationship with invalid JSON
yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = 'Invalid JSON string'
response = self.app.patch('/api/person/1/relationships/articles',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_preprocessor(self):
"""Test that a preprocessor is triggered on a request to update
a to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
data = {'triggered': False}
def update_data(*args, **kw):
data['triggered'] = True
preprocessors = {'PATCH_RELATIONSHIP': [update_data]}
self.manager.create_api(self.Person, preprocessors=preprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_to_many_replacement=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
# The preprocessor will change the resource ID and the
# relationship name.
self.app.patch('/api2/person/1/relationships/articles',
data=dumps(data))
assert data['triggered']
def test_change_two_preprocessor(self):
"""Test for a preprocessor that changes both the primary
resource ID and the relation name from the ones given in the
requested URL.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
def change_two(*args, **kw):
return 1, 'articles'
preprocessors = {'PATCH_RELATIONSHIP': [change_two]}
self.manager.create_api(self.Person, preprocessors=preprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_to_many_replacement=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
# The preprocessor will change the resource ID and the
# relationship name.
response = self.app.patch('/api2/person/bogus1/relationships/bogus2',
data=dumps(data))
assert response.status_code == 204
assert person.articles == [article]
def test_postprocessor(self):
"""Tests that a postprocessor gets executing when replacing a
to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
has_run = []
def enable_flag(*args, **kw):
has_run.append(True)
postprocessors = {'PATCH_RELATIONSHIP': [enable_flag]}
self.manager.create_api(self.Person, postprocessors=postprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_to_many_replacement=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.patch('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert has_run == [True]
def test_postprocessor_no_commit_on_error(self):
"""Tests that a postprocessor gets executing when deleting from
a to-many relationship.
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([article, person])
self.session.commit()
def raise_error(**kw):
raise ProcessingException(status=500)
postprocessors = {'PATCH_RELATIONSHIP': [raise_error]}
self.manager.create_api(self.Person, postprocessors=postprocessors,
url_prefix='/api2', methods=['PATCH'],
allow_to_many_replacement=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.patch('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 500
assert article.author is person
self.session.rollback()
assert article.author is not person
def test_set_null(self):
"""Tests that an attempt to set a null value on a to-many
relationship causes an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {'data': None}
response = self.app.patch('/api/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 400
# TODO Check error message here.
class TestUpdatingToOne(ManagerTestBase):
"""Tests for updating a resource's to-one relationship via the relationship
URL.
"""
def setUp(self):
super(TestUpdatingToOne, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article, methods=['PATCH'])
self.manager.create_api(Person)
def test_nonexistent_instance(self):
"""Tests that an attempt to update a relationship for a resource that
doesn't exist yields an error.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=dict(id=1, type='person'))
response = self.app.patch('/api/article/bogus/relationships/author',
data=dumps(data))
assert response.status_code == 404
# TODO check error message here
def test_nonexistent_relation(self):
"""Tests that an attempt to update a relationship for a nonexistent
relation yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = dict(data=dict(id=1, type='bogus'))
data = dumps(data)
response = self.app.patch('/api/article/1/relationships/bogus',
data=data)
assert response.status_code == 404
# TODO check error message here
def test_missing_relation(self):
"""Tests that an attempt to update a relationship without specifying a
relationship in the URL yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(id=1, type='person'))
response = self.app.patch('/api/article/1/relationships',
data=dumps(data))
assert response.status_code == 405
# TODO check error message here
def test_missing_id(self):
"""Tests that providing a linkage object without an ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(type='person'))
data = dumps(data)
response = self.app.patch('/api/article/1/relationships/author',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_missing_type(self):
"""Tests that providing a linkage object without a resource type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(id=1))
data = dumps(data)
response = self.app.patch('/api/article/1/relationships/author',
data=data)
assert response.status_code == 400
# TODO check error message here
def test_conflicting_type(self):
"""Tests that providing a linkage object with an incorrect type yields
an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(id=1, type='bogus'))
data = dumps(data)
response = self.app.patch('/api/article/1/relationships/author',
data=data)
assert response.status_code == 409
# TODO check error message here
def test_nonexistent_linkage(self):
"""Tests that an attempt to update a relationship with a linkage object
that has an unknown ID yields an error.
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
data = dict(data=dict(id='bogus', type='person'))
data = dumps(data)
response = self.app.patch('/api/article/1/relationships/author',
data=data)
check_sole_error(response, 404, ['No resource', 'found', 'type',
'person', 'ID', 'bogus'])
def test_empty_request(self):
"""Test that attempting to delete from a relationship URL with no data
yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.patch('/api/article/1/relationships/author')
assert response.status_code == 400
# TODO check the error message here
def test_empty_string(self):
"""Test that attempting to update a relationship with an empty string
(which is invalid JSON) yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.patch('/api/article/1/relationships/author',
data='')
assert response.status_code == 400
# TODO check the error message here
def test_invalid_json(self):
"""Test that attempting to update a relationship with invalid JSON
yields an error.
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
data = 'Invalid JSON string'
response = self.app.patch('/api/article/1/relationships/author',
data=data)
assert response.status_code == 400
# TODO check error message here
| 38,540
|
Python
|
.py
| 880
| 32.976136
| 79
| 0.596948
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,657
|
helpers.py
|
jfinkels_flask-restless/tests/helpers.py
|
# helpers.py - helper functions for unit tests
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Helper functions for unit tests."""
from datetime import date
from datetime import datetime
from datetime import time
from datetime import timedelta
from functools import wraps
import sys
import types
from unittest2 import skipUnless as skip_unless
from unittest2 import TestCase
import uuid
from flask import Flask
from flask import json
try:
import flask_sqlalchemy
from flask_sqlalchemy import SQLAlchemy
except ImportError:
has_flask_sqlalchemy = False
else:
has_flask_sqlalchemy = True
from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session as SessionBase
from sqlalchemy.types import CHAR
from sqlalchemy.types import TypeDecorator
from flask_restless import APIManager
from flask_restless import collection_name
from flask_restless import DefaultSerializer
from flask_restless import DefaultDeserializer
from flask_restless import DeserializationException
from flask_restless import JSONAPI_MIMETYPE
from flask_restless import model_for
from flask_restless import primary_key_for
from flask_restless import SerializationException
from flask_restless import serializer_for
from flask_restless import url_for
dumps = json.dumps
loads = json.loads
#: The User-Agent string for Microsoft Internet Explorer 8.
#:
#: From <http://blogs.msdn.com/b/ie/archive/2008/02/21/
#: the-internet-explorer-8-user-agent-string.aspx>.
MSIE8_UA = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'
#: The User-Agent string for Microsoft Internet Explorer 9.
#:
#: From <http://blogs.msdn.com/b/ie/archive/2010/03/23/
#: introducing-ie9-s-user-agent-string.aspx>.
MSIE9_UA = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
#: Boolean representing whether this code is being executed on Python 2.
IS_PYTHON2 = (sys.version_info[0] == 2)
#: Tuple of objects representing types.
CLASS_TYPES = (types.TypeType, types.ClassType) if IS_PYTHON2 else (type, )
#: Global helper functions used by Flask-Restless
GLOBAL_FUNCS = [model_for, url_for, collection_name, serializer_for,
primary_key_for]
class raise_s_exception(DefaultSerializer):
"""A serializer that unconditionally raises an exception when
either :meth:`.serialize` or :meth:`.serialize_many` is called.
This class is useful for tests of serialization exceptions.
"""
def serialize(self, instance, *args, **kw):
"""Immediately raises a :exc:`SerializationException` with
access to the provided `instance` of a SQLAlchemy model.
"""
raise SerializationException(instance)
def serialize_many(self, instances, *args, **kw):
"""Immediately raises a :exc:`SerializationException`.
This function requires `instances` to be non-empty.
"""
raise SerializationException(instances[0])
class raise_d_exception(DefaultDeserializer):
"""A deserializer that unconditionally raises an exception when
either :meth:`.deserialize` or :meth:`.deserialize_many` is called.
This class is useful for tests of deserialization exceptions.
"""
def deserialize(self, *args, **kw):
"""Immediately raises a :exc:`DeserializationException`."""
raise DeserializationException
def deserialize_many(self, *args, **kw):
"""Immediately raises a :exc:`DeserializationException`."""
raise DeserializationException
def isclass(obj):
"""Returns ``True`` if and only if the specified object is a type (or a
class).
"""
return isinstance(obj, CLASS_TYPES)
def parse_version(version_string):
"""Parses the Flask-SQLAlchemy version string into a pair of
integers.
"""
# First, check for '-dev' suffix.
split_on_hyphen = version_string.split('-')
version_string = split_on_hyphen[0]
return tuple(int(n) for n in version_string.split('.'))
def unregister_fsa_session_signals():
"""Unregisters Flask-SQLAlchemy session commit and rollback signal
handlers.
When a Flask-SQLAlchemy object is created, it registers signal handlers for
``before_commit``, ``after_commit``, and ``after_rollback`` signals. In
case of using both a plain SQLAlchemy session and a Flask-SQLAlchemy
session (as is happening in the tests in this package), we need to
unregister handlers or there will be some exceptions during test
executions like::
AttributeError: 'Session' object has no attribute '_model_changes'
"""
# We don't need to do this if Flask-SQLAlchemy is not installed.
if not has_flask_sqlalchemy:
return
# We don't need to do this if Flask-SQLAlchemy version 2.0 or
# greater is installed.
version = parse_version(flask_sqlalchemy.__version__)
if version >= (2, 0):
return
events = flask_sqlalchemy._SessionSignalEvents
signal_names = ('before_commit', 'after_commit', 'after_rollback')
for signal_name in signal_names:
# For Flask-SQLAlchemy version less than 3.0.
signal = getattr(events, 'session_signal_{0}'.format(signal_name))
event.remove(SessionBase, signal_name, signal)
def check_sole_error(response, status, strings):
"""Asserts that the response is an errors response with a single
error object whose detail message contains all of the given strings.
`strings` may also be a single string object to check.
`status` is the expected status code for the sole error object in
the response.
"""
if isinstance(strings, str):
strings = [strings]
assert response.status_code == status
document = loads(response.data)
errors = document['errors']
assert len(errors) == 1
error = errors[0]
assert error['status'] == status
assert all(s in error['detail'] for s in strings)
def force_content_type_jsonapi(test_client):
"""Ensures that all requests made by the specified Flask test client
that include data have the correct :http:header:`Content-Type`
header.
"""
def set_content_type(func):
"""Returns a decorated version of ``func``, as described in the
wrapper defined below.
"""
@wraps(func)
def new_func(*args, **kw):
"""Sets the correct :http:header:`Content-Type` headers
before executing ``func(*args, **kw)``.
"""
# if 'content_type' not in kw:
# kw['content_type'] = CONTENT_TYPE
if 'headers' not in kw:
kw['headers'] = dict()
headers = kw['headers']
if 'content_type' not in kw and 'Content-Type' not in headers:
kw['content_type'] = JSONAPI_MIMETYPE
return func(*args, **kw)
return new_func
# Decorate the appropriate test client request methods.
test_client.patch = set_content_type(test_client.patch)
test_client.post = set_content_type(test_client.post)
# This code is adapted from
# http://docs.sqlalchemy.org/en/latest/core/custom_types.html#backend-agnostic-guid-type
class GUID(TypeDecorator):
"""Platform-independent GUID type.
Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as
stringified hex values.
"""
impl = CHAR
def load_dialect_impl(self, dialect):
descriptor = UUID() if dialect.name == 'postgresql' else CHAR(32)
return dialect.type_descriptor(descriptor)
def process_bind_param(self, value, dialect):
if value is None:
return None
if dialect.name == 'postgresql':
return str(value)
if not isinstance(value, uuid.UUID):
return uuid.UUID(value).hex
# If we get to this point, we assume `value` is a UUID object.
return value.hex
def process_result_value(self, value, dialect):
if value is None:
return None
return uuid.UUID(value)
# In versions of Flask before 0.11, datetime and time objects are not
# serializable by default so we need to create a custom JSON encoder class.
#
# TODO When Flask 0.11 is required, remove this.
class BetterJSONEncoder(json.JSONEncoder):
"""Extends the default JSON encoder to serialize objects from the
:mod:`datetime` module.
"""
def default(self, obj):
if isinstance(obj, (date, datetime, time)):
return obj.isoformat()
if isinstance(obj, timedelta):
return int(obj.days * 86400 + obj.seconds)
return super(BetterJSONEncoder, self).default(obj)
class FlaskTestBase(TestCase):
"""Base class for tests which use a Flask application.
The Flask test client can be accessed at ``self.app``. The Flask
application itself is accessible at ``self.flaskapp``.
"""
def setUp(self):
"""Creates the Flask application and the APIManager."""
# create the Flask application
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['TESTING'] = True
# The SERVER_NAME is required by `manager.url_for()` in order to
# construct absolute URLs.
app.config['SERVER_NAME'] = 'localhost:5000'
app.logger.disabled = True
self.flaskapp = app
# create the test client
self.app = app.test_client()
force_content_type_jsonapi(self.app)
class DatabaseMixin(object):
"""A class that accesses a database via a connection URI.
Subclasses can override the :meth:`database_uri` method to return a
connection URI for the desired database backend.
"""
def database_uri(self):
"""The database connection URI to use for the SQLAlchemy engine.
By default, this returns the URI for the SQLite in-memory
database. Subclasses that wish to use a different SQL backend
should override this method so that it returns the desired URI
string.
"""
return 'sqlite://'
@skip_unless(has_flask_sqlalchemy, 'Flask-SQLAlchemy not found')
class FlaskSQLAlchemyTestBase(FlaskTestBase, DatabaseMixin):
"""Base class for tests that use Flask-SQLAlchemy (instead of plain
old SQLAlchemy).
If Flask-SQLAlchemy is not installed, the :meth:`.setUp` method will
raise :exc:`nose.SkipTest`, so that each test method will be
skipped individually.
"""
def setUp(self):
super(FlaskSQLAlchemyTestBase, self).setUp()
# if not has_flask_sqlalchemy:
# raise SkipTest('Flask-SQLAlchemy not found.')
self.flaskapp.config['SQLALCHEMY_DATABASE_URI'] = self.database_uri()
# This is to avoid a warning in earlier versions of
# Flask-SQLAlchemy.
self.flaskapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Store some attributes for convenience and so the test methods
# read more like the tests for plain old SQLAlchemy.
self.db = SQLAlchemy(self.flaskapp)
self.session = self.db.session
def tearDown(self):
"""Drops all tables and unregisters Flask-SQLAlchemy session
signals.
"""
self.db.drop_all()
unregister_fsa_session_signals()
class SQLAlchemyTestBase(FlaskTestBase, DatabaseMixin):
"""Base class for tests that use a SQLAlchemy database.
The :meth:`setUp` method does the necessary SQLAlchemy
initialization, and the subclasses should populate the database with
models and then create the database (by calling
``self.Base.metadata.create_all()``).
By default, this class creates a SQLite database; subclasses can
override the :meth:`.database_uri` method to enable configuration of
an alternate database backend.
"""
def setUp(self):
"""Initializes the components necessary for models in a SQLAlchemy
database.
"""
super(SQLAlchemyTestBase, self).setUp()
engine = create_engine(self.database_uri(), convert_unicode=True)
self.Session = sessionmaker(autocommit=False, autoflush=False,
bind=engine)
self.session = scoped_session(self.Session)
self.Base = declarative_base()
self.Base.metadata.bind = engine
def tearDown(self):
"""Drops all tables from the temporary database."""
self.session.remove()
self.Base.metadata.drop_all()
class ManagerTestBase(SQLAlchemyTestBase):
"""Base class for tests that use a SQLAlchemy database and an
:class:`~flask_restless.APIManager`.
Nearly all test classes should subclass this class. Since we strive
to make Flask-Restless compliant with plain old SQLAlchemy first,
the default database abstraction layer used by tests in this class
will be SQLAlchemy. Test classes requiring Flask-SQLAlchemy must
instantiate their own :class:`~flask_restless.APIManager`.
The :class:`~flask_restless.APIManager` instance for use in
tests is accessible at ``self.manager``.
"""
def setUp(self):
"""Initializes an instance of
:class:`~flask_restless.APIManager` with a SQLAlchemy
session.
"""
super(ManagerTestBase, self).setUp()
self.manager = APIManager(self.flaskapp, session=self.session)
# HACK If we don't include this, there seems to be an issue with the
# globally known APIManager objects not being cleared after every test.
def tearDown(self):
"""Clear the :class:`~flask_restless.APIManager` objects
known by the global helper functions :data:`model_for`,
:data:`url_for`, etc.
"""
super(ManagerTestBase, self).tearDown()
for func in GLOBAL_FUNCS:
func.created_managers.clear()
| 14,304
|
Python
|
.py
| 325
| 37.978462
| 88
| 0.703594
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,658
|
test_filtering.py
|
jfinkels_flask-restless/tests/test_filtering.py
|
# test_filtering.py - unit tests for filtering resources in client requests
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for filtering resources in client requests."""
from datetime import date
from datetime import datetime
from datetime import time
from operator import gt
# In Python 3...
try:
from urllib.parse import unquote
# In Python 2...
except ImportError:
from urlparse import unquote
from unittest2 import skip
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import func
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import select
from sqlalchemy import Time
from sqlalchemy import Unicode
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from flask_restless import register_operator
from .helpers import check_sole_error
from .helpers import dumps
from .helpers import loads
from .helpers import ManagerTestBase
class SearchTestBase(ManagerTestBase):
"""Provides a search method that simplifies a fetch request with filtering
query parameters.
"""
def search(self, url, filters=None, single=None):
"""Convenience function for performing a filtered :http:method:`get`
request.
`url` is the ``path`` part of the URL to which the request will be
sent.
If `filters` is specified, it must be a Python list containing filter
objects. It specifies how to set the ``filter[objects]`` query
parameter.
If `single` is specified, it must be a Boolean. It specifies how to set
the ``filter[single]`` query parameter.
"""
if filters is None:
filters = []
# The value provided to the `separators` keyword argument
# minimizes whitespace.
filters_str = dumps(filters, separators=(',', ':'))
params = {'filter[objects]': filters_str}
if single is not None:
params['filter[single]'] = 1 if single else 0
return self.app.get(url, query_string=params)
class TestFiltering(SearchTestBase):
"""Tests for filtering resources.
For more information, see the `Filtering`_ section of the JSON API
specification.
.. _Filtering: http://jsonapi.org/format/#fetching-filtering
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application,
and creates the ReSTful API endpoints for the models used in the test
methods.
"""
super(TestFiltering, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
publishtime = Column(DateTime)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('articles'))
@hybrid_property
def has_comments(self):
return len(self.comments) > 0
@has_comments.expression
def has_comments(cls):
return select([func.count(self.Comment.id)]).\
where(self.Comment.article_id == cls.id).\
label('num_comments') > 0
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
age = Column(Integer)
birthday = Column(Date)
birth_datetime = Column(DateTime)
bedtime = Column(Time)
@hybrid_property
def is_minor(self):
if not hasattr(self, 'age') or self.age is None:
return False
return self.age <= 18
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
content = Column(Unicode)
article_id = Column(Integer, ForeignKey('article.id'))
article = relationship(Article, backref=backref('comments'))
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship(Person, backref=backref('comments'))
self.Article = Article
self.Person = Person
self.Comment = Comment
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
# HACK Need to create APIs for these other models because otherwise
# we're not able to create the link URLs to them.
#
# TODO Fix this by simply not creating links to related models for
# which no API has been made.
self.manager.create_api(Comment)
def test_bad_filter(self):
"""Tests that providing a bad filter parameter causes an error
response.
"""
query_string = {'filter[objects]': 'bogus'}
response = self.app.get('/api/person', query_string=query_string)
assert response.status_code == 400
# TODO check error messages here
def test_bad_filter_relation(self):
"""Tests for providing a bad filter parameter for fetching a
relation.
"""
query_string = {'filter[objects]': 'bogus'}
response = self.app.get('/api/person/1/articles',
query_string=query_string)
check_sole_error(response, 400, ['Unable to decode', 'filter object'])
def test_bad_filter_relationship(self):
"""Test for providing a bad filter parameter for fetching
relationship objects.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
query_string = {'filter[objects]': 'bogus'}
response = self.app.get('/api/person/1/relationships/articles',
query_string=query_string)
assert response.status_code == 400
# TODO check error messages here
def test_like(self):
"""Tests for filtering using the ``like`` operator."""
person1 = self.Person(name=u'Jesus')
person2 = self.Person(name=u'Mary')
person3 = self.Person(name=u'Joseph')
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='name', op='like', val='%s%')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert len(people) == 2
assert ['Jesus', 'Joseph'] == sorted(person['attributes']['name']
for person in people)
def test_single(self):
"""Tests for requiring a single resource response to a filtered
request.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='id', op='equals', val='1')]
response = self.search('/api/person', filters, single=True)
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person['id'] == '1'
def test_single_relationship(self):
"""Tests for requiring a single relationship object in a
response to a filtered request.
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
filters = [dict(name='id', op='equals', val='1')]
response = self.search('/api/person/1/relationships/articles', filters,
single=True)
assert response.status_code == 200
document = loads(response.data)
article = document['data']
# Check that this is just a resource identifier object and not a
# full resource object representing the Article.
assert ['id', 'type'] == sorted(article)
assert article['type'] == 'article'
assert article['id'] == '1'
def test_single_too_many(self):
"""Tests that requiring a single resource response returns an error if
the filtered request would have returned more than one resource.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
response = self.search('/api/person', single=True)
# TODO should this be a 404? Maybe 409 is better?
assert response.status_code == 404
# TODO check the error message here.
def test_single_too_few(self):
"""Tests that requiring a single resource response yields an error
response if the filtered request would have returned zero resources.
"""
response = self.search('/api/person', single=True)
# TODO should this be a 404? Maybe 409 is better?
assert response.status_code == 404
# TODO check the error message here.
def test_single_wrong_format(self):
"""Tests that providing an incorrectly formatted argument to
``filter[single]`` yields an error response.
"""
params = {'filter[single]': 'bogus'}
response = self.app.get('/api/person', query_string=params)
assert response.status_code == 400
# TODO check the error message here.
def test_relation_single_wrong_format(self):
"""Tests that providing an incorrectly formatted argument to
``filter[single]`` yields an error response when fetching a
relation.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
params = {'filter[single]': 'bogus'}
response = self.app.get('/api/person/1/articles', query_string=params)
assert response.status_code == 400
# TODO check the error message here.
def test_relationship_single_wrong_format(self):
"""Tests that providing an incorrectly formatted argument to
``filter[single]`` yields an error response when fetching
relationship.
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
query_string = {'filter[single]': 'bogus'}
response = self.app.get('/api/person/1/relationships/articles',
query_string=query_string)
assert response.status_code == 400
# TODO check the error message here.
def test_in_list(self):
"""Tests for a filter object checking for a field with value in a
specified list of acceptable values.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='id', op='in', val=[2, 3])]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert len(people) == 2
assert ['2', '3'] == sorted(person['id'] for person in people)
def test_any_in_to_many(self):
"""Test for filtering using the ``any`` operator with a sub-filter
object on a to-many relationship.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
comment1 = self.Comment(content=u"that's cool!", author=person1)
comment2 = self.Comment(content=u'i like turtles', author=person2)
comment3 = self.Comment(content=u'not cool dude', author=person3)
self.session.add_all([person1, person2, person3])
self.session.add_all([comment1, comment2, comment3])
self.session.commit()
# Search for any people who have comments that contain the word "cool".
filters = [dict(name='comments', op='any',
val=dict(name='content', op='like', val='%cool%'))]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1', '3'] == sorted(person['id'] for person in people)
def test_any_with_boolean(self):
"""Tests for nesting a Boolean formula under an ``any`` filter.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article1 = self.Article(id=1, publishtime=datetime(1900, 1, 1))
article2 = self.Article(id=2, publishtime=datetime(2000, 1, 1))
article1.author = person1
article2.author = person2
self.session.add_all([person1, person2, article1, article2])
self.session.commit()
# Filter by only those people that have articles published after
# 1-1-1950 and before 1-1-2050.
filters = [{
'name': 'articles',
'op': 'any',
'val': {
'and': [
{
'name': 'publishtime',
'op': '>',
'val': '1950-1-1'
},
{
'name': 'publishtime',
'op': '<',
'val': '2050-1-1'
}
]
}
}]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == [person['id'] for person in people]
def test_has_in_to_one(self):
"""Test for filtering using the ``has`` operator with a sub-filter
object on a to-one relationship.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
comment1 = self.Comment(content=u"that's cool!", author=person1)
comment2 = self.Comment(content=u"i like turtles", author=person2)
comment3 = self.Comment(content=u"not cool dude", author=person3)
self.session.add_all([person1, person2, person3])
self.session.add_all([comment1, comment2, comment3])
self.session.commit()
# Search for any comments whose author has ID equals to 1.
filters = [dict(name='author', op='has',
val=dict(name='id', op='gt', val=1))]
response = self.search('/api/comment', filters)
document = loads(response.data)
comments = document['data']
assert ['2', '3'] == sorted(comment['id'] for comment in comments)
def test_has_with_boolean(self):
"""Tests for nesting a Boolean formula under a ``has`` filter.
"""
person1 = self.Person(id=1, bedtime=time(2))
person2 = self.Person(id=2, bedtime=time(4))
article1 = self.Article(id=1)
article2 = self.Article(id=2)
article1.author = person1
article2.author = person2
self.session.add_all([person1, person2, article1, article2])
self.session.commit()
# Filter by only those articles with an author that has a
# bedtime greater than 1:00 and less than 3:00.
filters = [{
'name': 'author',
'op': 'has',
'val': {
'and': [
{
'name': 'bedtime',
'op': '>',
'val': '1:00'
},
{
'name': 'bedtime',
'op': '<',
'val': '3:00'
}
]
}
}]
response = self.search('/api/article', filters)
document = loads(response.data)
articles = document['data']
assert ['1'] == [article['id'] for article in articles]
def test_has_with_has(self):
"""Tests for nesting a ``has`` filter beneath another ``has`` filter.
"""
for i in range(5):
person = self.Person(id=i)
article = self.Article(id=i)
comment = self.Comment(id=i)
article.author = person
comment.author = person
comment.article = article
self.session.add_all([article, person, comment])
self.session.commit()
# Search for any comments whose articles have authors with id < 3.
id_filter = dict(name='id', op='lt', val=3)
author_filter = dict(name='author', op='has', val=id_filter)
article_filter = dict(name='article', op='has', val=author_filter)
filters = [article_filter]
response = self.search('/api/comment', filters)
document = loads(response.data)
comments = document['data']
assert ['0', '1', '2'] == sorted(comment['id'] for comment in comments)
def test_any_with_any(self):
"""Tests for nesting an ``any`` filter beneath another ``any`` filter.
"""
for i in range(5):
person = self.Person(id=i)
article = self.Article(id=i)
comment = self.Comment(id=i)
article.author = person
comment.author = person
comment.article = article
self.session.add_all([article, person, comment])
self.session.commit()
# Search for any people whose articles have any comment with id < 3.
id_filter = dict(name='id', op='lt', val=3)
comments_filter = dict(name='comments', op='any', val=id_filter)
articles_filter = dict(name='articles', op='any', val=comments_filter)
filters = [articles_filter]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['0', '1', '2'] == sorted(person['id'] for person in people)
def test_has_with_any(self):
"""Tests for nesting a ``has`` filter beneath an ``any`` filter."""
for i in range(5):
person = self.Person(id=i)
article = self.Article(id=i)
comment = self.Comment(id=i)
article.author = person
comment.author = person
comment.article = article
self.session.add_all([article, person, comment])
self.session.commit()
# Search for any articles with comments whose author has id < 3.
id_filter = dict(name='id', op='lt', val=3)
author_filter = dict(name='author', op='has', val=id_filter)
comments_filter = dict(name='comments', op='any', val=author_filter)
filters = [comments_filter]
response = self.search('/api/article', filters)
document = loads(response.data)
articles = document['data']
assert ['0', '1', '2'] == sorted(article['id'] for article in articles)
def test_any_with_has(self):
"""Tests for nesting an ``any`` filter beneath a ``has`` filter."""
for i in range(5):
person = self.Person(id=i)
article = self.Article(id=i)
content = u'me' if i % 2 else u'you'
comment = self.Comment(id=i, content=content)
article.author = person
comment.author = person
self.session.add_all([article, person, comment])
self.session.commit()
# Search for any articles with an author who has made comments that
# include the word "me".
content_filter = dict(name='content', op='like', val='%me%')
comment_filter = dict(name='comments', op='any', val=content_filter)
author_filter = dict(name='author', op='has', val=comment_filter)
filters = [author_filter]
response = self.search('/api/article', filters)
document = loads(response.data)
articles = document['data']
assert ['1', '3'] == sorted(article['id'] for article in articles)
def test_comparing_fields(self):
"""Test for comparing the value of two fields in a filter object."""
person1 = self.Person(id=1, age=1)
person2 = self.Person(id=2, age=3)
person3 = self.Person(id=3, age=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='age', op='eq', field='id')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1', '3'] == sorted(person['id'] for person in people)
def test_date_yyyy_mm_dd(self):
"""Test for date parsing in filter objects with dates of the form
``1969-07-20``.
"""
person1 = self.Person(id=1, birthday=date(1969, 7, 20))
person2 = self.Person(id=2, birthday=date(1900, 1, 2))
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='birthday', op='eq', val='1969-07-20')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_date_english(self):
"""Tests for date parsing in filter object with dates of the form ``2nd
Jan 1900``.
"""
person1 = self.Person(id=1, birthday=date(1969, 7, 20))
person2 = self.Person(id=2, birthday=date(1900, 1, 2))
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='birthday', op='eq', val='2nd Jan 1900')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_times(self):
"""Test for time parsing in filter objects."""
person1 = self.Person(id=1, bedtime=time(17))
person2 = self.Person(id=2, bedtime=time(19))
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='bedtime', op='eq', val='19:00')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_datetimes(self):
"""Test for datetime parsing in filter objects."""
person1 = self.Person(id=1, birth_datetime=datetime(1900, 1, 2))
person2 = self.Person(id=2, birth_datetime=datetime(1969, 7, 20))
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='birth_datetime', op='eq', val='1969-07-20')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_datetime_to_date(self):
"""Tests that a filter object with a datetime value and a field with a
``Date`` type automatically converts the datetime to a date.
"""
person1 = self.Person(id=1, birthday=date(1969, 7, 20))
person2 = self.Person(id=2, birthday=date(1900, 1, 2))
self.session.add_all([person1, person2])
self.session.commit()
datestring = '2nd Jan 1900 14:35'
filters = [dict(name='birthday', op='eq', val=datestring)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_datetime_to_time(self):
"""Test that a datetime gets truncated to a time if the model has a
time field.
"""
person1 = self.Person(id=1, bedtime=time(1, 2))
person2 = self.Person(id=2, bedtime=time(14, 35))
self.session.add_all([person1, person2])
self.session.commit()
datetimestring = datetime(1900, 1, 2, 14, 35).isoformat()
filters = [dict(name='bedtime', op='eq', val=datetimestring)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_bad_date(self):
"""Tests that an invalid date causes an error."""
filters = [dict(name='birthday', op='eq', val='bogus')]
response = self.search('/api/person', filters)
assert response.status_code == 400
# TODO check error message here
def test_bad_time(self):
"""Tests that an invalid time causes an error."""
filters = [dict(name='bedtime', op='eq', val='bogus')]
response = self.search('/api/person', filters)
assert response.status_code == 400
# TODO check error message here
def test_bad_datetime(self):
"""Tests that an invalid datetime causes an error."""
filters = [dict(name='created_at', op='eq', val='bogus')]
response = self.search('/api/person', filters)
assert response.status_code == 400
# TODO check error message here
def test_bad_name(self):
"""Tests that an invalid ``name`` element causes an error."""
filters = [dict(name='bogus__field', op='eq', val='whatever')]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['no such field', 'bogus__field'])
def test_search_boolean_formula(self):
"""Tests for Boolean formulas of filters in a search query."""
person1 = self.Person(id=1, name=u'John', age=10)
person2 = self.Person(id=2, name=u'Paul', age=20)
person3 = self.Person(id=3, name=u'Luke', age=30)
person4 = self.Person(id=4, name=u'Matthew', age=40)
self.session.add_all([person1, person2, person3, person4])
self.session.commit()
# This searches for people whose name is John, or people older than age
# 10 who have a "u" in their names. This should return three people:
# John, Paul, and Luke.
filters = [{'or': [{'and': [dict(name='name', op='like', val='%u%'),
dict(name='age', op='ge', val=10)]},
dict(name='name', op='eq', val='John')]
}]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert len(people) == 3
assert ['1', '2', '3'] == sorted(person['id'] for person in people)
def test_dates_in_boolean_formulas(self):
"""Tests that dates are correctly handled in recursively defined
boolean formula filters.
For more information, see issue #423.
"""
person1 = self.Person(id=1, birthday=date(1990, 1, 1))
person2 = self.Person(id=2, birthday=date(1991, 1, 1))
person3 = self.Person(id=3, birthday=date(1992, 1, 1))
person4 = self.Person(id=4, birthday=date(1993, 1, 1))
self.session.add_all([person1, person2, person3, person4])
self.session.commit()
filters = [
{
'and': [
{
'name': 'birthday',
'op': '>',
'val': '1990-1-1'
},
{
'name': 'birthday',
'op': '<',
'val': '1993-1-1'
}
]
}
]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert len(people) == 2
assert ['2', '3'] == sorted(person['id'] for person in people)
@skip("I'm not certain in what situations an invalid value should cause"
" a SQLAlchemy error")
def test_invalid_value(self):
"""Tests for an error response on an invalid value in a filter object.
"""
filters = [dict(name='age', op='>', val='should not be a string')]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['invalid', 'argument', 'value'])
def test_invalid_field(self):
"""Tests for an error response on an invalid field name in a filter
object.
"""
filters = [dict(name='foo', op='>', val=2)]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['no such field', 'foo'])
def test_invalid_other(self):
"""Tests that an invalid field name for the "other" field causes
an error.
"""
filters = [{'name': 'age', 'op': 'eq', 'field': 'bogus'}]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['no such field', 'bogus'])
def test_invalid_operator(self):
"""Tests for an error response on an invalid operator in a filter
object.
"""
filters = [dict(name='age', op='bogus', val=2)]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['unknown', 'operator', 'bogus'])
def test_missing_argument(self):
"""Tests that filter requests with a missing ``'val'`` causes an error
response.
"""
filters = [dict(name='name', op='==')]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['expected', 'argument', 'operator',
'none'])
def test_missing_fieldname(self):
"""Tests that filter requests with a missing ``'name'`` causes an error
response.
"""
filters = [dict(op='==', val='foo')]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['missing', 'field', 'name'])
def test_missing_operator(self):
"""Tests that filter requests with a missing ``'op'`` causes an error
response.
"""
filters = [dict(name='age', val=3)]
response = self.search('/api/person', filters)
check_sole_error(response, 400, ['missing', 'operator'])
def test_to_many_relation(self):
"""Tests for filtering a to-many relation."""
person = self.Person(id=1)
articles = [self.Article(id=i) for i in range(5)]
person.articles = articles
self.session.add(person)
self.session.add_all(articles)
self.session.commit()
filters = [dict(name='id', op='gt', val=2)]
response = self.search('/api/person/1/articles', filters)
document = loads(response.data)
articles = document['data']
assert ['3', '4'] == sorted(article['id'] for article in articles)
def test_hybrid_property(self):
"""Test for filtering on a hybrid property.
In this test, the hybrid attribute and the SQL expression are of
the same type.
"""
person1 = self.Person(id=1, age=10)
person2 = self.Person(id=2, age=20)
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='is_minor', op='==', val=True)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
self.assertEqual(len(people), 1)
person = people[0]
self.assertEqual(person['id'], '1')
def test_hybrid_expression(self):
"""Test for filtering on a hybrid property with a separate expression.
For more information, see GitHub issue #562.
"""
article1 = self.Article(id=1)
article2 = self.Article(id=2)
comment = self.Comment(id=1)
comment.article = article1
self.session.add_all([article1, article2, comment])
self.session.commit()
filters = [{'name': 'has_comments', 'op': '==', 'val': True}]
response = self.search('/api/article', filters)
document = loads(response.data)
articles = document['data']
self.assertEqual(['1'], sorted(article['id'] for article in articles))
filters = [{'name': 'has_comments', 'op': '==', 'val': False}]
response = self.search('/api/article', filters)
document = loads(response.data)
articles = document['data']
self.assertEqual(['2'], sorted(article['id'] for article in articles))
def test_urlencode_pagination_links(self):
"""Test that filter objects in pagination links are URL-encoded.
For more information, see GitHub issue #553.
"""
people = [self.Person(id=i) for i in range(30)]
self.session.add_all(people)
self.session.commit()
filters = [dict(name='id', op='gte', val=0)]
response = self.search('/api/person', filters)
document = loads(response.data)
links = document['links']
expected = 'filter[objects]=[{"name":"id","op":"gte","val":0}]'
self.assertIn(expected, unquote(links['first']))
self.assertIn(expected, unquote(links['last']))
class TestSimpleFiltering(ManagerTestBase):
"""Unit tests for "simple" filter query parameters.
These are filters of the form
.. sourcecode:: http
GET /comments?filter[post]=1,2&filter[author]=12 HTTP/1.1
"""
def setUp(self):
super(TestSimpleFiltering, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
age = Column(Integer)
class Tag(self.Base):
__tablename__ = 'tag'
name = Column(Unicode, primary_key=True)
id = Column(Integer)
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
article_id = Column(Integer, ForeignKey('article.id'))
article = relationship(Article, backref=backref('comments'))
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship(Person)
tag_name = Column(Unicode, ForeignKey('tag.name'))
tag = relationship(Tag)
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Tag = Tag
self.Base.metadata.create_all()
self.manager.create_api(Comment)
# HACK Need to create APIs for these other models because otherwise
# we're not able to create the link URLs to them.
self.manager.create_api(Article)
self.manager.create_api(Person)
self.manager.create_api(Tag)
def test_single_foreign_key(self):
"""Tests for filtering resources by relationship foreign key."""
for i in range(1, 3):
comment = self.Comment(id=i)
article = self.Article(id=i)
comment.article = article
self.session.add_all([article, comment])
self.session.commit()
query_string = {'filter[article]': 1}
response = self.app.get('/api/comment', query_string=query_string)
document = loads(response.data)
comments = document['data']
assert ['1'] == sorted(comment['id'] for comment in comments)
def test_multiple_foreign_keys(self):
"""Tests for filtering resources by those having a relationship
foreign key in a given set of keys.
"""
for i in range(1, 4):
comment = self.Comment(id=i)
article = self.Article(id=i)
comment.article = article
self.session.add_all([article, comment])
self.session.commit()
query_string = {'filter[article]': ','.join(['1', '2'])}
response = self.app.get('/api/comment', query_string=query_string)
document = loads(response.data)
comments = document['data']
assert ['1', '2'] == sorted(comment['id'] for comment in comments)
def test_multiple_relationships(self):
for i in range(1, 4):
comment = self.Comment(id=i)
article = self.Article(id=i)
person = self.Person(id=i)
comment.article = article
comment.author = person
self.session.add_all([article, comment, person])
self.session.commit()
query_string = {'filter[article]': ','.join(['1', '2']),
'filter[author]': 2}
response = self.app.get('/api/comment', query_string=query_string)
document = loads(response.data)
comments = document['data']
assert ['2'] == sorted(comment['id'] for comment in comments)
def test_primary_key_string(self):
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
tag1 = self.Tag(name=u'foo')
tag2 = self.Tag(name=u'bar')
comment1.tag = tag1
comment2.tag = tag2
self.session.add_all([comment1, comment2, tag1, tag2])
self.session.commit()
query_string = {'filter[tag]': u'foo'}
response = self.app.get('/api/comment', query_string=query_string)
document = loads(response.data)
comments = document['data']
assert ['1'] == sorted(comment['id'] for comment in comments)
def test_custom_primary_key(self):
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
tag1 = self.Tag(id=1, name=u'foo')
tag2 = self.Tag(id=2, name=u'bar')
comment1.tag = tag1
comment2.tag = tag2
self.session.add_all([comment1, comment2, tag1, tag2])
self.session.commit()
# TODO This won't work, since the other API for Tag still exists.
self.manager.create_api(self.Tag, primary_key='id')
query_string = {'filter[tag]': 1}
response = self.app.get('/api/comment', query_string=query_string)
document = loads(response.data)
comments = document['data']
assert ['1'] == sorted(comment['id'] for comment in comments)
def test_field_name(self):
"""Tests for filtering by field name."""
person1 = self.Person(id=1, age=10)
person2 = self.Person(id=2, age=20)
person3 = self.Person(id=3, age=10)
self.session.add_all([person1, person2, person3])
self.session.commit()
query_string = {'filter[age]': 10}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
assert ['1', '3'] == sorted(person['id'] for person in people)
def test_simple_and_complex(self):
"""Tests for requests that employ both simple filtering and
(complex) filter objects.
"""
person1 = self.Person(id=1, age=10)
person2 = self.Person(id=2, age=20)
person3 = self.Person(id=3, age=10)
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [{'name': 'id', 'op': '<', 'val': 3}]
query_string = {
'filter[age]': 10,
'filter[objects]': dumps(filters)
}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_to_many_filter_by_relation(self):
"""Tests for simple filtering on a to-many relation endpoint."""
article = self.Article(id=1)
self.session.add(article)
for i in range(1, 3):
comment = self.Comment(id=i)
tag = self.Tag(name=u'{0}'.format(i))
comment.article = article
comment.tag = tag
self.session.add_all([comment, tag])
self.session.commit()
# There are two comments on article 1, each with a distinct
# tag. Let's choose the sole comment on the article with tag
# '1'.
query_string = {'filter[tag]': '1'}
response = self.app.get('/api/article/1/comments',
query_string=query_string)
document = loads(response.data)
comments = document['data']
assert ['1'] == sorted(comment['id'] for comment in comments)
class TestOperators(SearchTestBase):
"""Tests for each SQLAlchemy operator supported by Flask-Restless."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application,
and creates the ReSTful API endpoints for the models used in the test
methods.
"""
super(TestOperators, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
# age = Column(Integer)
# birthday = Column(Date)
# class Comment(self.Base):
# __tablename__ = 'comment'
# id = Column(Integer, primary_key=True)
# content = Column(Unicode)
# author_id = Column(Integer, ForeignKey('person.id'))
# author = relationship('Person', backref=backref('comments'))
self.Person = Person
# self.Comment = Comment
self.Base.metadata.create_all()
self.manager.create_api(Person)
# HACK Need to create APIs for these other models because otherwise
# we're not able to create the link URLs to them.
#
# TODO Fix this by simply not creating links to related models for
# which no API has been made.
# self.manager.create_api(Comment)
def test_equals(self):
"""Tests for the ``eq`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
for op in '==', 'eq', 'equals', 'equal_to':
filters = [dict(name='id', op=op, val=1)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_not_equal(self):
"""Tests for the ``neq`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
for op in '!=', 'ne', 'neq', 'not_equal_to', 'does_not_equal':
filters = [dict(name='id', op=op, val=1)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_greater_than(self):
"""Tests for the ``gt`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
for op in '>', 'gt':
filters = [dict(name='id', op=op, val=1)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_less_than(self):
"""Tests for the ``lt`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
for op in '<', 'lt':
filters = [dict(name='id', op=op, val=2)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_greater_than_or_equal(self):
"""Tests for the ``gte`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
for op in '>=', 'ge', 'gte', 'geq':
filters = [dict(name='id', op=op, val=2)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2', '3'] == sorted(person['id'] for person in people)
def test_less_than_or_equal(self):
"""Tests for the ``lte`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
for op in '<=', 'le', 'lte', 'leq':
filters = [dict(name='id', op=op, val=2)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1', '2'] == sorted(person['id'] for person in people)
def test_like(self):
"""Tests for the ``like`` operator."""
person1 = self.Person(name=u'foo')
person2 = self.Person(name=u'bar')
person3 = self.Person(name=u'baz')
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='name', op='like', val='%ba%')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['bar', 'baz'] == sorted(person['attributes']['name']
for person in people)
def test_not_like(self):
"""Tests for the ``not_like`` operator."""
person1 = self.Person(name=u'foo')
person2 = self.Person(name=u'bar')
person3 = self.Person(name=u'baz')
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='name', op='not_like', val='%fo%')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['bar', 'baz'] == sorted(person['attributes']['name']
for person in people)
def test_ilike(self):
"""Tests for the ``ilike`` operator."""
person1 = self.Person(name=u'foo')
person2 = self.Person(name=u'bar')
person3 = self.Person(name=u'baz')
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='name', op='ilike', val='%BA%')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['bar', 'baz'] == sorted(person['attributes']['name']
for person in people)
def test_in(self):
"""Tests for the ``in`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='id', op='in', val=[1, 3])]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1', '3'] == sorted(person['id'] for person in people)
def test_not_in(self):
"""Tests for the ``not_in`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
person3 = self.Person(id=3)
self.session.add_all([person1, person2, person3])
self.session.commit()
filters = [dict(name='id', op='not_in', val=[1, 3])]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_is_null(self):
"""Tests for the ``is_null`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2, name=u'foo')
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='name', op='is_null')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['1'] == sorted(person['id'] for person in people)
def test_is_not_null(self):
"""Tests for the ``is_not_null`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2, name=u'foo')
self.session.add_all([person1, person2])
self.session.commit()
filters = [dict(name='name', op='is_not_null')]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_negation(self):
"""Test for the ``not`` operator."""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
filters = [{'not': {'name': 'id', 'op': 'lt', 'val': 2}}]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
assert ['2'] == sorted(person['id'] for person in people)
def test_compare_equals_to_null(self):
"""Tests that an attempt to compare the value of a field to ``None``
using the ``eq`` operator yields an error response, indicating that the
user should use the ``is_null` operation instead.
"""
filters = [dict(name='name', op='eq', val=None)]
response = self.search('/api/person', filters)
keywords = ['compare', 'value', 'NULL', 'use', 'is_null', 'operator']
check_sole_error(response, 400, keywords)
def test_custom_operator(self):
"""Test for a custom operator provided by the user.
For more information, see GitHub pull request #590.
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
register_operator('my_gt', gt)
filters = [dict(name='id', op='my_gt', val=1)]
response = self.search('/api/person', filters)
document = loads(response.data)
people = document['data']
self.assertEqual(['2'], [person['id'] for person in people])
class TestAssociationProxy(SearchTestBase):
"""Test for filtering on association proxies."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application,
and creates the ReSTful API endpoints for the models used in the test
methods.
"""
super(TestAssociationProxy, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
tags = association_proxy('articletags', 'tag',
creator=lambda tag: ArticleTag(tag=tag))
class ArticleTag(self.Base):
__tablename__ = 'articletag'
article_id = Column(Integer, ForeignKey('article.id'),
primary_key=True)
article = relationship(Article, backref=backref('articletags'))
tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True)
tag = relationship('Tag')
# TODO this dummy column is required to create an API for this
# object.
id = Column(Integer)
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Article = Article
self.Tag = Tag
self.Base.metadata.create_all()
self.manager.create_api(Article)
# HACK Need to create APIs for these other models because otherwise
# we're not able to create the link URLs to them.
#
# TODO Fix this by simply not creating links to related models for
# which no API has been made.
self.manager.create_api(ArticleTag)
self.manager.create_api(Tag)
def test_any(self):
"""Tests for filtering on a many-to-many relationship via an
association proxy backed by an association object.
"""
article1 = self.Article(id=1)
article2 = self.Article(id=2)
article3 = self.Article(id=3)
tag1 = self.Tag(name=u'foo')
tag2 = self.Tag(name=u'bar')
tag3 = self.Tag(name=u'baz')
article1.tags = [tag1, tag2]
article2.tags = [tag2, tag3]
article3.tags = [tag3, tag1]
self.session.add_all([article1, article2, article3])
self.session.add_all([tag1, tag2, tag3])
self.session.commit()
filters = [dict(name='tags', op='any',
val=dict(name='name', op='eq', val='bar'))]
response = self.search('/api/article', filters)
document = loads(response.data)
articles = document['data']
assert ['1', '2'] == sorted(article['id'] for article in articles)
| 53,966
|
Python
|
.py
| 1,187
| 35.56866
| 79
| 0.590394
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,659
|
test_creating_resources.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_creating_resources.py
|
# test_creating_resources.py - tests creating resources according to JSON API
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for requests that create resources.
The tests in this module correspond to the `Creating Resources`_ section
of the JSON API specification.
.. _Creating Resources: http://jsonapi.org/format/#crud-creating
"""
import uuid
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.orm import relationship
from ..helpers import dumps
from ..helpers import GUID
from ..helpers import loads
from ..helpers import ManagerTestBase
class TestCreatingResources(ManagerTestBase):
"""Tests corresponding to the `Creating Resources`_ section of the JSON API
specification.
.. _Creating Resources: http://jsonapi.org/format/#crud-creating
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestCreatingResources, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(GUID, primary_key=True)
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
age = Column(Integer)
comments = relationship('Comment')
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Person, methods=['POST'])
self.manager.create_api(Article, methods=['POST'],
allow_client_generated_ids=True)
self.manager.create_api(Comment)
def test_sparse_fieldsets_post(self):
"""Tests for restricting which fields are returned in a
:http:method:`post` request.
This unit test lives in this class instead of the
:class:`TestFetchingData` class because in that class, APIs do
not allow :http:method:`post` requests.
For more information, see the `Sparse Fieldsets`_ section
of the JSON API specification.
.. _Sparse Fieldsets:
http://jsonapi.org/format/#fetching-sparse-fieldsets
"""
data = {
'data': {
'type': 'person',
'attributes': {
'name': 'foo',
'age': 99,
}
}
}
query_string = {'fields[person]': 'name'}
response = self.app.post('/api/person', data=dumps(data),
query_string=query_string)
document = loads(response.data)
person = document['data']
# ID and type must always be included.
assert ['attributes', 'id', 'type'] == sorted(person)
assert ['name'] == sorted(person['attributes'])
def test_include_post(self):
"""Tests for including related resources on a
:http:method:`post` request.
This unit test lives in this class instead of the
:class:`TestFetchingData` class because in that class, APIs do
not allow :http:method:`post` requests.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
comment = self.Comment(id=1)
self.session.add(comment)
self.session.commit()
data = {
'data': {
'type': 'person',
'relationships': {
'comments': {
'data': [
{'type': 'comment', 'id': 1}
]
}
}
}
}
query_string = dict(include='comments')
response = self.app.post('/api/person', data=dumps(data),
query_string=query_string)
assert response.status_code == 201
document = loads(response.data)
included = document['included']
assert len(included) == 1
comment = included[0]
assert comment['type'] == 'comment'
assert comment['id'] == '1'
def test_create(self):
"""Tests that the client can create a single resource.
For more information, see the `Creating Resources`_ section of the JSON
API specification.
.. _Creating Resources: http://jsonapi.org/format/#crud-creating
"""
data = {
'data': {
'type': 'person',
'attributes': {
'name': 'foo',
}
}
}
response = self.app.post('/api/person', data=dumps(data))
self.assertEqual(response.status_code, 201)
location = response.headers['Location']
people = self.session.query(self.Person).all()
self.assertEqual(len(people), 1)
person = people[0]
self.assertTrue(location.endswith('/api/person/{0}'.format(person.id)))
document = loads(response.data)
person = document['data']
self.assertEqual(person['type'], 'person')
self.assertEqual(person['id'], '1')
self.assertEqual(person['attributes']['name'], 'foo')
# # No self link will exist because no GET endpoint was created.
# assert person['links']['self'] == location
def test_without_type(self):
"""Tests for an error response if the client fails to specify the type
of the object to create.
For more information, see the `Creating Resources`_ section of the JSON
API specification.
.. _Creating Resources: http://jsonapi.org/format/#crud-creating
"""
data = dict(data=dict(name='foo'))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 400
# TODO test for error details (for example, a message specifying that
# type is missing)
def test_client_generated_id(self):
"""Tests that the client can specify a UUID to become the ID of the
created object.
For more information, see the `Client-Generated IDs`_ section of the
JSON API specification.
.. _Client-Generated IDs:
http://jsonapi.org/format/#crud-creating-client-ids
"""
generated_id = uuid.uuid1()
data = dict(data=dict(type='article', id=generated_id))
response = self.app.post('/api/article', data=dumps(data))
# Our server always responds with 201 when a client-generated ID is
# specified. It does not return a 204.
#
# TODO should we reverse that and only return 204?
assert response.status_code == 201
document = loads(response.data)
article = document['data']
assert article['type'] == 'article'
assert article['id'] == str(generated_id)
def test_client_generated_id_forbidden(self):
"""Tests that the client can specify a UUID to become the ID of the
created object.
For more information, see the `Client-Generated IDs`_ section of the
JSON API specification.
.. _Client-Generated IDs:
http://jsonapi.org/format/#crud-creating-client-ids
"""
self.manager.create_api(self.Article, url_prefix='/api2',
methods=['POST'])
data = dict(data=dict(type='article', id=uuid.uuid1()))
response = self.app.post('/api2/article', data=dumps(data))
assert response.status_code == 403
# TODO test for error details (for example, a message specifying that
# client-generated IDs are not allowed).
def test_type_conflict(self):
"""Tests that if a client specifies a type that does not match the
endpoint, a :http:status:`409` is returned.
For more information, see the `409 Conflict`_ section of the JSON API
specification.
.. _409 Conflict:
http://jsonapi.org/format/#crud-creating-responses-409
"""
data = dict(data=dict(type='bogustype', name='foo'))
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 409
# TODO test for error details (for example, a message specifying that
# client-generated IDs are not allowed).
def test_id_conflict(self):
"""Tests that if a client specifies a client-generated ID that already
exists, a :http:status:`409` is returned.
For more information, see the `409 Conflict`_ section of the JSON API
specification.
.. _409 Conflict:
http://jsonapi.org/format/#crud-creating-responses-409
"""
generated_id = uuid.uuid1()
self.session.add(self.Article(id=generated_id))
self.session.commit()
data = dict(data=dict(type='article', id=generated_id))
response = self.app.post('/api/article', data=dumps(data))
assert response.status_code == 409
# TODO test for error details (for example, a message specifying that
# client-generated IDs are not allowed).
| 10,092
|
Python
|
.py
| 228
| 34.605263
| 79
| 0.615651
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,660
|
test_deleting_resources.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_deleting_resources.py
|
# test_deleting_resources.py - tests deleting resources according to JSON API
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for requests that delete resources.
The tests in this module correspond to the `Deleting Resources`_ section
of the JSON API specification.
.. _Deleting Resources: http://jsonapi.org/format/#crud-deleting
"""
from sqlalchemy import Column
from sqlalchemy import Integer
from ..helpers import ManagerTestBase
class TestDeletingResources(ManagerTestBase):
"""Tests corresponding to the `Deleting Resources`_ section of the JSON API
specification.
.. _Deleting Resources: http://jsonapi.org/format/#crud-deleting
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
class.
"""
# create the database
super(TestDeletingResources, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(self.Person, methods=['DELETE'])
def test_delete(self):
"""Tests for deleting a resource.
For more information, see the `Deleting Resources`_ section of the JSON
API specification.
.. _Deleting Resources: http://jsonapi.org/format/#crud-deleting
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.delete('/api/person/1')
assert response.status_code == 204
assert self.session.query(self.Person).count() == 0
def test_delete_nonexistent(self):
"""Tests that deleting a nonexistent resource causes a
:http:status:`404`.
For more information, see the `404 Not Found`_ section of the JSON API
specification.
.. _404 Not Found:
http://jsonapi.org/format/#crud-deleting-responses-404
"""
response = self.app.delete('/api/person/1')
assert response.status_code == 404
| 2,609
|
Python
|
.py
| 60
| 37.1
| 79
| 0.689601
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,661
|
test_document_structure.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_document_structure.py
|
# test_document_structure.py - tests JSON API document structure
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Tests that Flask-Restless responds to the client with correctly
structured JSON documents.
The tests in this module correspond to the `Document Structure`_ section
of the JSON API specification.
.. _Document Structure: http://jsonapi.org/format/#document-structure
"""
import string
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy.orm import relationship
from ..helpers import dumps
from ..helpers import loads
from ..helpers import ManagerTestBase
class TestDocumentStructure(ManagerTestBase):
"""Tests corresponding to the `Document Structure`_ section of the JSON API
specification.
.. _Document Structure: http://jsonapi.org/format/#document-structure
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestDocumentStructure, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
articles = relationship(Article)
comments = relationship('Comment')
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Comment)
self.manager.create_api(Person, methods=['GET', 'POST'])
def test_ignore_additional_members(self):
"""Tests that the server ignores any additional top-level members.
For more information, see the `Document Structure`_ section of the JSON
API specification.
.. _Document Structure: http://jsonapi.org/format/#document-structure
"""
# The key `bogus` is unknown to the JSON API specification, and
# therefore should be ignored.
data = dict(data=dict(type='person'), bogus=True)
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
document = loads(response.data)
assert 'errors' not in document
assert self.session.query(self.Person).count() == 1
def test_allowable_top_level_keys(self):
"""Tests that a response contains at least one of the top-level
elements ``data``, ``errors``, and ``meta``.
For more information, see the `Top Level`_ section of the JSON
API specification.
.. _Top Level: http://jsonapi.org/format/#document-top-level
"""
response = self.app.get('/api/person')
allowable_keys = ('data', 'errors', 'meta')
assert any(key in loads(response.data) for key in allowable_keys)
def test_no_data_and_errors_good_request(self):
"""Tests that a response to a valid request does not contain
both ``data`` and ``errors`` simultaneously as top-level
elements.
For more information, see the `Top Level`_ section of the JSON
API specification.
.. _Top Level: http://jsonapi.org/format/#document-top-level
"""
response = self.app.get('/api/person')
assert not all(k in loads(response.data) for k in ('data', 'errors'))
def test_no_data_and_errors_bad_request(self):
"""Tests that a response to an invalid request does not contain
both ``data`` and ``errors`` simultaneously as top-level
elements.
For more information, see the `Top Level`_ section of the JSON
API specification.
.. _Top Level: http://jsonapi.org/format/#document-top-level
"""
response = self.app.get('/api/person/boguskey')
assert not all(k in loads(response.data) for k in ('data', 'errors'))
def test_errors_top_level_key(self):
"""Tests that errors appear under a top-level key ``errors``."""
response = self.app.get('/api/person/boguskey')
data = loads(response.data)
assert 'errors' in data
def test_no_other_top_level_keys(self):
"""Tests that no there are no other alphanumeric top-level keys in the
response other than the allowed ones.
For more information, see the `Top Level`_ section of the JSON API
specification.
.. _Top Level: http://jsonapi.org/format/#document-structure-top-level
"""
response = self.app.get('/api/person')
document = loads(response.data)
allowed = ('data', 'errors', 'meta', 'jsonapi', 'links', 'included')
alphanumeric = string.ascii_letters + string.digits
assert all(d in allowed or d[0] not in alphanumeric for d in document)
def test_resource_attributes(self):
"""Test that a resource has the required top-level keys.
For more information, see the `Resource Objects`_ section of the JSON
API specification.
.. _Resource Objects:
http://jsonapi.org/format/#document-resource-objects
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
assert person['id'] == '1'
assert person['type'] == 'person'
def test_no_foreign_keys(self):
"""By default, foreign keys should not appear in the representation of
a resource.
For more information, see the `Resource Object Attributes`_
section of the JSON API specification.
.. _Resource Object Attributes:
http://jsonapi.org/format/#document-resource-object-attributes
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
assert 'attributes' not in article
assert 'author_id' not in article
def test_required_relationship_keys(self):
"""Tests that a relationship object contains at least one of the
required keys, ``links``, ``data``, or ``meta``.
For more information, see the `Resource Object Relationships`_
section of the JSON API specification.
.. _Resource Object Relationships:
http://jsonapi.org/format/#document-resource-object-relationships
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
relationship = document['data']['relationships']['articles']
assert any(key in relationship for key in ('data', 'links', 'meta'))
def test_required_relationship_link_keys(self):
"""Tests that a relationship links object contains at least one
of the required keys, ``self`` or ``related``.
For more information, see the `Resource Object Relationships`_
section of the JSON API specification.
.. _Resource Object Relationships:
http://jsonapi.org/format/#document-resource-object-relationships
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
relationship = document['data']['relationships']['articles']
links = relationship['links']
assert any(key in links for key in ('self', 'related'))
def test_self_relationship_url(self):
"""Tests that a relationship object correctly identifies its own
relationship URL.
For more information, see the `Resource Object Relationships`_
section of the JSON API specification.
.. _Resource Object Relationships:
http://jsonapi.org/format/#document-resource-object-relationships
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
relationship = article['relationships']['author']
relationship_url = relationship['links']['self']
assert relationship_url.endswith('/api/article/1/relationships/author')
def test_related_resource_url_to_one(self):
"""Tests that the related resource URL in a to-one relationship
correctly identifies the related resource.
For more information, see the `Related Resource Links`_ section
of the JSON API specification.
.. _Related Resource Links:
http://jsonapi.org/format/#document-resource-object-related-resource-links
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
# Get a resource that has links.
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
# Get the related resource URL.
resource_url = article['relationships']['author']['links']['related']
# The Flask test client doesn't need the `netloc` part of the URL.
path = urlparse(resource_url).path
# Fetch the resource at the related resource URL.
response = self.app.get(path)
document = loads(response.data)
actual_person = document['data']
# Compare it with what we expect to get.
response = self.app.get('/api/person/1')
expected_person = loads(response.data)['data']
assert actual_person == expected_person
def test_related_resource_url_to_many(self):
"""Tests that the related resource URL in a to-many relationship
correctly identifies the related resource.
For more information, see the `Related Resource Links`_ section
of the JSON API specification.
.. _Related Resource Links:
http://jsonapi.org/format/#document-resource-object-related-resource-links
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
# Get a resource that has links.
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
# Get the related resource URL.
resource_url = person['relationships']['articles']['links']['related']
# The Flask test client doesn't need the `netloc` part of the URL.
path = urlparse(resource_url).path
# Fetch the resource at the related resource URL.
response = self.app.get(path)
document = loads(response.data)
actual_articles = document['data']
# Compare it with what we expect to get.
#
# TODO To make this test more robust, filter by `article.author == 1`.
response = self.app.get('/api/article')
document = loads(response.data)
expected_articles = document['data']
assert actual_articles == expected_articles
def test_resource_linkage_empty_to_one(self):
"""Tests that resource linkage for an empty to-one relationship
is ``null``.
For more information, see the `Resource Linkage`_ section of the
JSON API specification.
.. _Resource Linkage:
http://jsonapi.org/format/#document-resource-object-linkage
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
author_relationship = article['relationships']['author']
linkage = author_relationship['data']
assert linkage is None
def test_resource_linkage_empty_to_many(self):
"""Tests that resource linkage for an empty to-many relationship
is an empty list.
For more information, see the `Resource Linkage`_ section of the
JSON API specification.
.. _Resource Linkage:
http://jsonapi.org/format/#document-resource-object-linkage
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
articles_relationship = person['relationships']['articles']
linkage = articles_relationship['data']
assert linkage == []
def test_resource_linkage_to_one(self):
"""Tests that resource linkage for a to-one relationship is
a single resource identifier object.
For more information, see the `Resource Linkage`_ section of the
JSON API specification.
.. _Resource Linkage:
http://jsonapi.org/format/#document-resource-object-linkage
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
author_relationship = article['relationships']['author']
linkage = author_relationship['data']
assert linkage['id'] == '1'
assert linkage['type'] == 'person'
def test_resource_linkage_to_many(self):
"""Tests that resource linkage for a to-many relationship is a
list of resource identifier objects.
For more information, see the `Resource Linkage`_ section of the
JSON API specification.
.. _Resource Linkage:
http://jsonapi.org/format/#document-resource-object-linkage
"""
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person = self.Person(id=1)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
articles_relationship = person['relationships']['articles']
linkage = articles_relationship['data']
assert ['1', '2'] == sorted(link['id'] for link in linkage)
assert all(link['type'] == 'article' for link in linkage)
def test_self_link(self):
"""Tests that a request to a self link responds with the same
object.
For more information, see the `Resource Links`_ section of the
JSON API specification.
.. _Resource Links:
http://jsonapi.org/format/#document-resource-object-links
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1')
document1 = loads(response.data)
person = document1['data']
selfurl = person['links']['self']
# The Flask test client doesn't need the `netloc` part of the URL.
path = urlparse(selfurl).path
response = self.app.get(path)
document2 = loads(response.data)
assert document1 == document2
def test_resource_identifier_object_keys(self):
"""Tests that a resource identifier object contains the required
keys.
For more information, see the `Resource Identifier Objects`_
section of the JSON API specification.
.. _Resource Identifier Objects:
http://jsonapi.org/format/#document-resource-identifier-objects
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
response = self.app.get('/api/article/1')
document = loads(response.data)
article = document['data']
author_relationship = article['relationships']['author']
linkage = author_relationship['data']
assert all(key in linkage for key in ('id', 'type'))
assert linkage['id'] == '1'
assert linkage['type'] == 'person'
# def test_link_object(self):
# """Tests for relations as resource URLs."""
# # TODO configure the api manager here
# person = self.Person(id=1)
# self.session.add(person)
# self.session.commit()
# response = self.app.get('/api/person/1')
# person = loads(response.data)['data']
# links = person['relationships']['articles']['links']
# # A link object must contain at least one of 'self', 'related',
# # linkage to a compound document, or 'meta'.
# assert links['self'].endswith('/api/person/1/links/articles')
# assert links['related'].endswith('/api/person/1/articles')
# # TODO should also include pagination links
def test_top_level_self_link(self):
"""Tests that there is a top-level links object containing a
self link.
For more information, see the `Links`_ section of the JSON API
specification.
.. _Links: http://jsonapi.org/format/#document-links
"""
response = self.app.get('/api/person')
document = loads(response.data)
links = document['links']
assert links['self'].endswith('/api/person')
# TODO Test this for every possible type of request.
def test_jsonapi_object(self):
"""Tests that the server provides a jsonapi object.
For more information, see the `JSON API Object`_ section of the
JSON API specification.
.. _JSON API Object: http://jsonapi.org/format/#document-jsonapi-object
"""
response = self.app.get('/api/person')
document = loads(response.data)
jsonapi = document['jsonapi']
assert '1.0' == jsonapi['version']
| 19,375
|
Python
|
.py
| 419
| 37.747017
| 85
| 0.644997
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,662
|
test_fetching_data.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_fetching_data.py
|
# test_fetching_data.py - tests fetching data according to JSON API
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for requests that fetch resources and relationships.
The tests in this module correspond to the `Fetching Data`_ section of
the JSON API specification.
.. _Fetching Data: http://jsonapi.org/format/#fetching
"""
from functools import partial
import re
# In Python 3...
try:
from urllib.parse import unquote
# In Python 2...
except ImportError:
from urlparse import unquote
from sqlalchemy import Column
from sqlalchemy import Float
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from ..helpers import loads
from ..helpers import ManagerTestBase
#: A regular expression that captures a relationship name in a Link header.
REL_REGEX = re.compile('rel="(.*)"')
class TestFetchingData(ManagerTestBase):
"""Tests corresponding to the `Fetching Data`_ section of the JSON API
specification.
.. _Fetching Data: http://jsonapi.org/format/#fetching
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestFetchingData, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
article_id = Column(Integer, ForeignKey('article.id'))
article = relationship(Article, backref=backref('comments'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
age = Column(Integer)
other = Column(Float)
articles = relationship('Article')
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
# HACK Need to create APIs for these other models because otherwise
# we're not able to create the link URLs to them.
#
# TODO Fix this by simply not creating links to related models for
# which no API has been made.
self.manager.create_api(Comment)
def test_single_resource(self):
"""Tests for fetching a single resource.
For more information, see the `Fetching Resources`_ section of
JSON API specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1')
assert response.status_code == 200
document = loads(response.data)
article = document['data']
assert article['id'] == '1'
assert article['type'] == 'article'
def test_collection(self):
"""Tests for fetching a collection of resources.
For more information, see the `Fetching Resources`_ section of
JSON API specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article')
assert response.status_code == 200
document = loads(response.data)
articles = document['data']
assert ['1'] == sorted(article['id'] for article in articles)
def test_related_resource(self):
"""Tests for fetching a to-one related resource.
For more information, see the `Fetching Resources`_ section of
JSON API specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
article = self.Article(id=1)
person = self.Person(id=1)
article.author = person
self.session.add_all([article, person])
self.session.commit()
response = self.app.get('/api/article/1/author')
assert response.status_code == 200
document = loads(response.data)
author = document['data']
assert author['type'] == 'person'
assert author['id'] == '1'
def test_empty_collection(self):
"""Tests for fetching an empty collection of resources.
For more information, see the `Fetching Resources`_ section of
JSON API specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
response = self.app.get('/api/person')
assert response.status_code == 200
document = loads(response.data)
people = document['data']
assert people == []
def test_to_many_related_resource_url(self):
"""Tests for fetching to-many related resources from a related
resource URL.
The response to a request to a to-many related resource URL should
include an array of resource objects, *not* linkage objects.
For more information, see the `Fetching Resources`_ section of JSON API
specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
response = self.app.get('/api/person/1/articles')
assert response.status_code == 200
document = loads(response.data)
articles = document['data']
assert ['1', '2'] == sorted(article['id'] for article in articles)
assert all(article['type'] == 'article' for article in articles)
assert all('title' in article['attributes'] for article in articles)
assert all('author' in article['relationships']
for article in articles)
def test_to_one_related_resource_url(self):
"""Tests for fetching a to-one related resource from a related resource
URL.
The response to a request to a to-one related resource URL should
include a resource object, *not* a linkage object.
For more information, see the `Fetching Resources`_ section of JSON API
specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
response = self.app.get('/api/article/1/author')
assert response.status_code == 200
document = loads(response.data)
author = document['data']
assert author['id'] == '1'
assert author['type'] == 'person'
assert all(field in author['attributes']
for field in ('name', 'age', 'other'))
def test_empty_to_many_related_resource_url(self):
"""Tests for fetching an empty to-many related resource from a related
resource URL.
For more information, see the `Fetching Resources`_ section of JSON API
specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
response = self.app.get('/api/person/1/articles')
assert response.status_code == 200
document = loads(response.data)
articles = document['data']
assert articles == []
def test_empty_to_one_related_resource(self):
"""Tests for fetching an empty to-one related resource from a related
resource URL.
For more information, see the `Fetching Resources`_ section of JSON API
specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1/author')
assert response.status_code == 200
document = loads(response.data)
author = document['data']
assert author is None
def test_nonexistent_resource(self):
"""Tests for fetching a nonexistent resource.
For more information, see the `Fetching Resources`_ section of
JSON API specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
response = self.app.get('/api/article/1')
assert response.status_code == 404
def test_nonexistent_collection(self):
"""Tests for fetching a nonexistent collection of resources.
For more information, see the `Fetching Resources`_ section of
JSON API specification.
.. _Fetching Resources: http://jsonapi.org/format/#fetching-resources
"""
response = self.app.get('/api/bogus')
assert response.status_code == 404
def test_to_many_relationship_url(self):
"""Test for fetching linkage objects from a to-many relationship
URL.
The response to a request to a to-many relationship URL should
be a linkage object, *not* a resource object.
For more information, see the `Fetching Relationships`_ section
of JSON API specification.
.. _Fetching Relationships:
http://jsonapi.org/format/#fetching-relationships
"""
article = self.Article(id=1)
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
comment3 = self.Comment(id=3)
article.comments = [comment1, comment2]
self.session.add_all([article, comment1, comment2, comment3])
self.session.commit()
response = self.app.get('/api/article/1/relationships/comments')
assert response.status_code == 200
document = loads(response.data)
comments = document['data']
assert all(['id', 'type'] == sorted(comment) for comment in comments)
assert ['1', '2'] == sorted(comment['id'] for comment in comments)
assert all(comment['type'] == 'comment' for comment in comments)
def test_empty_to_many_relationship_url(self):
"""Test for fetching from an empty to-many relationship URL.
For more information, see the `Fetching Relationships`_ section of JSON
API specification.
.. _Fetching Relationships:
http://jsonapi.org/format/#fetching-relationships
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1/relationships/comments')
assert response.status_code == 200
document = loads(response.data)
comments = document['data']
assert comments == []
def test_to_one_relationship_url(self):
"""Test for fetching a resource from a to-one relationship URL.
The response to a request to a to-many relationship URL should
be a linkage object, *not* a resource object.
For more information, see the `Fetching Relationships`_ section
of JSON API specification.
.. _Fetching Relationships:
http://jsonapi.org/format/#fetching-relationships
"""
person = self.Person(id=1)
article = self.Article(id=1)
article.author = person
self.session.add_all([person, article])
self.session.commit()
response = self.app.get('/api/article/1/relationships/author')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert ['id', 'type'] == sorted(person)
assert person['id'] == '1'
assert person['type'] == 'person'
def test_empty_to_one_relationship_url(self):
"""Test for fetching from an empty to-one relationship URL.
For more information, see the `Fetching Relationships`_ section of JSON
API specification.
.. _Fetching Relationships:
http://jsonapi.org/format/#fetching-relationships
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1/relationships/author')
assert response.status_code == 200
document = loads(response.data)
person = document['data']
assert person is None
def test_relationship_links(self):
"""Tests for links included in relationship objects.
For more information, see the `Fetching Relationships`_ section
of JSON API specification.
.. _Fetching Relationships:
http://jsonapi.org/format/#fetching-relationships
"""
article = self.Article(id=1)
self.session.add(article)
self.session.commit()
response = self.app.get('/api/article/1/relationships/author')
document = loads(response.data)
links = document['links']
assert links['self'].endswith('/article/1/relationships/author')
assert links['related'].endswith('/article/1/author')
class TestInclusion(ManagerTestBase):
"""Tests corresponding to the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
def setUp(self):
super(TestInclusion, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Comment(self.Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person', backref=backref('comments'))
article_id = Column(Integer, ForeignKey('article.id'))
article = relationship(Article, backref=backref('comments'))
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
articles = relationship('Article')
self.Article = Article
self.Comment = Comment
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Comment)
self.manager.create_api(Person)
def test_default_inclusion(self):
"""Tests that by default, Flask-Restless includes no included
resources in compound documents.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person = self.Person(id=1)
article = self.Article(id=1)
person.articles = [article]
self.session.add_all([person, article])
self.session.commit()
# By default, no links will be included at the top level of the
# document.
response = self.app.get('/api/person/1')
document = loads(response.data)
person = document['data']
articles = person['relationships']['articles']['data']
assert ['1'] == sorted(article['id'] for article in articles)
# The current implementation of Flask-Restless has an empty list
# for `included`.
assert document['included'] == []
# assert 'included' not in document
def test_set_default_inclusion(self):
"""Tests that the user can specify default compound document
inclusions when creating an API.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person = self.Person(id=1)
article = self.Article(id=1)
person.articles = [article]
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Person, includes=['articles'],
url_prefix='/api2')
# In the alternate API, articles are included by default in compound
# documents.
response = self.app.get('/api2/person/1')
document = loads(response.data)
person = document['data']
linked = document['included']
articles = person['relationships']['articles']['data']
assert ['1'] == sorted(article['id'] for article in articles)
assert linked[0]['type'] == 'article'
assert linked[0]['id'] == '1'
def test_include(self):
"""Tests that the client can specify which linked relations to
include in a compound document.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person = self.Person(id=1, name=u'foo')
article1 = self.Article(id=1)
article2 = self.Article(id=2)
comment = self.Comment()
person.articles = [article1, article2]
person.comments = [comment]
self.session.add_all([person, comment, article1, article2])
self.session.commit()
query_string = dict(include='articles')
response = self.app.get('/api/person/1', query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
linked = document['included']
# If a client supplied an include request parameter, no other types of
# objects should be included.
assert all(c['type'] == 'article' for c in linked)
assert ['1', '2'] == sorted(c['id'] for c in linked)
def test_include_multiple(self):
"""Tests that the client can specify multiple linked relations
to include in a compound document.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person = self.Person(id=1, name=u'foo')
article = self.Article(id=2)
comment = self.Comment(id=3)
person.articles = [article]
person.comments = [comment]
self.session.add_all([person, comment, article])
self.session.commit()
query_string = dict(include='articles,comments')
response = self.app.get('/api/person/1', query_string=query_string)
assert response.status_code == 200
document = loads(response.data)
# Sort the linked objects by type; 'article' comes before 'comment'
# lexicographically.
linked = sorted(document['included'], key=lambda x: x['type'])
linked_article, linked_comment = linked
assert linked_article['type'] == 'article'
assert linked_article['id'] == '2'
assert linked_comment['type'] == 'comment'
assert linked_comment['id'] == '3'
def test_include_dot_separated(self):
"""Tests that the client can specify resources linked to other
resources to include in a compound document.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
article = self.Article(id=1)
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
person1 = self.Person(id=1)
person2 = self.Person(id=2)
comment1.article = article
comment2.article = article
comment1.author = person1
comment2.author = person2
self.session.add_all([article, comment1, comment2, person1, person2])
self.session.commit()
query_string = dict(include='comments.author')
response = self.app.get('/api/article/1', query_string=query_string)
document = loads(response.data)
authors = [resource for resource in document['included']
if resource['type'] == 'person']
assert ['1', '2'] == sorted(author['id'] for author in authors)
def test_include_intermediate_resources(self):
"""Tests that intermediate resources from a multi-part
relationship path are included in a compound document.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article = self.Article(id=1)
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
article.comments = [comment1, comment2]
comment1.author = person1
comment2.author = person2
self.session.add_all([article, comment1, comment2, person1, person2])
self.session.commit()
query_string = dict(include='comments.author')
response = self.app.get('/api/article/1', query_string=query_string)
document = loads(response.data)
linked = document['included']
# The included resources should be the two comments and the two
# authors of those comments.
assert len(linked) == 4
authors = [r for r in linked if r['type'] == 'person']
comments = [r for r in linked if r['type'] == 'comment']
assert ['1', '2'] == sorted(author['id'] for author in authors)
assert ['1', '2'] == sorted(comment['id'] for comment in comments)
def test_include_relationship(self):
"""Tests for including related resources from a relationship endpoint.
For more information, see the `Inclusion of Related Resources`_
section of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article = self.Article(id=1)
comment1 = self.Comment(id=1)
comment2 = self.Comment(id=2)
article.comments = [comment1, comment2]
comment1.author = person1
comment2.author = person2
self.session.add_all([article, comment1, comment2, person1, person2])
self.session.commit()
query_string = dict(include='comments.author')
response = self.app.get('/api/article/1/relationships/comments',
query_string=query_string)
# In this case, the primary data is a collection of resource
# identifier objects that represent linkage to comments for an
# article, while the full comments and comment authors would be
# returned as included data.
#
# This differs from the previous test because the primary data
# is a collection of relationship objects instead of a
# collection of resource objects.
document = loads(response.data)
links = document['data']
assert all(sorted(link) == ['id', 'type'] for link in links)
included = document['included']
# The included resources should be the two comments and the two
# authors of those comments.
assert len(included) == 4
authors = [r for r in included if r['type'] == 'person']
comments = [r for r in included if r['type'] == 'comment']
assert ['1', '2'] == sorted(author['id'] for author in authors)
assert ['1', '2'] == sorted(comment['id'] for comment in comments)
def test_client_overrides_server_includes(self):
"""Tests that if a client supplies an include query parameter, the
server does not include any other resource objects in the included
section of the compound document.
For more information, see the `Inclusion of Related Resources`_ section
of the JSON API specification.
.. _Inclusion of Related Resources:
http://jsonapi.org/format/#fetching-includes
"""
person = self.Person(id=1)
article = self.Article(id=2)
comment = self.Comment(id=3)
article.author = person
comment.author = person
self.session.add_all([person, article, comment])
self.session.commit()
# The server will, by default, include articles. The client will
# override this and request only comments.
self.manager.create_api(self.Person, url_prefix='/api2',
includes=['articles'])
query_string = dict(include='comments')
response = self.app.get('/api2/person/1', query_string=query_string)
document = loads(response.data)
included = document['included']
assert ['3'] == sorted(obj['id'] for obj in included)
assert ['comment'] == sorted(obj['type'] for obj in included)
class TestSparseFieldsets(ManagerTestBase):
"""Tests corresponding to the `Sparse Fieldsets`_ section of the
JSON API specification.
.. _Sparse Fieldsets: http://jsonapi.org/format/#fetching-sparse-fieldsets
"""
def setUp(self):
super(TestSparseFieldsets, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
age = Column(Integer)
articles = relationship('Article')
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_sparse_fieldsets(self):
"""Tests that the client can specify which fields to return in the
response of a fetch request for a single object.
For more information, see the `Sparse Fieldsets`_ section
of the JSON API specification.
.. _Sparse Fieldsets:
http://jsonapi.org/format/#fetching-sparse-fieldsets
"""
person = self.Person(id=1, name=u'foo', age=99)
self.session.add(person)
self.session.commit()
query_string = {'fields[person]': 'id,name'}
response = self.app.get('/api/person/1', query_string=query_string)
document = loads(response.data)
person = document['data']
# ID and type must always be included.
assert ['attributes', 'id', 'type'] == sorted(person)
assert ['name'] == sorted(person['attributes'])
def test_sparse_fieldsets_id_and_type(self):
"""Tests that the ID and type of the resource are always included in a
response from a request for sparse fieldsets, regardless of what the
client requests.
For more information, see the `Sparse Fieldsets`_ section
of the JSON API specification.
.. _Sparse Fieldsets:
http://jsonapi.org/format/#fetching-sparse-fieldsets
"""
person = self.Person(id=1, name=u'foo', age=99)
self.session.add(person)
self.session.commit()
query_string = {'fields[person]': 'id'}
response = self.app.get('/api/person/1', query_string=query_string)
document = loads(response.data)
person = document['data']
# ID and type must always be included.
assert ['id', 'type'] == sorted(person)
def test_sparse_fieldsets_collection(self):
"""Tests that the client can specify which fields to return in the
response of a fetch request for a collection of objects.
For more information, see the `Sparse Fieldsets`_ section
of the JSON API specification.
.. _Sparse Fieldsets:
http://jsonapi.org/format/#fetching-sparse-fieldsets
"""
person1 = self.Person(id=1, name=u'foo', age=99)
person2 = self.Person(id=2, name=u'bar', age=80)
self.session.add_all([person1, person2])
self.session.commit()
query_string = {'fields[person]': 'id,name'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
assert all(['attributes', 'id', 'type'] == sorted(p) for p in people)
assert all(['name'] == sorted(p['attributes']) for p in people)
def test_sparse_fieldsets_multiple_types(self):
"""Tests that the client can specify which fields to return in the
response with multiple types specified.
For more information, see the `Sparse Fieldsets`_ section
of the JSON API specification.
.. _Sparse Fieldsets:
http://jsonapi.org/format/#fetching-sparse-fieldsets
"""
article = self.Article(id=1, title=u'bar')
person = self.Person(id=1, name=u'foo', age=99)
article.author = person
self.session.add_all([article, person])
self.session.commit()
# Person objects should only have ID and name, while article objects
# should only have ID.
query_string = {'include': 'articles',
'fields[person]': 'id,name,articles',
'fields[article]': 'id'}
response = self.app.get('/api/person/1', query_string=query_string)
document = loads(response.data)
person = document['data']
linked = document['included']
# We requested 'id', 'name', and 'articles'; 'id' and 'type' must
# always be present; 'name' comes under an 'attributes' key; and
# 'articles' comes under a 'links' key.
assert ['attributes', 'id', 'relationships', 'type'] == sorted(person)
assert ['articles'] == sorted(person['relationships'])
assert ['name'] == sorted(person['attributes'])
# We requested only 'id', but 'type' must always appear as well.
assert all(['id', 'type'] == sorted(article) for article in linked)
class TestSorting(ManagerTestBase):
"""Tests corresponding to the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
def setUp(self):
super(TestSorting, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
age = Column(Integer)
articles = relationship('Article')
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Article)
self.manager.create_api(Person)
def test_sort_increasing(self):
"""Tests that the client can specify the fields on which to sort
the response in increasing order.
For more information, see the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
person1 = self.Person(name=u'foo', age=20)
person2 = self.Person(name=u'bar', age=10)
person3 = self.Person(name=u'baz', age=30)
self.session.add_all([person1, person2, person3])
self.session.commit()
query_string = {'sort': 'age'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
age1, age2, age3 = (p['attributes']['age'] for p in people)
assert age1 <= age2 <= age3
def test_sort_decreasing(self):
"""Tests that the client can specify the fields on which to sort
the response in decreasing order.
For more information, see the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
person1 = self.Person(name=u'foo', age=20)
person2 = self.Person(name=u'bar', age=10)
person3 = self.Person(name=u'baz', age=30)
self.session.add_all([person1, person2, person3])
self.session.commit()
query_string = {'sort': '-age'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
age1, age2, age3 = (p['attributes']['age'] for p in people)
assert age1 >= age2 >= age3
def test_sort_multiple_fields(self):
"""Tests that the client can sort by multiple fields.
For more information, see the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
person1 = self.Person(name=u'foo', age=99)
person2 = self.Person(name=u'bar', age=99)
person3 = self.Person(name=u'baz', age=80)
person4 = self.Person(name=u'xyzzy', age=80)
self.session.add_all([person1, person2, person3, person4])
self.session.commit()
# Sort by age, decreasing, then by name, increasing.
query_string = {'sort': '-age,name'}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
people = document['data']
p1, p2, p3, p4 = (p['attributes'] for p in people)
assert p1['age'] == p2['age'] >= p3['age'] == p4['age']
assert p1['name'] <= p2['name']
assert p3['name'] <= p4['name']
def test_sort_relationship_attributes(self):
"""Tests that the client can sort by relationship attributes.
For more information, see the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
person1 = self.Person(age=20)
person2 = self.Person(age=10)
person3 = self.Person(age=30)
article1 = self.Article(id=1, author=person1)
article2 = self.Article(id=2, author=person2)
article3 = self.Article(id=3, author=person3)
self.session.add_all([person1, person2, person3, article1, article2,
article3])
self.session.commit()
query_string = {'sort': 'author.age'}
response = self.app.get('/api/article', query_string=query_string)
document = loads(response.data)
articles = document['data']
assert ['2', '1', '3'] == [c['id'] for c in articles]
def test_sort_multiple_relationship_attributes(self):
"""Tests that the client can sort by multiple relationship
attributes.
For more information, see the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
person1 = self.Person(age=2, name=u'd')
person2 = self.Person(age=1, name=u'b')
person3 = self.Person(age=1, name=u'a')
person4 = self.Person(age=2, name=u'c')
people = [person1, person2, person3, person4]
articles = [self.Article(id=i, author=person)
for i, person in enumerate(people, start=1)]
self.session.add_all(people + articles)
self.session.commit()
query_string = {'sort': 'author.age,author.name'}
response = self.app.get('/api/article', query_string=query_string)
document = loads(response.data)
articles = document['data']
assert ['3', '2', '4', '1'] == [c['id'] for c in articles]
def test_sorting_relationship(self):
"""Tests for sorting relationship objects when requesting
information from a to-many relationship endpoint.
For more information, see the `Sorting`_ section of the JSON API
specification.
.. _Sorting: http://jsonapi.org/format/#fetching-sorting
"""
person = self.Person(id=1)
# In Python 3, the `unicode` class doesn't exist.
try:
to_string = unicode
except NameError:
to_string = str
Article = partial(self.Article, author=person)
articles = [Article(id=i, title=to_string(i)) for i in range(5)]
self.session.add(person)
self.session.add_all(articles)
self.session.commit()
query_string = dict(sort='-title')
response = self.app.get('/api/person/1/relationships/articles',
query_string=query_string)
document = loads(response.data)
articles = document['data']
articleids = [article['id'] for article in articles]
assert ['4', '3', '2', '1', '0'] == articleids
class TestPagination(ManagerTestBase):
"""Tests for pagination links in fetched documents.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
def setUp(self):
super(TestPagination, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(Person)
def test_top_level_pagination_link(self):
"""Tests that there are top-level pagination links by default.
For more information, see the `Top Level`_ section of the JSON
API specification.
.. _Top Level: http://jsonapi.org/format/#document-top-level
"""
response = self.app.get('/api/person')
document = loads(response.data)
links = document['links']
self.assertIn('first', links)
self.assertIn('last', links)
self.assertIn('prev', links)
self.assertIn('next', links)
def test_no_client_parameters(self):
"""Tests that a request without pagination query parameters returns the
first page of the collection.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
response = self.app.get('/api/person')
document = loads(response.data)
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
self.assertIn('/api/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('/api/person?', last)
self.assertIn('page[number]=3', last)
self.assertIs(pagination['prev'], None)
self.assertIn('/api/person?', next_)
self.assertIn('page[number]=2', next_)
self.assertEqual(len(document['data']), 10)
def test_client_page_and_size(self):
"""Tests that a request that specifies both page number and page size
returns the correct page of the collection.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
query_string = {'page[number]': 2, 'page[size]': 3}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
prev = unquote(pagination['prev'])
self.assertIn('/api/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('/api/person?', last)
self.assertIn('page[number]=9', last)
self.assertIn('/api/person?', prev)
self.assertIn('page[number]=1', prev)
self.assertIn('/api/person?', next_)
self.assertIn('page[number]=3', next_)
self.assertEqual(len(document['data']), 3)
def test_client_number_only(self):
"""Tests that a request that specifies only the page number returns the
correct page with the default page size.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
query_string = {'page[number]': 2}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
prev = unquote(pagination['prev'])
self.assertIn('/api/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('/api/person?', last)
self.assertIn('page[number]=3', last)
self.assertIn('/api/person?', prev)
self.assertIn('page[number]=1', prev)
self.assertIn('/api/person?', next_)
self.assertIn('page[number]=3', next_)
self.assertEqual(len(document['data']), 10)
def test_sorted_pagination(self):
"""Tests that pagination is consistent with sorting.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(40)]
self.session.add_all(people)
self.session.commit()
query_string = {'sort': '-id', 'page[number]': 2}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
# In reverse order, the first page should have Person instances with
# IDs 40 through 31, so the second page should have Person instances
# with IDs 30 through 21.
people = document['data']
people_ids = [int(p['id']) for p in people]
self.assertEqual(list(range(30, 20, -1)), people_ids)
# The pagination links should include not only the pagination query
# parameters, but also the same sorting query parameters from the
# client's original quest.
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
prev = unquote(pagination['prev'])
self.assertIn('/api/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('sort=-id', first)
self.assertIn('/api/person?', last)
self.assertIn('page[number]=4', last)
self.assertIn('sort=-id', last)
self.assertIn('/api/person?', prev)
self.assertIn('page[number]=1', prev)
self.assertIn('sort=-id', prev)
self.assertIn('/api/person?', next_)
self.assertIn('page[number]=3', next_)
self.assertIn('sort=-id', next_)
def test_client_size_only(self):
"""Tests that a request that specifies only the page size returns the
first page with the requested page size.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
query_string = {'page[size]': 5}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
self.assertIn('/api/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('/api/person?', last)
self.assertIn('page[number]=5', last)
self.assertIs(pagination['prev'], None)
self.assertIn('/api/person?', next_)
self.assertIn('page[number]=2', next_)
self.assertEqual(len(document['data']), 5)
def test_short_page(self):
"""Tests that a request that specifies the last page may get fewer
resources than the page size.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
query_string = {'page[number]': 3}
response = self.app.get('/api/person', query_string=query_string)
document = loads(response.data)
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
prev = unquote(pagination['prev'])
self.assertIn('/api/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('/api/person?', last)
self.assertIn('page[number]=3', last)
self.assertIn('/api/person?', prev)
self.assertIn('page[number]=2', prev)
self.assertIs(pagination['next'], None)
self.assertEqual(len(document['data']), 5)
def test_server_page_size(self):
"""Tests for setting the default page size on the server side.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
self.manager.create_api(self.Person, url_prefix='/api2', page_size=5)
query_string = {'page[number]': 3}
response = self.app.get('/api2/person', query_string=query_string)
document = loads(response.data)
pagination = document['links']
first = unquote(pagination['first'])
last = unquote(pagination['last'])
next_ = unquote(pagination['next'])
prev = unquote(pagination['prev'])
self.assertIn('/api2/person?', first)
self.assertIn('page[number]=1', first)
self.assertIn('/api2/person?', last)
self.assertIn('page[number]=5', last)
self.assertIn('/api2/person?', prev)
self.assertIn('page[number]=2', prev)
self.assertIn('/api2/person?', next_)
self.assertIn('page[number]=4', next_)
self.assertEqual(len(document['data']), 5)
def test_disable_pagination(self):
"""Tests for disabling default pagination on the server side.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
self.manager.create_api(self.Person, url_prefix='/api2', page_size=0)
response = self.app.get('/api2/person')
document = loads(response.data)
pagination = document['links']
self.assertNotIn('first', pagination)
self.assertNotIn('last', pagination)
self.assertNotIn('prev', pagination)
self.assertNotIn('next', pagination)
assert len(document['data']) == 25
def test_disable_pagination_ignore_client(self):
"""Tests that disabling default pagination on the server side ignores
client page number requests.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
self.manager.create_api(self.Person, url_prefix='/api2', page_size=0)
query_string = {'page[number]': 2}
response = self.app.get('/api2/person', query_string=query_string)
document = loads(response.data)
pagination = document['links']
self.assertNotIn('first', pagination)
self.assertNotIn('last', pagination)
self.assertNotIn('prev', pagination)
self.assertNotIn('next', pagination)
self.assertEqual(len(document['data']), 25)
# TODO Should there be an error here?
def test_max_page_size(self):
"""Tests that the client cannot exceed the maximum page size.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
self.manager.create_api(self.Person, url_prefix='/api2',
max_page_size=15)
query_string = {'page[size]': 20}
response = self.app.get('/api2/person', query_string=query_string)
assert response.status_code == 400
# TODO check the error message here.
def test_negative_page_size(self):
"""Tests that the client cannot specify a negative page size.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
query_string = {'page[size]': -1}
response = self.app.get('/api/person', query_string=query_string)
assert response.status_code == 400
# TODO check the error message here.
def test_negative_page_number(self):
"""Tests that the client cannot specify a negative page number.
For more information, see the `Pagination`_ section of the JSON API
specification.
.. _Pagination: http://jsonapi.org/format/#fetching-pagination
"""
query_string = {'page[number]': -1}
response = self.app.get('/api/person', query_string=query_string)
assert response.status_code == 400
# TODO check the error message here.
def test_headers(self):
"""Tests that paginated requests come with ``Link`` headers.
(This is not part of the JSON API standard, but should live with the
other pagination test methods anyway.)
"""
people = [self.Person() for i in range(25)]
self.session.add_all(people)
self.session.commit()
query_string = {'page[number]': 4, 'page[size]': 3}
response = self.app.get('/api/person', query_string=query_string)
links = response.headers['Link'].split(',')
# Sort Link header strings by relationship name.
links = sorted(links, key=lambda s: REL_REGEX.search(s).group(1))
first, last, next_, prev = map(unquote, links)
self.assertIn('/api/person?', first)
self.assertIn('/api/person?', last)
self.assertIn('/api/person?', prev)
self.assertIn('/api/person?', next_)
self.assertIn('page[size]=3', first)
self.assertIn('page[size]=3', last)
self.assertIn('page[size]=3', prev)
self.assertIn('page[size]=3', next_)
self.assertIn('page[number]=1', first)
self.assertIn('page[number]=9', last)
self.assertIn('page[number]=3', prev)
self.assertIn('page[number]=5', next_)
| 53,491
|
Python
|
.py
| 1,143
| 37.680665
| 79
| 0.631369
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,663
|
test_server_responsibilities.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_server_responsibilities.py
|
# test_server_responsibilities.py - tests JSON API server responsibilities
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Tests that Flask-Restless handles the responsibilities of a server
according to the JSON API specification.
The tests in this module correspond to the `Server Responsibilities`_
section of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
from unittest2 import skip
from sqlalchemy import Column
from sqlalchemy import Unicode
from sqlalchemy import Integer
from flask_restless import JSONAPI_MIMETYPE
from ..helpers import check_sole_error
from ..helpers import dumps
from ..helpers import loads
from ..helpers import ManagerTestBase
class TestServerResponsibilities(ManagerTestBase):
"""Tests corresponding to the `Server Responsibilities`_ section of
the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
def setUp(self):
super(TestServerResponsibilities, self).setUp()
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
self.Base.metadata.create_all()
self.manager.create_api(Person, methods=['GET', 'POST', 'PATCH',
'DELETE'])
def test_get_content_type(self):
""""Tests that a response to a :http:method:`get` request has
the correct content type.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
response = self.app.get('/api/person')
assert response.mimetype == JSONAPI_MIMETYPE
def test_post_content_type(self):
""""Tests that a response to a :http:method:`post` request has
the correct content type.
Our implementation of the JSON API specification always responds
to a :http:method:`post` request with a representation of the
created resource.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
data = {'data': {'type': 'person'}}
response = self.app.post('/api/person', data=dumps(data))
assert response.mimetype == JSONAPI_MIMETYPE
@skip('we currently do not support updates that have side-effects')
def test_patch_content_type(self):
""""Tests that the response for a :http:method:`patch` request
that has side-effects has the correct content type.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'person',
'id': 1,
'attributes': {
'name': 'bar'
}
}
}
# TODO Need to make a request that has side-effects.
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.mimetype == JSONAPI_MIMETYPE
def test_no_response_media_type_params(self):
""""Tests that a server responds with :http:status:`415` if any
media type parameters appear in the request content type header.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
data = {
'data': {
'type': 'person',
}
}
headers = {'Content-Type': '{0}; version=1'.format(JSONAPI_MIMETYPE)}
response = self.app.post('/api/person', data=dumps(data),
headers=headers)
check_sole_error(response, 415, ['Content-Type',
'media type parameters'])
def test_empty_accept_header(self):
"""Tests that an empty :http:header:`Accept` header, which is
technically legal according to :rfc:`2616#sec14.1`, is allowed,
since it is not explicitly forbidden by JSON API.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
headers = {'Accept': ''}
response = self.app.get('/api/person', headers=headers)
assert response.status_code == 200
document = loads(response.data)
assert len(document['data']) == 0
def test_valid_accept_header(self):
"""Tests that we handle requests with an :http:header:`Accept`
header specifying the JSON API mimetype are handled normally.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
headers = {'Accept': JSONAPI_MIMETYPE}
response = self.app.get('/api/person', headers=headers)
assert response.status_code == 200
document = loads(response.data)
assert len(document['data']) == 0
def test_no_accept_media_type_params(self):
""""Tests that a server responds with :http:status:`406` if each
:http:header:`Accept` header is the JSON API media type, but
each instance of that media type has a media type parameter.
For more information, see the `Server Responsibilities`_ section
of the JSON API specification.
.. _Server Responsibilities:
http://jsonapi.org/format/#content-negotiation-servers
"""
headers = {'Accept': '{0}; q=.8, {0}; q=.9'.format(JSONAPI_MIMETYPE)}
response = self.app.get('/api/person', headers=headers)
check_sole_error(response, 406, ['Accept', 'media type parameter'])
| 6,798
|
Python
|
.py
| 147
| 37.462585
| 77
| 0.650325
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,664
|
test_updating_relationships.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_updating_relationships.py
|
# test_updating_relationships.py - tests updating relationships via JSON API
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for requests that update relationships.
The tests in this module correspond to the `Updating Relationships`_
section of the JSON API specification.
.. _Updating Relationships:
http://jsonapi.org/format/#crud-updating-relationships
"""
from operator import attrgetter
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy.orm import relationship
from ..helpers import dumps
from ..helpers import ManagerTestBase
class TestUpdatingRelationships(ManagerTestBase):
"""Tests corresponding to the `Updating Relationships`_ section of the JSON
API specification.
.. _Updating Relationships:
http://jsonapi.org/format/#crud-updating-relationships
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestUpdatingRelationships, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
articles = relationship('Article')
self.Article = Article
self.Person = Person
self.Base.metadata.create_all()
self.manager.create_api(self.Person, methods=['PATCH'])
self.manager.create_api(self.Article, methods=['PATCH'])
def test_to_one(self):
"""Tests for updating a to-one relationship via a :http:method:`patch`
request to a relationship URL.
For more information, see the `Updating To-One Relationships`_ section
of the JSON API specification.
.. _Updating To-One Relationships:
http://jsonapi.org/format/#crud-updating-to-one-relationships
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article = self.Article(id=1)
article.author = person1
self.session.add_all([person1, person2, article])
self.session.commit()
data = dict(data=dict(type='person', id='2'))
response = self.app.patch('/api/article/1/relationships/author',
data=dumps(data))
assert response.status_code == 204
assert article.author is person2
def test_remove_to_one(self):
"""Tests for removing a to-one relationship via a :http:method:`patch`
request to a relationship URL.
For more information, see the `Updating To-One Relationships`_ section
of the JSON API specification.
.. _Updating To-One Relationships:
http://jsonapi.org/format/#crud-updating-to-one-relationships
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article = self.Article(id=1)
article.author = person1
self.session.add_all([person1, person2, article])
self.session.commit()
data = dict(data=None)
response = self.app.patch('/api/article/1/relationships/author',
data=dumps(data))
assert response.status_code == 204
assert article.author is None
def test_to_many(self):
"""Tests for replacing a to-many relationship via a
:http:method:`patch` request to a relationship URL.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
self.session.add_all([person, article1, article2])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_to_many_replacement=True)
data = {'data': [{'type': 'article', 'id': '1'},
{'type': 'article', 'id': '2'}]}
response = self.app.patch('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
articles = sorted(person.articles, key=attrgetter('id'))
assert [article1, article2] == articles
def test_to_many_not_found(self):
"""Tests that an attempt to replace a to-many relationship with a
related resource that does not exist yields an error response.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article = self.Article(id=1)
self.session.add_all([person, article])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_to_many_replacement=True)
data = {'data': [{'type': 'article', 'id': '1'},
{'type': 'article', 'id': '2'}]}
response = self.app.patch('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 404
# TODO test error messages
def test_to_many_forbidden(self):
"""Tests that full replacement of a to-many relationship is forbidden
by the server configuration, then the response is :http:status:`403`.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {'data': []}
response = self.app.patch('/api/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 403
# TODO test error messages
def test_to_many_append(self):
"""Tests for appending to a to-many relationship via a
:http:method:`post` request to a relationship URL.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
self.session.add_all([person, article1, article2])
self.session.commit()
data = {'data': [{'type': 'article', 'id': '1'},
{'type': 'article', 'id': '2'}]}
response = self.app.post('/api/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
articles = sorted(person.articles, key=attrgetter('id'))
assert [article1, article2] == articles
def test_to_many_preexisting(self):
"""Tests for attempting to append an element that already exists in a
to-many relationship via a :http:method:`post` request to a
relationship URL.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article = self.Article(id=1)
person.articles = [article]
self.session.add_all([person, article])
self.session.commit()
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.post('/api/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert person.articles == [article]
def test_to_many_delete(self):
"""Tests for deleting from a to-many relationship via a
:http:method:`delete` request to a relationship URL.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_delete_from_to_many_relationships=True)
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.delete('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert person.articles == [article2]
def test_to_many_delete_nonexistent(self):
"""Tests for deleting a nonexistent member from a to-many relationship
via a :http:method:`delete` request to a relationship URL.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1]
self.session.add_all([person, article1, article2])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_delete_from_to_many_relationships=True)
data = {'data': [{'type': 'article', 'id': '2'}]}
response = self.app.delete('/api2/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 204
assert person.articles == [article1]
def test_to_many_delete_forbidden(self):
"""Tests that attempting to delete from a to-many relationship via a
:http:method:`delete` request to a relationship URL when the server has
disallowed it yields a :http:status:`409` response.
For more information, see the `Updating To-Many Relationships`_ section
of the JSON API specification.
.. _Updating To-Many Relationships:
http://jsonapi.org/format/#crud-updating-to-many-relationships
"""
person = self.Person(id=1)
article = self.Article(id=1)
person.articles = [article]
self.session.add_all([person, article])
self.session.commit()
data = {'data': [{'type': 'article', 'id': '1'}]}
response = self.app.delete('/api/person/1/relationships/articles',
data=dumps(data))
assert response.status_code == 403
assert person.articles == [article]
| 12,213
|
Python
|
.py
| 251
| 38.231076
| 79
| 0.622271
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,665
|
test_updating_resources.py
|
jfinkels_flask-restless/tests/test_jsonapi/test_updating_resources.py
|
# test_updating_resources.py - tests updating resources according to JSON API
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Unit tests for updating resources according to the JSON API
specification.
The tests in this module correspond to the `Updating Resources`_ section
of the JSON API specification.
.. _Updating Resources: http://jsonapi.org/format/#crud-updating
"""
from operator import attrgetter
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.orm import relationship
from ..helpers import check_sole_error
from ..helpers import dumps
from ..helpers import loads
from ..helpers import ManagerTestBase
class TestUpdatingResources(ManagerTestBase):
"""Tests corresponding to the `Updating Resources`_ section of the JSON API
specification.
.. _Updating Resources: http://jsonapi.org/format/#crud-updating
"""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`TestSupport.Person`
and :class:`TestSupport.Article` models.
"""
super(TestUpdatingResources, self).setUp()
class Article(self.Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('person.id'))
author = relationship('Person')
class Person(self.Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(Unicode, unique=True)
age = Column(Integer)
articles = relationship('Article')
class Tag(self.Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
updated_at = Column(DateTime, server_default=func.now(),
onupdate=func.current_timestamp())
self.Article = Article
self.Person = Person
self.Tag = Tag
self.Base.metadata.create_all()
self.manager.create_api(Article, methods=['PATCH'])
self.manager.create_api(Person, methods=['PATCH'])
self.manager.create_api(Tag, methods=['GET', 'PATCH'])
def test_update(self):
"""Tests that the client can update a resource's attributes.
For more information, see the `Updating a Resource's Attributes`_
section of the JSON API specification.
.. _Updating a Resource's Attributes:
http://jsonapi.org/format/#crud-updating-resource-attributes
"""
person = self.Person(id=1, name=u'foo', age=10)
self.session.add(person)
self.session.commit()
data = dict(data=dict(type='person', id='1',
attributes=dict(name=u'bar')))
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 204
assert person.id == 1
assert person.name == 'bar'
assert person.age == 10
def test_to_one(self):
"""Tests that the client can update a resource's to-one relationships.
For more information, see the `Updating a Resource's To-One
Relationships`_ section of the JSON API specification.
.. _Updating a Resource's To-One Relationships:
http://jsonapi.org/format/#crud-updating-resource-to-one-relationships
"""
person1 = self.Person(id=1)
person2 = self.Person(id=2)
article = self.Article(id=1)
person1.articles = [article]
self.session.add_all([person1, person2, article])
self.session.commit()
# Change the author of the article from person 1 to person 2.
data = {
'data': {
'type': 'article',
'id': '1',
'relationships': {
'author': {
'data': {'type': 'person', 'id': '2'}
}
}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
assert response.status_code == 204
assert article.author is person2
def test_remove_to_one(self):
"""Tests that the client can remove a resource's to-one relationship.
For more information, see the `Updating a Resource's To-One
Relationships`_ section of the JSON API specification.
.. _Updating a Resource's To-One Relationships:
http://jsonapi.org/format/#crud-updating-resource-to-one-relationships
"""
person = self.Person(id=1)
article = self.Article()
person.articles = [article]
self.session.add_all([person, article])
self.session.commit()
# Change the author of the article to None.
data = {
'data': {
'type': 'article',
'id': '1',
'relationships': {'author': {'data': None}}
}
}
response = self.app.patch('/api/article/1', data=dumps(data))
assert response.status_code == 204
assert article.author is None
def test_to_many(self):
"""Tests that the client can update a resource's to-many relationships.
For more information, see the `Updating a Resource's To-Many
Relationships`_ section of the JSON API specification.
.. _Updating a Resource's To-Many Relationships:
http://jsonapi.org/format/#crud-updating-resource-to-many-relationships
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
self.session.add_all([person, article1, article2])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_to_many_replacement=True)
data = {
'data': {
'type': 'person',
'id': '1',
'relationships': {
'articles': {
'data': [
{'type': 'article', 'id': '1'},
{'type': 'article', 'id': '2'}
]
}
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
assert response.status_code == 204
articles = sorted(person.articles, key=attrgetter('id'))
assert [article1, article2] == articles
def test_to_many_clear(self):
"""Tests that the client can clear a resource's to-many relationships.
For more information, see the `Updating a Resource's To-Many
Relationships`_ section of the JSON API specification.
.. _Updating a Resource's To-Many Relationships:
http://jsonapi.org/format/#crud-updating-resource-to-many-relationships
"""
person = self.Person(id=1)
article1 = self.Article(id=1)
article2 = self.Article(id=2)
person.articles = [article1, article2]
self.session.add_all([person, article1, article2])
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_to_many_replacement=True)
data = {
'data': {
'type': 'person',
'id': '1',
'relationships': {
'articles': {
'data': []
}
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
assert response.status_code == 204
assert person.articles == []
def test_to_many_forbidden(self):
"""Tests that the client receives a :http:status:`403` if the server
has been configured to disallow full replacement of a to-many
relationship.
For more information, see the `Updating a Resource's To-Many
Relationships`_ section of the JSON API specification.
.. _Updating a Resource's To-Many Relationships:
http://jsonapi.org/format/#crud-updating-resource-to-many-relationships
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'person',
'id': '1',
'relationships': {'articles': {'data': []}}
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 403
def test_other_modifications(self):
"""Tests that if an update causes additional changes in the resource in
ways other than those specified by the client, the response has status
:http:status:`200` and includes the updated resource.
For more information, see the `200 OK`_ section of the JSON API
specification.
.. _200 OK: http://jsonapi.org/format/#crud-updating-responses-200
"""
tag = self.Tag(id=1)
self.session.add(tag)
self.session.commit()
data = {
'data': {
'type': 'tag',
'id': '1',
'attributes': {
'name': u'foo'
}
}
}
response = self.app.patch('/api/tag/1', data=dumps(data))
assert response.status_code == 200
document = loads(response.data)
tag1 = document['data']
response = self.app.get('/api/tag/1')
document = loads(response.data)
tag2 = document['data']
assert tag1 == tag2
def test_nonexistent(self):
"""Tests that an attempt to update a nonexistent resource causes a
:http:status:`404` response.
For more information, see the `404 Not Found`_ section of the JSON API
specification.
.. _404 Not Found:
http://jsonapi.org/format/#crud-updating-responses-404
"""
data = dict(data=dict(type='person', id='1'))
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 404
def test_nonexistent_relationship(self):
"""Tests that an attempt to update a nonexistent resource causes a
:http:status:`404` response.
For more information, see the `404 Not Found`_ section of the JSON API
specification.
.. _404 Not Found:
http://jsonapi.org/format/#crud-updating-responses-404
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2',
allow_to_many_replacement=True)
data = {
'data': {
'type': 'person',
'id': '1',
'relationships': {
'articles': {'data': [{'type': 'article', 'id': '1'}]}
}
}
}
response = self.app.patch('/api2/person/1', data=dumps(data))
assert response.status_code == 404
# TODO test for error details
def test_conflicting_attributes(self):
"""Tests that an attempt to update a resource with a non-unique
attribute value where uniqueness is required causes a
:http:status:`409` response.
For more information, see the `409 Conflict`_ section of the JSON API
specification.
.. _409 Conflict:
http://jsonapi.org/format/#crud-updating-responses-409
"""
person1 = self.Person(id=1, name=u'foo')
person2 = self.Person(id=2)
self.session.add_all([person1, person2])
self.session.commit()
data = dict(data=dict(type='person', id='2',
attributes=dict(name=u'foo')))
response = self.app.patch('/api/person/2', data=dumps(data))
assert response.status_code == 409
# TODO test for error details
def test_conflicting_type(self):
"""Tests that an attempt to update a resource with the wrong type
causes a :http:status:`409` response.
For more information, see the `409 Conflict`_ section of the JSON API
specification.
.. _409 Conflict:
http://jsonapi.org/format/#crud-updating-responses-409
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = {
'data': {
'type': 'bogus',
'id': '1'
}
}
response = self.app.patch('/api/person/1', data=dumps(data))
check_sole_error(response, 409, ['expected', 'type', 'person',
'bogus'])
def test_conflicting_id(self):
"""Tests that an attempt to update a resource with the wrong ID causes
a :http:status:`409` response.
For more information, see the `409 Conflict`_ section of the JSON API
specification.
.. _409 Conflict:
http://jsonapi.org/format/#crud-updating-responses-409
"""
person = self.Person(id=1)
self.session.add(person)
self.session.commit()
data = dict(data=dict(type='person', id='bogus'))
response = self.app.patch('/api/person/1', data=dumps(data))
assert response.status_code == 409
# TODO test for error details
| 14,188
|
Python
|
.py
| 335
| 31.641791
| 82
| 0.582016
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,666
|
__init__.py
|
jfinkels_flask-restless/tests/test_jsonapi/__init__.py
|
# __init__.py - indicates that this directory is a Python package
#
# Copyright 2011 Lincoln de Sousa <lincoln@comum.org>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <jeffrey.finkelstein@gmail.com> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distributed under both the GNU Affero General Public
# License version 3 and under the 3-clause BSD license. For more
# information, see LICENSE.AGPL and LICENSE.BSD.
"""Tests that ensure that Flask-Restless meets the requirements of the
JSON API specification.
Each module in this package corresponds to a section of the
specification; for example, the :mod:`test_fetching_data` module
corresponds to the `Fetching Data`_ section of the `JSON API`_
specification.
.. _JSON API: http://jsonapi.org
.. _Fetching Data: http://jsonapi.org/format/#fetching
"""
| 869
|
Python
|
.py
| 20
| 42.3
| 72
| 0.771868
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,667
|
make-release.py
|
jfinkels_flask-restless/scripts/make-release.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make-release
~~~~~~~~~~~~
Helper script that performs a release. Does pretty much everything
automatically for us.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
import os
import re
from datetime import datetime, date
from subprocess import Popen, PIPE
_date_clean_re = re.compile(r'(\d+)(st|nd|rd|th)')
def add_new_changelog_section(current_version, next_version):
version_string = 'Version {}'.format(current_version)
with open('CHANGES') as f:
all_lines = f.readlines()
stripped_lines = [l.strip() for l in all_lines]
try:
# get the index of the first occurrence of `version_string`
line_num = stripped_lines.index(version_string)
except:
fail('Could not find "{}" in {}.'.format(version_string, 'CHANGES'))
new_header = 'Version {}'.format(next_version)
horizontal_rule = '-' * len(new_header)
new_lines = [new_header + '\n', horizontal_rule + '\n', '\n',
'Not yet released.' + '\n', '\n']
# insert the new lines into the list of all lines read from CHANGES
all_lines[line_num:line_num] = new_lines
# write the changes back to...CHANGES
with open('CHANGES', 'w') as f:
f.writelines(all_lines)
def parse_changelog():
with open('CHANGES') as f:
lineiter = iter(f)
for line in lineiter:
match = re.search('^Version\s+(.*)', line.strip())
if match is None:
continue
# length = len(match.group(1))
version = match.group(1).strip()
if lineiter.next().count('-') != len(match.group(0)):
continue
while 1:
change_info = lineiter.next().strip()
if change_info:
break
match = re.search(r'Released on (\w+\s+\d+,\s+\d+)',
change_info)
if match is None:
continue
datestr = match.groups()[0]
return version, parse_date(datestr)
def bump_version(version):
try:
parts = map(int, version.split('.'))
except ValueError:
fail('Current version is not numeric')
if sys.argv[1] == 'major':
parts = [parts[0] + 1, 0, 0]
elif sys.argv[1] == 'minor':
parts = [parts[0], parts[1] + 1, 0]
else:
parts[-1] += 1
return '.'.join(map(str, parts))
def parse_date(string):
string = _date_clean_re.sub(r'\1', string)
return datetime.strptime(string, '%B %d, %Y')
def set_filename_version(filename, version_number, pattern):
changed = []
def inject_version(match):
before, old, after = match.groups()
changed.append(True)
return before + version_number + after
with open(filename) as f:
contents = re.sub(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern,
inject_version, f.read())
if not changed:
fail('Could not find %s in %s', pattern, filename)
with open(filename, 'w') as f:
f.write(contents)
def set_init_version(version):
info('Setting __init__.py version to %s', version)
set_filename_version('flask_restless/__init__.py', version, '__version__')
def set_setup_version(version):
info('Setting setup.py version to %s', version)
set_filename_version('setup.py', version, 'version')
def build():
Popen([sys.executable, 'setup.py', 'sdist', 'bdist_wheel']).wait()
def sign(version):
bdist_wheel = 'dist/Flask_Restless-{0}-py2.py3-none-any.whl'
bdist_wheel = bdist_wheel.format(version)
sdist = 'dist/Flask-Restless-{0}.tar.gz'.format(version)
Popen(['gpg', '--detach-sign', '-a', bdist_wheel]).wait()
Popen(['gpg', '--detach-sign', '-a', sdist]).wait()
def upload(version):
bdist_wheel = 'dist/Flask_Restless-{0}-py2.py3-none-any.whl'
bdist_wheel = bdist_wheel.format(version)
bdist_wheel_signature = '{0}.asc'.format(bdist_wheel)
sdist = 'dist/Flask-Restless-{0}.tar.gz'.format(version)
sdist_signature = '{0}.asc'.format(bdist_wheel)
files = [sdist, sdist_signature, bdist_wheel, bdist_wheel_signature]
Popen(['twine', 'upload'] + files).wait()
def fail(message, *args):
print >> sys.stderr, 'Error:', message % args
sys.exit(1)
def info(message, *args):
print >> sys.stderr, message % args
def get_git_tags():
process = Popen(['git', 'tag'], stdout=PIPE)
return set(process.communicate()[0].splitlines())
def git_is_clean():
return Popen(['git', 'diff', '--quiet']).wait() == 0
def make_git_commit(message, *args):
message = message % args
Popen(['git', 'commit', '-am', message]).wait()
def make_git_tag(tag):
info('Tagging "%s"', tag)
msg = '"Released version {}"'.format(tag)
Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()
def main():
os.chdir(os.path.join(os.path.dirname(__file__), '..'))
rv = parse_changelog()
if rv is None:
fail('Could not parse changelog')
version, release_date = rv
dev_version = bump_version(version) + '-dev'
info('Releasing %s (release date %s)',
version, release_date.strftime('%d/%m/%Y'))
tags = get_git_tags()
if version in tags:
fail('Version "%s" is already tagged', version)
if release_date.date() != date.today():
fail('Release date is not today (%s != %s)')
if not git_is_clean():
fail('You have uncommitted changes in git')
set_init_version(version)
# set_setup_version(version)
make_git_commit('Bump version number to %s', version)
make_git_tag(version)
build()
sign(version)
upload(version)
set_init_version(dev_version)
# set_setup_version(dev_version)
add_new_changelog_section(version, dev_version)
make_git_commit('Set development version number to %s', dev_version)
print('*************************************')
print('* *')
print('* Now run *')
print('* *')
print('* git push --tags origin master *')
print('* *')
print('*************************************')
if __name__ == '__main__':
main()
| 6,337
|
Python
|
.py
| 159
| 33.295597
| 78
| 0.58453
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,668
|
set-version.py
|
jfinkels_flask-restless/scripts/set-version.py
|
def set_filename_version(filename, version_number, pattern):
changed = []
def inject_version(match):
before, old, after = match.groups()
changed.append(True)
return before + version_number + after
with open(filename) as f:
contents = re.sub(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern,
inject_version, f.read())
if not changed:
fail('Could not find %s in %s', pattern, filename)
with open(filename, 'w') as f:
f.write(contents)
def set_changelog_version(version):
info('Setting CHANGES version to %s', version)
# TODO this won't work...
set_filename_version('CHANGES', version, 'Version')
def set_init_version(version):
info('Setting __init__.py version to %s', version)
set_filename_version('flask_restless/__init__.py', version, '__version__')
def set_setup_version(version):
info('Setting setup.py version to %s', version)
set_filename_version('setup.py', version, 'version')
| 1,007
|
Python
|
.py
| 23
| 37.173913
| 78
| 0.635619
|
jfinkels/flask-restless
| 1,020
| 301
| 111
|
AGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,669
|
.pyup.yml
|
buffer_thug/.pyup.yml
|
# autogenerated pyup.io config file
# see https://pyup.io/docs/configuration/ for all available options
update: insecure
| 122
|
Python
|
.py
| 3
| 39.333333
| 67
| 0.813559
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,670
|
thugd.py
|
buffer_thug/tools/distributed/thugd.py
|
#!/usr/bin/env python
"""
Thug daemon
By thorsten.sick@avira.com
For the iTES project (www.ites-project.org)
"""
import os
import sys
import json
import shutil
import argparse
import subprocess
import configparser
import pika
class Thugd(object):
"""
A class waiting for jobs, starting thug, returning results
"""
def __init__(self, configfile, clear=False):
"""
@configfile: The configuration file to use
@clear: Clear the job chain
"""
self.clear = clear
self.username = "guest"
self.password = "guest"
self._read_config(configfile)
self._chdir()
self._run_queue()
def _read_config(self, configfile):
"""
read_config
Read configuration from configuration file
@configfile: The configfile to use
"""
self.host = "localhost"
self.queue = "thugctrl"
self.rhost = "localhost"
self.rqueue = "thugres"
if configfile is None:
return
conf = configparser.ConfigParser()
conf.read(configfile)
self.host = conf.get("jobs", "host")
self.queue = conf.get("jobs", "queue")
self.rhost = conf.get("results", "host")
self.rqueue = conf.get("results", "queue")
self.resdir = conf.get("results", "resdir")
self.username = conf.get("credentials", "username")
self.password = conf.get("credentials", "password")
def _chdir(self):
os.chdir(
os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "src")
)
)
def _run_queue(self):
credentials = pika.PlainCredentials(self.username, self.password)
parameters = pika.ConnectionParameters(host=self.host, credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.queue_declare(queue=self.queue, durable=True)
print(
"[*] Waiting for messages on %s %s (press CTRL+C to exit)"
% (
self.host,
self.queue,
)
)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
lambda c, m, p, b: self.callback(c, m, p, b), queue=self.queue
)
channel.start_consuming()
def runProcess(self, exe):
p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
retcode = p.poll()
line = p.stdout.readline()
yield line
if retcode is not None:
break
def send_results(self, data):
credentials = pika.PlainCredentials(self.username, self.password)
parameters = pika.ConnectionParameters(host=self.rhost, credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.queue_declare(queue=self.rqueue, durable=True)
message = json.dumps(data)
channel.basic_publish(
exchange="",
routing_key=self.rqueue,
body=message,
properties=pika.BasicProperties(
delivery_mode=2,
),
)
print("[x] Sent %r" % (message,))
connection.close()
def copy_to_result(self, frompath, job):
"""
Copy result folder to result path
"""
if not frompath:
return None
respath = os.path.join(self.resdir, str(job["id"]))
shutil.copytree(frompath, respath)
return os.path.relpath(respath, self.resdir)
def process(self, job):
"""
Execute thug to process a job
"""
print("job" + str(job))
print(os.getcwd())
command = ["python", "thug.py", "-t", str(job["threshold"])]
if job["extensive"]:
command.append("-E")
if job["timeout"]:
command.append("-T")
command.append(str(job["timeout"]))
if job["referer"]:
command.append("-r")
command.append(job["referer"])
if job["proxy"]:
command.append("-p")
command.append(job["proxy"])
command.append(job["url"])
print(command)
pathname = None
for line in self.runProcess(command):
if line.startswith("["):
print(line, end=" ")
if line.find("] Saving log analysis at ") >= 0:
pathname = line.split(" ")[-1].strip()
rpath = self.copy_to_result(pathname, job)
res = {"id": job["id"], "rpath": rpath}
self.send_results(res)
def callback(self, ch, method, properties, body):
print("[x] Received %r" % (body,))
if not self.clear:
self.process(json.loads(body))
print("[x] Done")
ch.basic_ack(delivery_tag=method.delivery_tag)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Receives jobs and starts Thug to process them"
)
parser.add_argument(
"--config", help="Configuration file to use", default="config.ini"
)
parser.add_argument(
"--clear", help="Clear the job chain", default=False, action="store_true"
)
args = parser.parse_args()
try:
t = Thugd(args.config, args.clear)
except KeyboardInterrupt:
sys.exit(0)
| 5,467
|
Python
|
.py
| 158
| 25.651899
| 88
| 0.579806
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,671
|
thugctrl.py
|
buffer_thug/tools/distributed/thugctrl.py
|
#!/usr/bin/env python
"""Thug Control
Send commands to Thug
"""
import json
import datetime
import argparse
import configparser
from urllib.parse import urlparse
import pika
class ThugCtrl(object):
"""Thug remote control"""
def __init__(
self,
configfile,
extensive=False,
threshold=0,
referer=None,
proxy=None,
timeout=None,
):
"""Init Thugd using config file"""
self.host = "localhost"
self.queue = "thugctrl"
self.username = "guest"
self.password = "guest"
self.extensive = extensive
self.threshold = threshold
self.referer = referer
self.proxy = proxy
self.timeout = timeout
self.configfile = configfile
self.read_config()
def read_config(self):
"""Read config from config file"""
conf = configparser.ConfigParser()
conf.read(self.configfile)
self.host = conf.get("jobs", "host")
self.queue = conf.get("jobs", "queue")
self.username = conf.get("credentials", "username")
self.password = conf.get("credentials", "password")
def send_command(self, data):
credentials = pika.PlainCredentials(self.username, self.password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=self.host, credentials=credentials)
)
channel = connection.channel()
channel.queue_declare(queue=self.queue, durable=True)
message = json.dumps(data)
channel.basic_publish(
exchange="",
routing_key=self.queue,
body=message,
properties=pika.BasicProperties(
delivery_mode=2,
),
)
print(" [x] Sent %r" % (message,))
connection.close()
def process(self, url):
"""Send URL to process"""
if url.find("://") < 0:
url = "http://" + url
o = urlparse(url)
jid = o.netloc + "_" + datetime.datetime.now().strftime("%Y_%m_%d__%H_%M_%S")
data = {
"url": url,
"id": jid,
"threshold": self.threshold,
"extensive": self.extensive,
"referer": self.referer,
"proxy": self.proxy,
"timeout": self.timeout,
}
print(data)
self.send_command(data)
class ThugCollect(object):
"""A class collecting thug results"""
def process(self, data):
print(data)
def callback(self, ch, method, properties, body):
self.process(json.loads(body))
ch.basic_ack(delivery_tag=method.delivery_tag)
def __init__(self, configfile):
self.configfile = configfile
self.host = "localhost"
self.queue = "thugctrl"
self.rhost = "localhost"
self.rqueue = "thugres"
self.username = "guest"
self.password = "guest"
self.read_config()
credentials = pika.PlainCredentials(self.username, self.password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=self.rhost, credentials=credentials)
)
channel = connection.channel()
channel.queue_declare(queue=self.rqueue, durable=True)
print(
" [*] Waiting for messages on %s %s To exit press CTRL+C"
% (self.rhost, self.rqueue)
)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
lambda c, m, p, b: self.callback(c, m, p, b), queue=self.rqueue
)
channel.start_consuming()
def read_config(self):
"""Read config from config file"""
conf = configparser.ConfigParser()
conf.read(self.configfile)
self.host = conf.get("jobs", "host")
self.queue = conf.get("jobs", "queue")
self.rhost = conf.get("results", "host")
self.rqueue = conf.get("results", "queue")
self.username = conf.get("credentials", "username")
self.password = conf.get("credentials", "password")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Send urls to Thug daemons tp process")
parser.add_argument(
"--urls", type=str, nargs="+", help="One or more URLs to process"
)
parser.add_argument("--config", help="Config file to use", default="config.ini")
parser.add_argument(
"--collect_results",
help="Start a daemon to collect the results",
default=False,
action="store_true",
)
parser.add_argument(
"--extensive", help="In depth follow links", default=False, action="store_true"
)
parser.add_argument(
"--threshold", type=int, help="Maximum pages to fetch", default=0
)
parser.add_argument("--referer", type=str, help="Referer to send", default=None)
parser.add_argument("--proxy", type=str, help="Proxy to use", default=None)
parser.add_argument(
"--timeout", type=int, help="Timeout in seconds for the analysis", default=None
)
args = parser.parse_args()
if args.urls:
t = ThugCtrl(
args.config,
args.extensive,
args.threshold,
args.referer,
args.proxy,
args.timeout,
)
for aurl in args.urls:
t.process(aurl)
if args.collect_results:
res = ThugCollect(args.config)
| 5,418
|
Python
|
.py
| 154
| 26.649351
| 88
| 0.595256
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,672
|
MongoUtils.py
|
buffer_thug/utils/MongoUtils.py
|
#!/usr/bin/env python
#
# MongoUtils.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
import sys
import getopt
MONGO_MODULE = True
try:
import gridfs
import pymongo
from bson.objectid import ObjectId
except ImportError:
MONGO_MODULE = False
class MongoUtils(object):
def __init__(self, host="localhost", port=27017):
self.__check_mongo_module()
self.__init_db(host, port)
def __check_mongo_module(self):
if not MONGO_MODULE:
print("[MongoUtils] PyMongo not installed. Please install it and retry.")
sys.exit(0)
def __init_db(self, host, port):
# MongoDB Connection class is marked as deprecated (MongoDB >= 2.4).
# The following code tries to use the new MongoClient if available and
# reverts to the old Connection class if not. This code will hopefully
# disappear in the next future.
client = getattr(pymongo, "MongoClient", None)
if client is None:
client = getattr(pymongo, "Connection", None)
try:
connection = client(host, int(port))
except Exception:
print("[MongoUtils] MongoDB instance not available")
sys.exit(0)
db = connection.thug
dbfs = connection.thugfs
self.urls = db.urls
self.analyses = db.analyses
self.thugfs = gridfs.GridFS(dbfs)
self.collections = (
db.urls,
db.analyses,
db.locations,
db.connections,
db.graphs,
db.samples,
db.behaviors,
db.certificates,
db.honeyagent,
db.exploits,
db.codes,
db.json,
)
def list_analyses(self):
print("ID\t\t\t\t| URL\t\t\t\t| Analysis datetime\n")
for analysis in self.analyses.find():
urls = self.urls.find(_id=analysis["url_id"])
if not urls:
continue
url = urls[0]["url"]
print("%s\t| %s\t| %s" % (analysis["_id"], url, analysis["timestamp"]))
def remove_analysis(self, analysis):
analysis_id = analysis["_id"]
for collection in self.collections:
collection.remove({"_id": analysis_id})
self.thugfs.delete({"_id": analysis_id})
def query_analysis_by_id(self, analysis_id):
analysis = self.analyses.find_one({"_id": ObjectId(analysis_id)})
if not analysis:
print("[MongoUtils] Analysis ID not found")
return None
return analysis
def usage():
msg = """
Synopsis:
MongoUtils.py
Usage:
python MongoUtils.py [ options ]
Options:
-h, --help \tDisplay this help information
-l, --ls \tList all the analyses
-r, --rm= \tRemove the analysis identified by the specified ID
-M, --mongodb-address= \tSpecify address and port of the MongoDB instance (format: host:port)
"""
print(msg)
sys.exit(0)
def main(args):
host = "localhost"
port = 27017
try:
options, args = getopt.getopt(
args, "hlr:M:", ["help", "ls", "rm=", "mongodb-address="]
)
except getopt.GetoptError:
usage()
if not options and not args:
usage()
for option in options:
if option[0] in ("-h", "--help"):
usage()
elif option[0] in ("-M", "--mongodb-address"):
host, port = option[1].split(":")
mongoutils = MongoUtils(host, port)
for option in options:
if option[0] in ("-l", "--ls"):
mongoutils.list_analyses()
for option in options:
if option[0] in ("-r", "--rm"):
analysis = mongoutils.query_analysis_by_id(option[1])
if analysis:
mongoutils.remove_analysis(analysis)
if __name__ == "__main__":
main(sys.argv[1:])
| 4,519
|
Python
|
.py
| 126
| 28.111111
| 102
| 0.603622
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,673
|
conf.py
|
buffer_thug/docs/source/conf.py
|
# -*- coding: utf-8 -*-
#
# Thug documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 13 00:07:06 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'python_docs_theme',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Thug'
copyright = u'2011-2024, Angelo Dell\'Aera'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '6.9'
# The full version, including alpha/beta/rc tags.
release = '6.9'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'python_docs_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': [
#'navigation.html',
'relations.html',
'searchbox.html',
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Thugdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Thug.tex', u'Thug Documentation',
u'Angelo Dell\'Aera', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'thug', u'Thug Documentation',
[u'Angelo Dell\'Aera'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Thug', u'Thug Documentation',
u'Angelo Dell\'Aera', 'Thug', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| 7,851
|
Python
|
.py
| 186
| 40.537634
| 80
| 0.721447
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,674
|
test_Honeyagent.py
|
buffer_thug/tests/Analysis/test_Honeyagent.py
|
import os
import logging
from mock import patch
from mock import Mock
import thug
from thug.Analysis.honeyagent import HoneyAgent
from thug.ThugAPI.ThugOpts import ThugOpts
from thug.Logging.ThugLogging import ThugLogging
configuration_path = thug.__configuration_path__
log = logging.getLogger("Thug")
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.ThugOpts = ThugOpts()
log.PyHooks = dict()
log.configuration_path = configuration_path
log.ThugLogging = ThugLogging()
HAGENT = HoneyAgent.HoneyAgent()
class mock_cls:
"""Mock class for other required methods in log"""
def __getattr__(self, attr):
return lambda *args: None
class mock_log:
"""Mock class for log"""
def __init__(self):
self.data = []
self.ThugOpts = mock_cls()
self.ThugLogging = mock_cls()
def warning(self, *args):
self.data.append(args)
class TestHoneyAgent:
cwd_path = os.path.dirname(os.path.realpath(__file__))
samples_path = os.path.join(cwd_path, os.pardir, os.pardir, "tests/test_files")
# Mock requests POST method
@patch("requests.post")
def test_analyze(self, mocked_post):
expected = [
("d4be8fbeb3a219ec8c6c26ffe4033a16",),
("d4be8fbeb3a219ec8c6c26ffe4033a16", "file"),
("d4be8fbeb3a219ec8c6c26ffe4033a16", "heuristics", "LocalFileAccess"),
]
sample = {"type": "JAR", "md5": "d4be8fbeb3a219ec8c6c26ffe4033a16"}
jar_path = os.path.join(self.samples_path, "sample.jar")
with open(jar_path, "rb") as f:
data = f.read()
json_data = lambda: { # noqa: E731
"result": {
"files": {"file": "test"},
"yara": {"heuristics": [{"rule": "LocalFileAccess"}]},
}
}
mocked_post.return_value = Mock(json=json_data)
_log = HoneyAgent.log
HoneyAgent.log = mock_log()
HAGENT.enabled = True
HAGENT.opts = {"enable": True, "scanurl": "http://test.com"}
HAGENT.analyze(data, sample, self.samples_path, None)
mock_data = [dat[1:] for dat in HoneyAgent.log.data]
assert mock_data == expected
HoneyAgent.log = _log
| 2,248
|
Python
|
.py
| 58
| 31.948276
| 84
| 0.647575
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,675
|
test_Plugin.py
|
buffer_thug/tests/DOM/test_Plugin.py
|
from thug.DOM.Plugin import Plugin
class TestPlugin(object):
def test_items(self):
plugin = Plugin()
plugin["test1"] = "value1"
assert plugin["test1"] in ("value1",)
plugin.test2 = "value2"
assert plugin.test2 in ("value2",)
del plugin["test1"]
del plugin.test2
assert plugin["test3"] is None
del plugin["test3"]
| 395
|
Python
|
.py
| 12
| 25.083333
| 45
| 0.602122
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,676
|
test_JSInspector.py
|
buffer_thug/tests/DOM/test_JSInspector.py
|
import logging
import thug
from thug.ThugAPI.ThugOpts import ThugOpts
from thug.DOM.JSInspector import JSInspector
configuration_path = thug.__configuration_path__
log = logging.getLogger("Thug")
log.configuration_path = configuration_path
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.ThugOpts = ThugOpts()
last_url = "https://www.google.com"
log.last_url = last_url
class WindowDict(dict):
def __setitem__(self, key, value):
self[key] = value
def __getitem__(self, key):
return self[key]
class TestJSInspector(object):
def test_dump_url(self):
window = WindowDict()
window.url = last_url
inspector = JSInspector(window, object(), "")
assert inspector.dump_url == last_url
| 789
|
Python
|
.py
| 22
| 31.590909
| 84
| 0.721854
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,677
|
test_SchemeHandler.py
|
buffer_thug/tests/DOM/test_SchemeHandler.py
|
import logging
import thug
from thug.DOM.SchemeHandler import SchemeHandler
from thug.Logging.ThugLogging import ThugLogging
from thug.ThugAPI.ThugOpts import ThugOpts
log = logging.getLogger("Thug")
configuration_path = thug.__configuration_path__
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.configuration_path = thug.__configuration_path__
log.ThugOpts = ThugOpts()
log.PyHooks = dict()
log.ThugLogging = ThugLogging()
class TestSchemeHandler(object):
def test_hcp(self):
handler = SchemeHandler()
handler.handle_hcp(None, "test")
handler.handle_hcp(None, "svr=foo")
handler.handle_hcp(None, "svr=foo<defer>")
handler.handle_hcp(None, "svr=foo<defer></script>")
| 762
|
Python
|
.py
| 19
| 36.315789
| 84
| 0.754768
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,678
|
test_MimeTypes.py
|
buffer_thug/tests/DOM/test_MimeTypes.py
|
import logging
import thug
from thug.ThugAPI.ThugVulnModules import ThugVulnModules
from thug.ThugAPI.ThugOpts import ThugOpts
from thug.DOM.MimeTypes import MimeTypes
log = logging.getLogger("Thug")
configuration_path = thug.__configuration_path__
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.ThugVulnModules = ThugVulnModules()
log.ThugOpts = ThugOpts()
class TestMimeTypes(object):
def test_items(self):
mimetypes = MimeTypes()
assert mimetypes[100]["description"] is None
assert mimetypes["application/x-ms-wmz"]["description"] in (
"Windows Media Player",
)
assert mimetypes.namedItem("application/x-ms-wmz")["description"] in (
"Windows Media Player",
)
| 788
|
Python
|
.py
| 20
| 34.2
| 84
| 0.730263
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,679
|
test_MimeType.py
|
buffer_thug/tests/DOM/test_MimeType.py
|
from thug.DOM.MimeType import MimeType
class TestMimeType(object):
def test_items(self):
mimetype = MimeType()
mimetype["test1"] = "value1"
assert mimetype["test1"] in ("value1",)
mimetype.test2 = "value2"
assert mimetype.test2 in ("value2",)
del mimetype["test1"]
del mimetype.test2
del mimetype["test3"]
| 380
|
Python
|
.py
| 11
| 26.818182
| 47
| 0.628099
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,680
|
test_JSEngine.py
|
buffer_thug/tests/DOM/test_JSEngine.py
|
import logging
import thug
from thug.DOM.JSEngine import JSEngine
log = logging.getLogger("Thug")
log.configuration_path = thug.__configuration_path__
class TestJSEngine(object):
def test_jsobject(self):
engine = JSEngine()
assert engine.isJSObject(None) is False
| 289
|
Python
|
.py
| 9
| 28.333333
| 52
| 0.76
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,681
|
test_Personality.py
|
buffer_thug/tests/DOM/test_Personality.py
|
import logging
import thug
from thug.DOM.Personality import Personality
from thug.ThugAPI.ThugVulnModules import ThugVulnModules
from thug.ThugAPI.ThugOpts import ThugOpts
log = logging.getLogger("Thug")
configuration_path = thug.__configuration_path__
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.ThugVulnModules = ThugVulnModules()
log.ThugOpts = ThugOpts()
log.ThugOpts.useragent = "winxpie60"
class TestPersonality(object):
def test_personality(self):
personality = Personality()
assert "Windows NT 5.1" in personality.userAgent
assert "Mozilla/4.0 (Windows XP 5.1) Java" in personality.javaUserAgent
assert "6.0" in personality.browserVersion
assert "Win32" in personality.platform
assert personality.browserMajorVersion == 6
assert "5.6" in personality.cc_on["_jscript_version"]
assert personality.isIE() is True
assert personality.isEdge() is False
assert personality.isWindows() is True
assert personality.isChrome() is False
assert personality.isSafari() is False
assert personality.ScriptEngineMajorVersion() == 5
assert personality.ScriptEngineMinorVersion() == 6
assert personality.ScriptEngineBuildVersion()
| 1,298
|
Python
|
.py
| 28
| 40.607143
| 84
| 0.750198
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,682
|
test_Location.py
|
buffer_thug/tests/DOM/test_Location.py
|
import logging
import thug
from thug.DOM.Location import Location
from thug.DOM.Navigator import Navigator
from thug.DOM.HTMLInspector import HTMLInspector
from thug.DOM.HTTPSession import HTTPSession
from thug.DOM.MIMEHandler import MIMEHandler
from thug.ThugAPI.ThugOpts import ThugOpts
from thug.ThugAPI.ThugVulnModules import ThugVulnModules
from thug.DOM.SchemeHandler import SchemeHandler
from thug.Logging.ThugLogging import ThugLogging
from thug.Magic.Magic import Magic
configuration_path = thug.__configuration_path__
log = logging.getLogger("Thug")
log.configuration_path = configuration_path
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.ThugOpts = ThugOpts()
log.HTMLInspector = HTMLInspector()
log.HTTPSession = HTTPSession()
log.MIMEHandler = MIMEHandler()
log.ThugVulnModules = ThugVulnModules()
log.SchemeHandler = SchemeHandler()
log.PyHooks = dict()
log.ThugLogging = ThugLogging()
log.Magic = Magic()
class WindowDict(dict):
def __setitem__(self, key, value):
self[key] = value
def __getitem__(self, key):
return self[key]
class TestLocation:
def check_expected(self, caplog, expected):
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def testParts(self):
log.ThugOpts.ssl_verify = True
window = WindowDict()
window.url = "https://www.google.com:1234/search?&q=test"
location = Location(window)
assert location.origin == "https://www.google.com:1234"
assert location.host == "www.google.com:1234"
assert location.hostname == "www.google.com"
assert location.pathname == "/search"
assert location.search == "&q=test"
assert location.port == 1234
assert location.hash == ""
def testPathname(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: https://www.google.com/search --> Location: https://www.google.com/test",
]
window = WindowDict()
window.url = "https://www.google.com/search"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.pathname = "/search"
location.pathname = "/test"
self.check_expected(caplog, expected)
def testProtocol(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: http://www.google.com --> Location: https://www.google.com",
]
window = WindowDict()
window.url = "http://www.google.com"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.protocol = "http:"
location.protocol = "https"
self.check_expected(caplog, expected)
def testHost(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: https://www.google.com:1234/search?&q=test --> Location: https://www.google.com/search?&q=test",
]
window = WindowDict()
window.url = "https://www.google.com:1234/search?&q=test"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.host = "www.google.com:1234"
location.host = "www.google.com"
self.check_expected(caplog, expected)
def testHostname(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: https://ww.google.com --> Location: https://www.google.com",
]
window = WindowDict()
window.url = "https://ww.google.com"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.hostname = "ww.google.com"
location.hostname = "www.google.com"
self.check_expected(caplog, expected)
def testPort(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: https://www.google.com:1234 --> Location: https://www.google.com:443",
]
window = WindowDict()
window.url = "https://www.google.com:1234"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.port = 1234
location.port = 443
self.check_expected(caplog, expected)
def testSearch(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: https://www.google.com/search?&q=test --> Location: https://www.google.com/search?&q=test2",
]
window = WindowDict()
window.url = "https://www.google.com/search?&q=test"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.search = "&q=test"
location.search = "&q=test2"
self.check_expected(caplog, expected)
def testHash(self, caplog):
log.ThugOpts.ssl_verify = True
expected = [
"[HREF Redirection (document.location)]",
"Content-Location: https://www.google.com/search#foo --> Location: https://www.google.com/search#bar",
]
window = WindowDict()
window.url = "https://www.google.com/search#foo"
window._navigator = Navigator("winxpie60")
location = Location(window)
location.hash = "foo"
location.hash = "bar"
self.check_expected(caplog, expected)
| 5,895
|
Python
|
.py
| 142
| 33.415493
| 127
| 0.644975
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,683
|
test_Views.py
|
buffer_thug/tests/DOM/test_Views.py
|
from thug.DOM.W3C.Views.AbstractView import AbstractView
class TestViews(object):
def testAbstractView(self):
view = AbstractView()
assert view.document is None
| 184
|
Python
|
.py
| 5
| 31.2
| 56
| 0.75
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,684
|
test_JSClass.py
|
buffer_thug/tests/DOM/test_JSClass.py
|
from thug.DOM.JSClass import JSClass
class JSClassTest(JSClass):
def __init__(self, value):
self.value = value
class TestJSClass(object):
def getter(self):
return "foobar"
def test_jsclass_1(self):
test1 = JSClassTest("test1")
assert test1.value == "test1"
assert str(test1.prototype) == "[object JSClassPrototype]"
assert "[native code]" in str(test1.constructor)
test1.__defineGetter__("anothervalue", self.getter)
assert test1.anothervalue == "foobar"
test2 = test1.constructor("test2")
assert test2.value == "test2"
| 620
|
Python
|
.py
| 16
| 31.5
| 66
| 0.652685
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,685
|
test_Plugins.py
|
buffer_thug/tests/DOM/test_Plugins.py
|
from thug.DOM.Plugins import Plugins
class TestPlugins(object):
def test_items(self):
plugins = Plugins()
plugins.refresh()
assert plugins["foo"] is None
assert plugins[100] is None
| 222
|
Python
|
.py
| 7
| 25
| 37
| 0.668246
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,686
|
test_DOMTokenList.py
|
buffer_thug/tests/DOM/test_DOMTokenList.py
|
from thug.DOM.W3C.DOMTokenList import DOMTokenList
class TestDOMTokenList(object):
def testDOMTokenList(self):
domtokenlist = DOMTokenList(["download", "fullscreen", "remoteplayback"])
assert domtokenlist.length == 0
assert domtokenlist.supports("download")
domtokenlist.add("foo")
assert domtokenlist.length == 0
assert domtokenlist.supports("nofullscreen")
domtokenlist.add("nofullscreen")
assert domtokenlist.length == 1
assert domtokenlist.item(0) == "nofullscreen"
assert domtokenlist.contains("nofullscreen")
domtokenlist.replace("nofullscreen", "fullscreen")
assert domtokenlist.contains("fullscreen")
domtokenlist.toggle("fullscreen")
domtokenlist.toggle("fullscreen")
assert domtokenlist.contains("fullscreen")
assert domtokenlist.value == "fullscreen"
| 903
|
Python
|
.py
| 19
| 39.105263
| 81
| 0.705143
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,687
|
test_HTTPSession.py
|
buffer_thug/tests/DOM/test_HTTPSession.py
|
import logging
import pytest
import thug
from thug.ThugAPI.ThugOpts import ThugOpts
from thug.DOM.HTTPSession import HTTPSession
configuration_path = thug.__configuration_path__
log = logging.getLogger("Thug")
log.configuration_path = configuration_path
log.personalities_path = thug.__personalities_path__ if configuration_path else None
log.ThugOpts = ThugOpts()
class WindowDict(dict):
def __setitem__(self, key, value):
self[key] = value
def __getitem__(self, key):
return self[key]
class TestHTTPSession(object):
def test_invalid_proxy_1(self):
with pytest.raises(SystemExit):
HTTPSession("invalid")
def test_invalid_proxy_2(self):
with pytest.raises(SystemExit):
HTTPSession("foo://bar")
def test_invalid_proxy_3(self):
with pytest.raises(ValueError):
HTTPSession("socks5://127.0.0.1:10000")
def test_valid_proxy(self):
HTTPSession(proxy="http://antifork.org:443")
def test_normalize_1(self):
window = WindowDict()
window.url = "about:blank"
s = HTTPSession()
url = s._normalize_protocol_relative_url(window, "//www.google.com")
assert url == "http://www.google.com"
def test_normalize_2(self):
window = WindowDict()
window.url = "www.google.com"
s = HTTPSession()
url = s._normalize_protocol_relative_url(window, "//www.google.com")
assert url == "http://www.google.com"
| 1,491
|
Python
|
.py
| 39
| 31.769231
| 84
| 0.669686
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,688
|
test_ThugPlugin.py
|
buffer_thug/tests/Plugins/test_ThugPlugin.py
|
import sys
from thug.thug import Thug
from thug.Plugins import ThugPlugins
THUG = Thug([])
ThugPlugins.PLUGINS_PATH = "thug/Plugins/plugins/"
PRE_PLUGINS = ThugPlugins.ThugPlugins("PRE", THUG)
POST_PLUGINS = ThugPlugins.ThugPlugins("POST", THUG)
sys.path.append(ThugPlugins.PLUGINS_PATH)
class TestThugPlugin:
def test_get_plugin_low_prio(self):
plugin_info = ["TestPlugin", "example"]
assert PRE_PLUGINS.get_plugin_prio(plugin_info) == 1000
def test_get_plugin_high_prio(self):
plugin_info = ["POST", "TestPlugin", "999"]
assert PRE_PLUGINS.get_plugin_prio(plugin_info) == 999
# Testing ValueError exception
plugin_info = ["POST", "999", "TestPlugin"]
assert PRE_PLUGINS.get_plugin_prio(plugin_info) == 1001
def test_get_plugin(self):
PRE_PLUGINS.get_plugins()
expected = [("PRE-TestPlugin-999", 999)]
assert PRE_PLUGINS.plugins == expected
POST_PLUGINS.get_plugins()
expected = [("POST-TestPlugin-999", 999)]
assert POST_PLUGINS.plugins == expected
def test_run(self):
self.expected = ("TestPlugin", "PRE", 999)
# Create mock object for log
class mock_log:
def __init__(self):
self.data = []
def warning(self, *args):
self.data.append(args)
def debug(self, *args):
pass
ThugPlugins.log = mock_log()
PRE_PLUGINS.run()
mock_data = ThugPlugins.log.data[0]
assert mock_data[1:4] == self.expected
POST_PLUGINS.run()
| 1,598
|
Python
|
.py
| 40
| 31.825
| 63
| 0.628164
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,689
|
test_shockwave.py
|
buffer_thug/tests/functional/test_shockwave.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestShockwave(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
misc_path = os.path.join(cwd_path, os.pardir, "samples/misc")
def do_perform_test(self, caplog, sample, shockwave, expected):
thug = ThugAPI()
thug.set_useragent("win7ie90")
thug.set_events("click,storage")
thug.disable_cert_logging()
thug.set_features_logging()
if shockwave in ("disable",):
thug.disable_shockwave_flash()
else:
thug.set_shockwave_flash(shockwave)
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_shockwave1(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = ["AdobeReader version: 9.1.0.0", "Flash version: 9.0.64.0"]
self.do_perform_test(caplog, sample, "9.0.64.0", expected)
def test_shockwave2(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"]
self.do_perform_test(caplog, sample, "10.0.64.0", expected)
def test_shockwave3(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = ["AdobeReader version: 9.1.0.0", "Flash version: 11.0.64.0"]
self.do_perform_test(caplog, sample, "11.0.64.0", expected)
def test_shockwave4(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = ["AdobeReader version: 9.1.0.0", "Flash version: 12.0.64.0"]
self.do_perform_test(caplog, sample, "12.0.64.0", expected)
def test_shockwave5(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = [
"AdobeReader version: 9.1.0.0",
]
self.do_perform_test(caplog, sample, "disable", expected)
| 2,255
|
Python
|
.py
| 48
| 38.270833
| 79
| 0.629291
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,690
|
test_events.py
|
buffer_thug/tests/functional/test_events.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestEvents(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
event_path = os.path.join(cwd_path, os.pardir, "samples/Events")
def do_perform_test(
self, caplog, sample, expected, events="", useragent="win7ie90"
):
thug = ThugAPI()
thug.set_useragent(useragent)
thug.set_events(events)
thug.disable_cert_logging()
thug.set_features_logging()
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_testDocumentEvent(self, caplog):
sample = os.path.join(self.event_path, "testDocumentEvent.html")
expected = [
"[object HTMLEvent]",
"[object MouseEvent]",
"[object MutationEvent]",
"[object StorageEvent]",
"[object UIEvent]",
]
self.do_perform_test(caplog, sample, expected)
def test_testMouseEvent_IE60(self, caplog):
sample = os.path.join(self.event_path, "testMouseEvent.html")
expected = [
"[object MouseEvent]",
"type: click",
"target: null",
"bubbles: false",
"cancelable: false",
"screenX: 0",
"screenY: 0",
"clientX: 0",
"clientY: 0",
"ctlrKey: false",
"altKey: false",
"shiftKey: false",
"metaKey: false",
"button: 0",
"relatedTarget: null",
"detail: 0",
"view: [object Window]",
"defaultPrevented: undefined",
]
self.do_perform_test(caplog, sample, expected, useragent="winxpie60")
def test_testMouseEvent_IE90(self, caplog):
sample = os.path.join(self.event_path, "testMouseEvent.html")
expected = [
"[object MouseEvent]",
"type: click",
"target: null",
"bubbles: false",
"cancelable: false",
"screenX: 0",
"screenY: 0",
"clientX: 0",
"clientY: 0",
"ctlrKey: false",
"altKey: false",
"shiftKey: false",
"metaKey: false",
"button: 0",
"relatedTarget: null",
"detail: 0",
"view: [object Window]",
"defaultPrevented: false",
]
self.do_perform_test(caplog, sample, expected, useragent="win7ie90")
def test_testMouseEvent_Chrome(self, caplog):
sample = os.path.join(self.event_path, "testMouseEvent.html")
expected = [
"[object MouseEvent]",
"type: click",
"target: null",
"bubbles: false",
"cancelable: false",
"screenX: 0",
"screenY: 0",
"clientX: 0",
"clientY: 0",
"ctlrKey: false",
"altKey: false",
"shiftKey: false",
"metaKey: false",
"button: 0",
"relatedTarget: null",
"detail: 0",
"view: [object Window]",
"defaultPrevented: false",
]
self.do_perform_test(caplog, sample, expected, useragent="win7chrome49")
def test_testMouseEvent_Safari(self, caplog):
sample = os.path.join(self.event_path, "testMouseEvent.html")
expected = [
"[object MouseEvent]",
"type: click",
"target: null",
"bubbles: false",
"cancelable: false",
"screenX: 0",
"screenY: 0",
"clientX: 0",
"clientY: 0",
"ctlrKey: false",
"altKey: false",
"shiftKey: false",
"metaKey: false",
"button: 0",
"relatedTarget: null",
"detail: 0",
"view: [object Window]",
"defaultPrevented: false",
]
self.do_perform_test(caplog, sample, expected, useragent="win7safari5")
def test_testMouseEvent_Firefox(self, caplog):
sample = os.path.join(self.event_path, "testMouseEvent.html")
expected = [
"[object MouseEvent]",
"type: click",
"target: null",
"bubbles: false",
"cancelable: false",
"screenX: 0",
"screenY: 0",
"clientX: 0",
"clientY: 0",
"ctlrKey: false",
"altKey: false",
"shiftKey: false",
"metaKey: false",
"button: 0",
"relatedTarget: null",
"detail: 0",
"view: [object Window]",
"defaultPrevented: false",
]
self.do_perform_test(caplog, sample, expected, useragent="linuxfirefox40")
def test_testStorageEvent(self, caplog):
sample = os.path.join(self.event_path, "testStorageEvent.html")
expected = [
"[object StorageEvent]",
"type: storage",
"target: null",
"bubbles: false",
"cancelable: false",
"key: key",
"oldValue: oldValue",
"newValue: newValue",
"url: http://www.example.com",
"storageArea: [object SessionStorage]",
]
self.do_perform_test(caplog, sample, expected)
def test_testMutationEvent(self, caplog):
sample = os.path.join(self.event_path, "testMutationEvent.html")
expected = [
"[object MutationEvent]",
"type: DOMAttrModified",
"target: null",
"bubbles: true",
"cancelable: true",
"relatedNode: [object Attr]",
"prevValue: null",
"newValue: foobar",
"attrName: value",
"attrChange: 1",
]
self.do_perform_test(caplog, sample, expected)
def test_testMessageEvent(self, caplog):
sample = os.path.join(self.event_path, "testMessageEvent.html")
expected = ["[object MessageEvent]", "msg.data: hello", "msg.source: null"]
self.do_perform_test(caplog, sample, expected, useragent="osx10chrome97")
def test_testEventException(self, caplog):
sample = os.path.join(self.event_path, "testEventException.html")
expected = [
"Error",
]
self.do_perform_test(caplog, sample, expected)
def test_testEvent1(self, caplog):
sample = os.path.join(self.event_path, "testEvent1.html")
expected = ["add", "[object HTMLParagraphElement]"]
self.do_perform_test(caplog, sample, expected)
def test_testEvent2(self, caplog):
sample = os.path.join(self.event_path, "testEvent2.html")
expected = [
"1. Div capture ran",
"Link capture ran - browser does not follow the specification",
"2. Link bubble ran (first listener)",
"2. Link bubble ran (second listener)",
"3. Div bubble ran",
]
self.do_perform_test(caplog, sample, expected)
def test_testEvent3(self, caplog):
sample = os.path.join(self.event_path, "testEvent3.html")
expected = ["onmousemove detected", "onclick detected"]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent4(self, caplog):
sample = os.path.join(self.event_path, "testEvent4.html")
expected = ["add", "[object HTMLParagraphElement]"]
self.do_perform_test(caplog, sample, expected, useragent="winxpie60")
def test_testEvent6(self, caplog):
sample = os.path.join(self.event_path, "testEvent6.html")
expected = [
"Clicked",
]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent7(self, caplog):
sample = os.path.join(self.event_path, "testEvent7.html")
expected = [
"foobar",
]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent8(self, caplog):
sample = os.path.join(self.event_path, "testEvent8.html")
expected = [
"Clicked",
"foobar",
]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent9(self, caplog):
sample = os.path.join(self.event_path, "testEvent9.html")
expected = [
"[object Event]",
"[object HTMLParagraphElement]",
]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent11(self, caplog):
sample = os.path.join(self.event_path, "testEvent11.html")
expected = [
"[object Event]",
"[object HTMLParagraphElement]",
"clicked",
"clicked 2",
]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent12(self, caplog):
sample = os.path.join(self.event_path, "testEvent12.html")
expected = ["You should see me two times", "First click"]
self.do_perform_test(
caplog, sample, expected, events="click", useragent="winxpie60"
)
def test_testEvent13(self, caplog):
sample = os.path.join(self.event_path, "testEvent13.html")
expected = ["You should not see me again", "First click"]
self.do_perform_test(
caplog, sample, expected, events="click", useragent="winxpie60"
)
def test_testEvent14(self, caplog):
sample = os.path.join(self.event_path, "testEvent14.html")
expected = [
"Done!",
]
self.do_perform_test(caplog, sample, expected, events="click")
def test_testEvent15(self, caplog):
sample = os.path.join(self.event_path, "testEvent15.html")
expected = [
"clicked",
]
self.do_perform_test(
caplog, sample, expected, events="click", useragent="winxpie60"
)
def test_testEvent16(self, caplog):
sample = os.path.join(self.event_path, "testEvent16.html")
expected = [
"loaded",
]
self.do_perform_test(caplog, sample, expected, useragent="winxpie60")
| 10,489
|
Python
|
.py
| 278
| 27.010791
| 83
| 0.554516
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,691
|
test_exploits.py
|
buffer_thug/tests/functional/test_exploits.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestExploitSamples(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
exploits_path = os.path.join(cwd_path, os.pardir, "samples/exploits")
def do_perform_test(self, caplog, sample, expected, useragent="win7ie90"):
thug = ThugAPI()
thug.set_useragent(useragent)
thug.set_events("click,storage")
thug.set_json_logging()
thug.set_features_logging()
thug.set_ssl_verify()
thug.set_connect_timeout(2)
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_22196(self, caplog):
sample = os.path.join(self.exploits_path, "22196.html")
expected = [
"[NCTAudioFile2 ActiveX] Overflow in SetFormatLikeSample",
"WinExec",
"ExitThread",
"calc.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_22811_Elazar(self, caplog):
sample = os.path.join(self.exploits_path, "22811_Elazar.html")
expected = [
"RealMedia RealPlayer Ierpplug.DLL ActiveX",
"Overflow in Import",
"Overflow in PlayerProperty",
]
self.do_perform_test(caplog, sample, expected)
def test_2448(self, caplog):
sample = os.path.join(self.exploits_path, "2448.html")
expected = [
"[WebViewFolderIcon ActiveX] setSlice attack",
"webviewfoldericon.webviewfoldericon.1",
]
self.do_perform_test(caplog, sample, expected)
def test_2mix(self, caplog):
sample = os.path.join(self.exploits_path, "2mix.html")
expected = [
"[Microsoft Access Snapshot Viewer ActiveX] SnapshotPath : http://paksusic.cn/nuc/exe.php",
"CompressedPath: C:/Program Files/Outlook Express/wab.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_33243_excel(self, caplog):
sample = os.path.join(self.exploits_path, "33243-excel.html")
expected = [
"[Office OCX Exploit redirection] about:blank -> http://192.168.1.100/putty.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_33243_office(self, caplog):
sample = os.path.join(self.exploits_path, "33243-office.html")
expected = [
"[Office OCX Exploit redirection] about:blank -> http://www.example.com/file.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_33243_powerpoint(self, caplog):
sample = os.path.join(self.exploits_path, "33243-powerpoint.html")
expected = [
"[Office OCX Exploit redirection] about:blank -> http://www.example.com/file.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_33243_word(self, caplog):
sample = os.path.join(self.exploits_path, "33243-word.html")
expected = [
"[Office OCX Exploit redirection] about:blank -> http://www.example.com/calc.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_4042(self, caplog):
sample = os.path.join(self.exploits_path, "4042.html")
expected = ["[Yahoo! Messenger 8.x Ywcvwr ActiveX] Server Console Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_4043(self, caplog):
sample = os.path.join(self.exploits_path, "4043.html")
expected = ["[Yahoo! Messenger 8.x Ywcvwr ActiveX] Server Console Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_4148(self, caplog):
sample = os.path.join(self.exploits_path, "4148.html")
expected = ["[EnjoySAP ActiveX] PrepareToPostHTML overflow in arg"]
self.do_perform_test(caplog, sample, expected)
def test_4149(self, caplog):
sample = os.path.join(self.exploits_path, "4149.html")
expected = ["[EnjoySAP ActiveX] LaunchGUI overflow in arg0"]
self.do_perform_test(caplog, sample, expected)
def test_4150(self, caplog):
sample = os.path.join(self.exploits_path, "4150.html")
expected = [
"[EnjoySAP ActiveX] Fetching from URL http://192.168.1.100/putty.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_4158(self, caplog):
sample = os.path.join(self.exploits_path, "4158.html")
expected = ["[NeoTraceExplorer.NeoTraceLoader ActiveX] Overflow in arg0"]
self.do_perform_test(caplog, sample, expected)
def test_4230(self, caplog):
sample = os.path.join(self.exploits_path, "4230.html")
expected = [
"[Nessus Vunlnerability Scanner ScanCtrl ActiveX] deleteReport(../../../../../../../test.txt)"
]
self.do_perform_test(caplog, sample, expected)
def test_4237(self, caplog):
sample = os.path.join(self.exploits_path, "4237.html")
expected = [
"[Nessus Vunlnerability Scanner ScanCtrl ActiveX] saveNessusRC(../../../../../../Documents and Settings/All Users/Menu Start/Programy/Autostart/exec.bat)"
]
self.do_perform_test(caplog, sample, expected)
def test_4250(self, caplog):
sample = os.path.join(self.exploits_path, "4250.html")
expected = [
"[Yahoo! Messenger 8.x Ywcvwr ActiveX] GetComponentVersion Overflow",
"LoadLibraryA",
"port = 4444",
"CreateProcess",
"cmd",
]
self.do_perform_test(caplog, sample, expected)
def test_4351(self, caplog):
sample = os.path.join(self.exploits_path, "4351.html")
expected = [
"[Yahoo! Messenger 8.x YVerInfo.dll ActiveX Control] Overflow in fvCom arg0",
"WinExec",
"calc",
]
self.do_perform_test(caplog, sample, expected)
def test_4427(self, caplog):
sample = os.path.join(self.exploits_path, "4427.html")
expected = [
r"[JetAudio ActiveX] Downloading from URL http://192.168.0.1/evil.mp3 (saving locally as ..\..\..\..\..\..\..\..\Program Files\JetAudio\JetAudio.exe)"
]
self.do_perform_test(caplog, sample, expected)
def test_4594(self, caplog):
sample = os.path.join(self.exploits_path, "4594.html")
expected = [
"[SonicWall SSL-VPN NetExtender NELaunchCtrl ActiveX] Overflow in AddRouteEntry",
"WinExec",
"calc.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_4613(self, caplog):
sample = os.path.join(self.exploits_path, "4613.html")
expected = ["[Shockwave] ShockwaveVersion Stack Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_4663(self, caplog):
sample = os.path.join(self.exploits_path, "4663.html")
expected = ["[BitDefender Online Scanner ActiveX] InitX overflow"]
self.do_perform_test(caplog, sample, expected)
def test_4829(self, caplog):
sample = os.path.join(self.exploits_path, "4829.html")
expected = ["[DivX Player ActiveX] Overflow in SetPassword"]
self.do_perform_test(caplog, sample, expected)
def test_4869(self, caplog):
sample = os.path.join(self.exploits_path, "4869.html")
expected = [
r"[Gateway Weblaunch ActiveX] Trying to execute ..\..\..\..\windows\system32\calc.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_4894(self, caplog):
sample = os.path.join(self.exploits_path, "4894.html")
expected = [
"[StreamAudio ChainCast VMR Client Proxy ActiveX] Buffer overflow in arg0"
]
self.do_perform_test(caplog, sample, expected)
def test_4903(self, caplog):
sample = os.path.join(self.exploits_path, "4903.html")
expected = [
"[DVRHOST Web CMS OCX ActiveX] Overflow in TimeSpanFormat",
"WinExec",
"cmd.exe /c net user sun tzu /ADD && net localgroup Administrators sun /ADD",
]
self.do_perform_test(caplog, sample, expected)
def test_4909(self, caplog):
sample = os.path.join(self.exploits_path, "4909.html")
expected = [
"[Macrovision Exploit 2 redirection] about:blank -> http://www.evilsite/evil.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_4918(self, caplog):
sample = os.path.join(self.exploits_path, "4918.html")
expected = ["[PTZCamPanel ActiveX] Overflow in ConnectServer user arg"]
self.do_perform_test(caplog, sample, expected)
def test_4932(self, caplog):
sample = os.path.join(self.exploits_path, "4932.html")
expected = ["[RTSP MPEG4 SP Control ActiveX] Overflow in MP4Prefix property"]
self.do_perform_test(caplog, sample, expected)
def test_4967(self, caplog):
sample = os.path.join(self.exploits_path, "4967.html")
expected = [
"[Lycos FileUploader ActiveX] Overflow in HandwriterFilename property"
]
self.do_perform_test(caplog, sample, expected)
def test_4974(self, caplog):
sample = os.path.join(self.exploits_path, "4974.html")
expected = [
'[Comodo AntiVirus ActiveX] Trying to execute: cmd.exe /C echo "hello world" && pause'
]
self.do_perform_test(caplog, sample, expected)
def test_4979(self, caplog):
sample = os.path.join(self.exploits_path, "4979.html")
expected = ["[Move Networks Upgrade Manager ActiveX] Overflow in Upgrade"]
self.do_perform_test(caplog, sample, expected)
def test_4982(self, caplog):
sample = os.path.join(self.exploits_path, "4982.html")
expected = ["[Gateway Weblaunch ActiveX] Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_4986(self, caplog):
sample = os.path.join(self.exploits_path, "4986.html")
expected = [
"[NamoInstaller ActiveX] Insecure download from URL http://ATTACKER.COM/HACK.EXE"
]
self.do_perform_test(caplog, sample, expected)
def test_4987(self, caplog):
sample = os.path.join(self.exploits_path, "4987.html")
expected = ["[XUpload ActiveX] Overflow in AddFile method"]
self.do_perform_test(caplog, sample, expected)
def test_5025(self, caplog):
sample = os.path.join(self.exploits_path, "5025.html")
expected = ["[Myspace UPloader ActiveX] Overflow in Action property"]
self.do_perform_test(caplog, sample, expected)
def test_5043(self, caplog):
sample = os.path.join(self.exploits_path, "5043.html")
expected = ["[Yahoo! Music Jukebox ActiveX] Overflow in AddImage"]
self.do_perform_test(caplog, sample, expected)
def test_5045(self, caplog):
sample = os.path.join(self.exploits_path, "5045.html")
expected = [
"[NamoInstaller ActiveX] Overflow in Install method",
"WinExec",
"calc",
]
self.do_perform_test(caplog, sample, expected)
def test_5049(self, caplog):
sample = os.path.join(self.exploits_path, "5049.html")
expected = [
"[FaceBook Photo Uploader ActiveX] Overflow in ExtractIptc property"
]
self.do_perform_test(caplog, sample, expected)
def test_5051(self, caplog):
sample = os.path.join(self.exploits_path, "5051.html")
expected = ["[Yahoo! Music Jukebox ActiveX] Overflow in AddButton"]
self.do_perform_test(caplog, sample, expected)
def test_5052(self, caplog):
sample = os.path.join(self.exploits_path, "5052.html")
expected = ["[Yahoo! Music Jukebox ActiveX] Overflow in AddBitmap"]
self.do_perform_test(caplog, sample, expected)
def test_5153(self, caplog):
sample = os.path.join(self.exploits_path, "5153.html")
expected = [
"[Ourgame GLWorld ActiveX] Overflow in hgs_startNotify",
"WinExec",
"calc",
]
self.do_perform_test(caplog, sample, expected)
def test_5188(self, caplog):
sample = os.path.join(self.exploits_path, "5188.html")
expected = [
"[Rising Online Virus Scanner Web Scan ActiveX] UpdateEngine Method vulnerability"
]
self.do_perform_test(caplog, sample, expected)
def test_5190(self, caplog):
sample = os.path.join(self.exploits_path, "5190.html")
expected = [
"[Move Networks Quantum Streaming Player Control ActiveX] Overflow in UploadLogs method"
]
self.do_perform_test(caplog, sample, expected)
def test_5193(self, caplog):
sample = os.path.join(self.exploits_path, "5193.html")
expected = ["[D-Link MPEG4 SHM Audio Control ActiveX] Overflow in Url property"]
self.do_perform_test(caplog, sample, expected)
def test_5205(self, caplog):
sample = os.path.join(self.exploits_path, "5205.html")
expected = ["[Symantec BackupExec ActiveX] Overflow in property _DOWText0"]
self.do_perform_test(caplog, sample, expected)
def test_5217(self, caplog):
sample = os.path.join(self.exploits_path, "5217.html")
expected = ["[ICQ Toolbar ActiveX] Buffer overflow in GetPropertyById"]
self.do_perform_test(caplog, sample, expected)
def test_5225(self, caplog):
sample = os.path.join(self.exploits_path, "5225.html")
expected = ["[Kingsoft AntiVirus ActiveX] SetUninstallName Heap Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_5264(self, caplog):
sample = os.path.join(self.exploits_path, "5264.html")
expected = ["[CA BrightStor ActiveX] Overflow in AddColumn"]
self.do_perform_test(caplog, sample, expected)
def test_5271(self, caplog):
sample = os.path.join(self.exploits_path, "5271.html")
expected = [
"[RegistryPro ActiveX] About called",
"[RegistryPro ActiveX] Deleting [HKEY_LOCAL_MACHINE/Software/key]",
]
self.do_perform_test(caplog, sample, expected)
def test_5272(self, caplog):
sample = os.path.join(self.exploits_path, "5272.html")
expected = ["[Universal HTTP File Upload ActiveX] Deleting C:/tmp.txt"]
self.do_perform_test(caplog, sample, expected)
def test_55875(self, caplog):
sample = os.path.join(self.exploits_path, "55875.html")
expected = [
"[iframe redirection] about:blank -> http://81.95.149.27/go.php?sid=1"
]
self.do_perform_test(caplog, sample, expected)
def test_ARCserve_AddColumn_BoF(self, caplog):
sample = os.path.join(self.exploits_path, "ARCserve_AddColumn_BoF.html")
expected = ["[CA BrightStor ActiveX] Overflow in AddColumn"]
self.do_perform_test(caplog, sample, expected)
def test_AnswerWorks(self, caplog):
sample = os.path.join(self.exploits_path, "AnswerWorks.htm")
expected = [
"[AnswerWorks ActiveX] Overflow in GetHistory",
]
self.do_perform_test(caplog, sample, expected)
def test_AnswerWorks2(self, caplog):
sample = os.path.join(self.exploits_path, "AnswerWorks2.htm")
expected = [
"[AnswerWorks ActiveX] Overflow in GetSeedQuery",
]
self.do_perform_test(caplog, sample, expected)
def test_AnswerWorks3(self, caplog):
sample = os.path.join(self.exploits_path, "AnswerWorks3.htm")
expected = [
"[AnswerWorks ActiveX] Overflow in SetSeedQuery",
]
self.do_perform_test(caplog, sample, expected)
def test_AolICQ(self, caplog):
sample = os.path.join(self.exploits_path, "AolICQ.htm")
expected = [
"[AOL ICQ ActiveX] Arbitrary File Download and Execute",
]
self.do_perform_test(caplog, sample, expected)
def test_BaiduBar(self, caplog):
sample = os.path.join(self.exploits_path, "BaiduBar.htm")
expected = [
"[BaiduBar.dll ActiveX] DloadDS function trying to download http://ruder.cdut.net/attach/calc.cab"
]
self.do_perform_test(caplog, sample, expected)
def test_BitDefender(self, caplog):
sample = os.path.join(self.exploits_path, "BitDefender.htm")
expected = ["[BitDefender Online Scanner ActiveX] InitX overflow"]
self.do_perform_test(caplog, sample, expected)
def test_CABrightStor(self, caplog):
sample = os.path.join(self.exploits_path, "CABrightStor.htm")
expected = ["[CA BrightStor ActiveX] Overflow in AddColumn"]
self.do_perform_test(caplog, sample, expected)
def test_Comodo(self, caplog):
sample = os.path.join(self.exploits_path, "Comodo.htm")
expected = [
'[Comodo AntiVirus ActiveX] Trying to execute: cmd.exe /C echo "hello world" && pause'
]
self.do_perform_test(caplog, sample, expected)
def test_ConnectAndEnterRoom(self, caplog):
sample = os.path.join(self.exploits_path, "ConnectAndEnterRoom.htm")
expected = [
"[GlobalLink ConnectAndEnterRoom ActiveX] ConnectAndEnterRoom Overflow"
]
self.do_perform_test(caplog, sample, expected)
def test_CreativeSoftAttack(self, caplog):
sample = os.path.join(self.exploits_path, "CreativeSoftAttack.htm")
expected = ["[CreativeSoft ActiveX] Overflow in cachefolder property"]
self.do_perform_test(caplog, sample, expected)
def test_DLinkMPEG(self, caplog):
sample = os.path.join(self.exploits_path, "DLinkMPEG.htm")
expected = ["[D-Link MPEG4 SHM Audio Control ActiveX] Overflow in Url property"]
self.do_perform_test(caplog, sample, expected)
def test_DPClient(self, caplog):
sample = os.path.join(self.exploits_path, "DPClient.htm")
expected = ["[Xunlei DPClient.Vod.1 ActiveX] DownURL2 Method Buffer Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_DVRHOSTWeb(self, caplog):
sample = os.path.join(self.exploits_path, "DVRHOSTWeb.htm")
expected = [
"[DVRHOST Web CMS OCX ActiveX] Overflow in TimeSpanFormat",
"WinExec",
"cmd.exe /c net user sun tzu /ADD && net localgroup Administrators sun /ADD",
]
self.do_perform_test(caplog, sample, expected)
def test_DirectShow(self, caplog):
sample = os.path.join(self.exploits_path, "DirectShow.htm")
expected = [
"[Microsoft DirectShow MPEG2TuneRequest ActiveX] Stack Overflow in data property"
]
self.do_perform_test(caplog, sample, expected)
def test_DivX(self, caplog):
sample = os.path.join(self.exploits_path, "DivX.htm")
expected = ["[DivX Player ActiveX] Overflow in SetPassword"]
self.do_perform_test(caplog, sample, expected)
def test_Domino(self, caplog):
sample = os.path.join(self.exploits_path, "Domino.htm")
expected = [
"[IBM Lotus Domino Web Access Control ActiveX] Overflow in General_ServerName property"
]
self.do_perform_test(caplog, sample, expected)
def test_Domino2(self, caplog):
sample = os.path.join(self.exploits_path, "Domino2.htm")
expected = [
"[IBM Lotus Domino Web Access Control ActiveX] Overflow in General_JunctionName property"
]
self.do_perform_test(caplog, sample, expected)
def test_Domino3(self, caplog):
sample = os.path.join(self.exploits_path, "Domino3.htm")
expected = [
"[IBM Lotus Domino Web Access Control ActiveX] Overflow in Mail_MailDbPath property"
]
self.do_perform_test(caplog, sample, expected)
def test_FileUploader(self, caplog):
sample = os.path.join(self.exploits_path, "FileUploader.htm")
expected = [
"[Lycos FileUploader ActiveX] Overflow in HandwriterFilename property"
]
self.do_perform_test(caplog, sample, expected)
def test_GatewayWeblaunch(self, caplog):
sample = os.path.join(self.exploits_path, "GatewayWeblaunch.htm")
expected = [
r"[Gateway Weblaunch ActiveX] Trying to execute ..\..\..\..\windows\system32\calc.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_GLIEDown2(self, caplog):
sample = os.path.join(self.exploits_path, "GLIEDown2.htm")
expected = [
"LoadLibraryA",
"URLDownloadToFile",
"http://www.baiduuo.cn/123/ok.exe",
"WinExec",
]
self.do_perform_test(caplog, sample, expected)
def test_Gogago(self, caplog):
sample = os.path.join(self.exploits_path, "Gogago.html")
expected = ["[Gogago YouTube Video Converter ActiveX] Buffer Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_Gogago2(self, caplog):
sample = os.path.join(self.exploits_path, "Gogago2.html")
expected = ["WinExec", "192.168.0.1", "GetVersion", "ExitProcess"]
self.do_perform_test(caplog, sample, expected)
def test_GomWeb(self, caplog):
sample = os.path.join(self.exploits_path, "GomWeb.htm")
expected = ["[GOM Player Manager ActiveX] Overflow in OpenURL"]
self.do_perform_test(caplog, sample, expected)
def test_HPInfo_GetRegValue(self, caplog):
sample = os.path.join(self.exploits_path, "HPInfo_GetRegValue.htm")
expected = ["[HP Info Center ActiveX] GetRegValue, reading: //"]
self.do_perform_test(caplog, sample, expected)
def test_HPInfo_LaunchApp(self, caplog):
sample = os.path.join(self.exploits_path, "HPInfo_LaunchApp.htm")
expected = [
"[HP Info Center ActiveX] LaunchApp called to run: c:\\windows\\system32\\cmd.exe /C c:\\ftpd.bat&del c:\\ftpd.bat&del c:\\ftpd&del c:\\malware.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_HPInfo_SetRegValue(self, caplog):
sample = os.path.join(self.exploits_path, "HPInfo_SetRegValue.htm")
expected = ["[HP Info Center ActiveX] SetRegValue: None/None/None set to None"]
self.do_perform_test(caplog, sample, expected)
def test_IMWebControl(self, caplog):
sample = os.path.join(self.exploits_path, "IMWebControl.htm")
expected = [
"[iMesh IMWebControl ActiveX] NULL value in ProcessRequestEx",
"cmd.exe /c net user sun tzu /ADD && net localgroup Administrators sun /ADD",
]
self.do_perform_test(caplog, sample, expected)
def test_InternetCleverSuite(self, caplog):
sample = os.path.join(self.exploits_path, "InternetCleverSuite.html")
expected = [
"[Clever Internet ActiveX Suite 6.2 (CLINETSUITEX6.OCX)] Arbitrary File Download/Overwrite Exploit",
]
self.do_perform_test(caplog, sample, expected)
def test_JavaActiveXMemoryCorruption(self, caplog):
sample = os.path.join(self.exploits_path, "JavaActiveXMemoryCorruption.html")
expected = [
"[Java Deployment Toolkit ActiveX] Java ActiveX component memory corruption (CVE-2013-2416)"
]
self.do_perform_test(caplog, sample, expected)
def test_JetAudioDownloadFromMusicStore(self, caplog):
sample = os.path.join(self.exploits_path, "JetAudioDownloadFromMusicStore.htm")
expected = [
r"[JetAudio ActiveX] Downloading from URL http://192.168.0.1/evil.mp3 (saving locally as ..\..\..\..\..\..\..\..\Program Files\JetAudio\JetAudio.exe)"
]
self.do_perform_test(caplog, sample, expected)
def test_Kingsoft(self, caplog):
sample = os.path.join(self.exploits_path, "Kingsoft.htm")
expected = ["[Kingsoft AntiVirus ActiveX] SetUninstallName Heap Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_MacrovisionFlexNet(self, caplog):
sample = os.path.join(self.exploits_path, "MacrovisionFlexNet.htm")
expected = [
'[Macrovision ActiveX] AddFile("http://www.evilsite/evil.exe"',
r'"C:\Documents and Settings\All Users\Start Menu\Programs\Startup\harmless.exe")',
]
self.do_perform_test(caplog, sample, expected)
def test_MicrosoftWorks7Attack(self, caplog):
sample = os.path.join(self.exploits_path, "MicrosoftWorks7Attack.htm")
expected = [
"[MicrosoftWorks7 ActiveX] Overflow in WksPictureInterface property",
"WinExec",
"calc",
]
self.do_perform_test(caplog, sample, expected)
def test_Move(self, caplog):
sample = os.path.join(self.exploits_path, "Move.htm")
expected = ["[Move Networks Upgrade Manager ActiveX] Overflow in Upgrade"]
self.do_perform_test(caplog, sample, expected)
def test_MSVFP(self, caplog):
sample = os.path.join(self.exploits_path, "MSVFP.html")
expected = ["[Microsoft VFP_OLE_Server ActiveX] Trying to run: calc.exe"]
self.do_perform_test(caplog, sample, expected)
def test_MyspaceUploader(self, caplog):
sample = os.path.join(self.exploits_path, "MyspaceUploader.htm")
expected = ["[Myspace UPloader ActiveX] Overflow in Action property"]
self.do_perform_test(caplog, sample, expected)
def test_msrichtxt(self, caplog):
sample = os.path.join(self.exploits_path, "msrichtxt.html")
expected = [
r"[Microsoft Rich Textbox Control ActiveX] Writing to file C:\shinnai.bat",
"cmd.exe /c notepad.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_NCTAudioFile2(self, caplog):
sample = os.path.join(self.exploits_path, "NCTAudioFile2.htm")
expected = ["[NCTAudioFile2 ActiveX] Overflow in SetFormatLikeSample"]
self.do_perform_test(caplog, sample, expected)
def test_NamoInstaller(self, caplog):
sample = os.path.join(self.exploits_path, "NamoInstaller.htm")
expected = [
"[NamoInstaller ActiveX] Insecure download from URL http://192.168.1.100/putty.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_NessusScanCtrl(self, caplog):
sample = os.path.join(self.exploits_path, "NessusScanCtrl.htm")
expected = [
"[Nessus Vunlnerability Scanner ScanCtrl ActiveX] saveNessusRC(../../../../../../Documents and Settings/All Users/Menu Start/Programy/Autostart/exec.bat)"
]
self.do_perform_test(caplog, sample, expected)
def test_OurgameGLWorld(self, caplog):
sample = os.path.join(self.exploits_path, "OurgameGLWorld.html")
expected = ["[Ourgame GLWorld ActiveX] Overflow in hgs_startNotify"]
self.do_perform_test(caplog, sample, expected)
def test_OurgameGLWorld2(self, caplog):
sample = os.path.join(self.exploits_path, "OurgameGLWorld2.htm")
expected = ["[Ourgame GLWorld ActiveX] Overflow in hgs_startGame"]
self.do_perform_test(caplog, sample, expected)
def test_PPlayer(self, caplog):
sample = os.path.join(self.exploits_path, "PPlayer.htm")
expected = [
"[Xunlei Thunder PPlayer ActiveX] FlvPlayerUrl Property Handling Buffer Overflow"
]
self.do_perform_test(caplog, sample, expected)
def test_Pps2(self, caplog):
sample = os.path.join(self.exploits_path, "Pps2.html")
expected = [
"[Xunlei Thunder PPlayer ActiveX] Remote Overflow Exploit in Logo property"
]
self.do_perform_test(caplog, sample, expected)
def test_Pps3(self, caplog):
sample = os.path.join(self.exploits_path, "Pps3.html")
expected = ["[Xunlei Thunder PPlayer ActiveX] DownURL2 Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_PTZCamPanel(self, caplog):
sample = os.path.join(self.exploits_path, "PTZCamPanel.htm")
expected = ["[PTZCamPanel ActiveX] Overflow in ConnectServer user arg"]
self.do_perform_test(caplog, sample, expected)
def test_QuantumStreaming(self, caplog):
sample = os.path.join(self.exploits_path, "QuantumStreaming.htm")
expected = [
"[Move Networks Quantum Streaming Player Control ActiveX] Overflow in UploadLogs method"
]
self.do_perform_test(caplog, sample, expected)
def test_RediffBolDownloaderAttack(self, caplog):
sample = os.path.join(self.exploits_path, "RediffBolDownloaderAttack.htm")
expected = ["[RediffBolDownloader ActiveX] Overflow in url property"]
self.do_perform_test(caplog, sample, expected)
def test_RegistryPro(self, caplog):
sample = os.path.join(self.exploits_path, "RegistryPro.htm")
expected = ["[RegistryPro ActiveX] Deleting [HKEY_LOCAL_MACHINE/Software/key]"]
self.do_perform_test(caplog, sample, expected)
def test_RtspVaPgCtrl(self, caplog):
sample = os.path.join(self.exploits_path, "RtspVaPgCtrl.htm")
expected = ["[RTSP MPEG4 SP Control ActiveX] Overflow in MP4Prefix property"]
self.do_perform_test(caplog, sample, expected)
def test_SSReaderPdg2_LoadPage(self, caplog):
sample = os.path.join(self.exploits_path, "SSReaderPdg2_LoadPage.htm")
expected = [
"LoadLibraryA",
"system32",
"URLDownloadToFile",
"WinExec",
"ExitThread",
]
self.do_perform_test(caplog, sample, expected)
def test_SSReaderPdg2_Register(self, caplog):
sample = os.path.join(self.exploits_path, "SSReaderPdg2_Register.htm")
expected = ["[SSReader Pdg2 ActiveX] Register Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_SinaDLoader(self, caplog):
sample = os.path.join(self.exploits_path, "SinaDLoader.htm")
expected = [
"[SinaDLoader Downloader ActiveX] Fetching from URL hxxp://dddd.nihao69.cn/down/ko.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_SonicWallNetExtenderAddRouteEntry(self, caplog):
sample = os.path.join(
self.exploits_path, "SonicWallNetExtenderAddRouteEntry.htm"
)
expected = [
"[SonicWall SSL-VPN NetExtender NELaunchCtrl ActiveX] Overflow in AddRouteEntry",
"WinExec",
"calc.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_StormConfig(self, caplog):
sample = os.path.join(self.exploits_path, "StormConfig.htm")
expected = ["[BaoFeng Storm ActiveX Control] SetAttributeValue Buffer Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_StreamAudioChainCast(self, caplog):
sample = os.path.join(self.exploits_path, "StreamAudioChainCast.htm")
expected = [
"[StreamAudio ChainCast VMR Client Proxy ActiveX] Buffer overflow in arg0"
]
self.do_perform_test(caplog, sample, expected)
def test_SymantecAppStream(self, caplog):
sample = os.path.join(self.exploits_path, "SymantecAppStream.html")
expected = [
"[Symantec AppStream LaunchObj ActiveX] Arbitrary File Download and Execute"
]
self.do_perform_test(caplog, sample, expected)
def test_SymantecBackupExec(self, caplog):
sample = os.path.join(self.exploits_path, "SymantecBackupExec.htm")
expected = ["[Symantec BackupExec ActiveX] Overflow in property _DOWText0"]
self.do_perform_test(caplog, sample, expected)
def test_SymantecBackupExec2(self, caplog):
sample = os.path.join(self.exploits_path, "SymantecBackupExec2.htm")
expected = ["[Symantec BackupExec ActiveX] Overflow in property _DOWText6"]
self.do_perform_test(caplog, sample, expected)
def test_SymantecBackupExec3(self, caplog):
sample = os.path.join(self.exploits_path, "SymantecBackupExec3.htm")
expected = ["[Symantec BackupExec ActiveX] Overflow in property _MonthText0"]
self.do_perform_test(caplog, sample, expected)
def test_SymantecBackupExec4(self, caplog):
sample = os.path.join(self.exploits_path, "SymantecBackupExec4.htm")
expected = ["[Symantec BackupExec ActiveX] Overflow in property _MonthText11"]
self.do_perform_test(caplog, sample, expected)
def test_Toshiba(self, caplog):
sample = os.path.join(self.exploits_path, "Toshiba.htm")
expected = [
"[Toshiba Surveillance RecordSend Class ActiveX] Overflow in SetPort"
]
self.do_perform_test(caplog, sample, expected)
def test_UUSeeUpdate(self, caplog):
sample = os.path.join(self.exploits_path, "UUSeeUpdate.htm")
expected = ["[UUsee UUPgrade ActiveX] Attack in Update Method"]
self.do_perform_test(caplog, sample, expected)
def test_UniversalUpload(self, caplog):
sample = os.path.join(self.exploits_path, "UniversalUpload.htm")
expected = ["[Universal HTTP File Upload ActiveX] Deleting C:/tmp.txt"]
self.do_perform_test(caplog, sample, expected)
def test_VisualStudioDTE80(self, caplog):
sample = os.path.join(self.exploits_path, "VisualStudioDTE80.html")
expected = [
"[VisualStudio.DTE.8.0 ActiveX] CreateObject (Shell.Application)",
]
self.do_perform_test(caplog, sample, expected)
def test_VLC(self, caplog):
sample = os.path.join(self.exploits_path, "VLC.htm")
expected = ["[VLC ActiveX] getVariable Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_VLC2(self, caplog):
sample = os.path.join(self.exploits_path, "VLC2.htm")
expected = ["[VLC ActiveX] setVariable Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_VLC3(self, caplog):
sample = os.path.join(self.exploits_path, "VLC3.htm")
expected = ["[VLC ActiveX] addTarget Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_WinZip(self, caplog):
sample = os.path.join(self.exploits_path, "WinZip.htm")
expected = [
"[WinZip ActiveX] CreateNewFolderFromName Overflow",
"WinExec",
"calc",
"ExitProcess",
]
self.do_perform_test(caplog, sample, expected)
def test_WMEncProfileManager(self, caplog):
sample = os.path.join(self.exploits_path, "WMEncProfileManager.htm")
expected = [
"[Microsoft Windows Media Encoder WMEX.DLL ActiveX] GetDetailsString Method Buffer Overflow",
"CVE-2008-3008",
"calc.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_WMP(self, caplog):
sample = os.path.join(self.exploits_path, "WMP.html")
expected = ["http://192.168.1.100/putty.exe"]
self.do_perform_test(caplog, sample, expected)
def test_XMLDOM_evasion(self, caplog):
sample = os.path.join(self.exploits_path, "XMLDOM-evasion.html")
expected = [
r"[Microsoft XMLDOM ActiveX] Attempting to load res://c:\Windows\System32\drivers\kl1.sys"
]
self.do_perform_test(caplog, sample, expected)
def test_Xupload(self, caplog):
sample = os.path.join(self.exploits_path, "Xupload.htm")
expected = ["[XUpload ActiveX] Overflow in AddFolder method"]
self.do_perform_test(caplog, sample, expected)
def test_YahooJukebox(self, caplog):
sample = os.path.join(self.exploits_path, "YahooJukebox.htm")
expected = ["[Yahoo! Music Jukebox ActiveX] Overflow in AddBitmap"]
self.do_perform_test(caplog, sample, expected)
def test_YahooMessengerYVerInfo(self, caplog):
sample = os.path.join(self.exploits_path, "YahooMessengerYVerInfo.htm")
expected = [
"[Yahoo! Messenger 8.x YVerInfo.dll ActiveX Control] Overflow in fvCom arg0",
"WinExec",
"calc",
"ExitProcess",
]
self.do_perform_test(caplog, sample, expected)
def test_YahooMessengerCyft(self, caplog):
sample = os.path.join(self.exploits_path, "YahooMessengerCyft.html")
expected = [
"[Yahoo! Messenger 8.x CYTF] Downloading http://192.168.1.100/putty.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_YahooMessengerYwcvwr_GetComponentVersion(self, caplog):
sample = os.path.join(
self.exploits_path, "YahooMessengerYwcvwr_GetComponentVersion.htm"
)
expected = [
"[Yahoo! Messenger 8.x Ywcvwr ActiveX] GetComponentVersion Overflow",
"LoadLibraryA",
"port = 4444",
"bind",
"listen",
"accept",
"CreateProcess",
"cmd",
]
self.do_perform_test(caplog, sample, expected)
def test_YahooMessengerYwcvwr_server(self, caplog):
sample = os.path.join(self.exploits_path, "YahooMessengerYwcvwr_server.htm")
expected = ["[Yahoo! Messenger 8.x Ywcvwr ActiveX] Server Console Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_ZenturiProgramCheckerAttack(self, caplog):
sample = os.path.join(self.exploits_path, "ZenturiProgramCheckerAttack.htm")
expected = [
"[ZenturiProgramChecker ActiveX] Attack in DebugMsgLog function",
"WinExec",
"calc.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_ZenturiProgramCheckerAttack2(self, caplog):
sample = os.path.join(self.exploits_path, "ZenturiProgramCheckerAttack2.htm")
expected = [
"[ZenturiProgramChecker ActiveX] Attack in DownloadFile function",
]
self.do_perform_test(caplog, sample, expected)
def test_ZenturiProgramCheckerAttack3(self, caplog):
sample = os.path.join(self.exploits_path, "ZenturiProgramCheckerAttack3.htm")
expected = [
"[ZenturiProgramChecker ActiveX] Attack in NavigateUrl function",
]
self.do_perform_test(caplog, sample, expected)
def test_aol_ampx(self, caplog):
sample = os.path.join(self.exploits_path, "aol_ampx.html")
expected = [
"[AOL Radio AOLMediaPlaybackControl ActiveX] Overflow in AppendFileToPlayList"
]
self.do_perform_test(caplog, sample, expected)
def test_blackhole(self, caplog):
sample = os.path.join(self.exploits_path, "blackhole.html")
expected = [
"CVE-2006-0003",
"adobeupdate.exe",
"Microsoft Internet Explorer HCP Scheme Detected"
"Microsoft Windows Help Center Malformed Escape Sequences Incorrect Handling",
"[doRun redirection]",
]
self.do_perform_test(caplog, sample, expected)
def test_domino(self, caplog):
sample = os.path.join(self.exploits_path, "domino.html")
expected = [
"[IBM Lotus Domino Web Access Control ActiveX] Overflow in General_ServerName property"
]
self.do_perform_test(caplog, sample, expected)
def test_hpinfo(self, caplog):
sample = os.path.join(self.exploits_path, "hpinfo.html")
expected = [
r"[HP Info Center ActiveX] LaunchApp called to run: c:\windows\system32\cmd.exe /C c:\ftpd.bat&del c:\ftpd.bat&del c:\ftpd&del c:\malware.exe"
]
self.do_perform_test(caplog, sample, expected)
def test_hpinfo2(self, caplog):
sample = os.path.join(self.exploits_path, "hpinfo2.html")
expected = ["[HP Info Center ActiveX] GetRegValue, reading: //"]
self.do_perform_test(caplog, sample, expected)
def test_hpinfo3(self, caplog):
sample = os.path.join(self.exploits_path, "hpinfo3.html")
expected = [
r"[HP Info Center ActiveX] SetRegValue: HKEY_LOCAL_MACHINE/SOFTWARE\Classes\CLSID\{62DDEB79-15B2-41E3-8834-D3B80493887A}\InprocServer32/ set to"
]
self.do_perform_test(caplog, sample, expected)
def test_hpupdate1(self, caplog):
sample = os.path.join(self.exploits_path, "hpupdate1.html")
expected = [
"[HP Info Center ActiveX] SaveToFile()",
"writes to c:\\temp\\testfile.txt",
]
self.do_perform_test(caplog, sample, expected)
def test_hpupdate2(self, caplog):
sample = os.path.join(self.exploits_path, "hpupdate2.html")
expected = [
"[HP Info Center ActiveX] SaveToFile()",
r"writes to c:\WINDOWS\system32\dllcache\ntoskrnl.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_intuit(self, caplog):
sample = os.path.join(self.exploits_path, "intuit.html")
expected = ["[AnswerWorks ActiveX] Overflow in GetHistory"]
self.do_perform_test(caplog, sample, expected)
def test_qvod(self, caplog):
sample = os.path.join(self.exploits_path, "qvod.html")
expected = [
"LoadLibraryA",
"URLDownloadToFile",
"http://www.360.cn.sxxsnp2.cn/d5.css",
"WinExec",
"U.exe",
"ExitProcess",
]
self.do_perform_test(caplog, sample, expected)
def test_qvod_js(self, caplog):
sample = os.path.join(self.exploits_path, "qvod.js")
expected = [
"LoadLibraryA",
"URLDownloadToFile",
"http://www.360.cn.sxxsnp2.cn/d5.css",
"WinExec",
"U.exe",
"ExitProcess",
]
self.do_perform_test(caplog, sample, expected)
def test_qvodctl(self, caplog):
sample = os.path.join(self.exploits_path, "qvodctl.html")
expected = ["[Qvod Player QvodCtrl Class ActiveX] Overflow in URL property"]
self.do_perform_test(caplog, sample, expected)
def test_qvodsrc2(self, caplog):
sample = os.path.join(self.exploits_path, "qvodsrc2.html")
expected = [
"LoadLibraryA",
"URLDownloadToFile",
"http://www.360.cn.sxxsnp2.cn/d5.css",
"WinExec",
"U.exe",
"ExitProcess",
]
self.do_perform_test(caplog, sample, expected)
def test_realplayer_mod(self, caplog):
sample = os.path.join(self.exploits_path, "realplayer-mod.html")
expected = [
"[RealMedia RealPlayer rmoc3260.DLL ActiveX] Overflow in Console property"
]
self.do_perform_test(caplog, sample, expected)
def test_realplayer_mod_2(self, caplog):
sample = os.path.join(self.exploits_path, "realplayer-mod-2.html")
expected = [
"[RealMedia RealPlayer Ierpplug.DLL ActiveX] Overflow in DoAutoUpdateRequest"
]
self.do_perform_test(caplog, sample, expected)
def test_rgod_imesh(self, caplog):
sample = os.path.join(self.exploits_path, "rgod_imesh.html")
expected = [
"[iMesh IMWebControl ActiveX] NULL value in ProcessRequestEx",
"cmd.exe /c net user sun tzu /ADD && net localgroup Administrators sun /ADD",
]
self.do_perform_test(caplog, sample, expected)
def test_show_283_1(self, caplog):
sample = os.path.join(self.exploits_path, "show-283-1.html")
expected = ["[Xunlei DPClient.Vod.1 ActiveX] DownURL2 Method Buffer Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_ssreader2(self, caplog):
sample = os.path.join(self.exploits_path, "ssreader2.html")
expected = ["[SSReader Pdg2 ActiveX] Register Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_ssreader_0day(self, caplog):
sample = os.path.join(self.exploits_path, "ssreader_0day.html")
expected = ["[SSReader Pdg2 ActiveX] Register Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_ssreader_noplus(self, caplog):
sample = os.path.join(self.exploits_path, "ssreader_noplus.html")
expected = ["[SSReader Pdg2 ActiveX] Register Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_URL(self, caplog):
sample = os.path.join(self.exploits_path, "storm_URL.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] URL Console Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_advancedOpen(self, caplog):
sample = os.path.join(self.exploits_path, "storm_advancedOpen.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] advanceOpen Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_backImage(self, caplog):
sample = os.path.join(self.exploits_path, "storm_backImage.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] backImage Console Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_isDVDPath(self, caplog):
sample = os.path.join(self.exploits_path, "storm_isDVDPath.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] isDVDPath Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_rawParse(self, caplog):
sample = os.path.join(self.exploits_path, "storm_rawParse.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] rawParse Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_titleImage(self, caplog):
sample = os.path.join(self.exploits_path, "storm_titleImage.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] titleImage Console Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_storm_onBeforeVideoDownload(self, caplog):
sample = os.path.join(self.exploits_path, "storm_onBeforeVideoDownload.htm")
expected = ["[MPS.StormPlayer.1 ActiveX] OnBeforeVideoDownload Method Overflow"]
self.do_perform_test(caplog, sample, expected)
def test_stormplayer(self, caplog):
sample = os.path.join(self.exploits_path, "stormplayer.html")
expected = [
"[MPS.StormPlayer.1 ActiveX] rawParse Method Overflow",
"GetProcAddress",
"GetSystemDirectoryA",
"WinExec",
"ExitThread",
"http://w.qqnetcn.cn/d2.exe",
"a.exe",
]
self.do_perform_test(caplog, sample, expected)
def test_toshiba(self, caplog):
sample = os.path.join(self.exploits_path, "toshiba.html")
expected = [
"[Toshiba Surveillance RecordSend Class ActiveX] Overflow in SetPort"
]
self.do_perform_test(caplog, sample, expected)
def test_xupload(self, caplog):
sample = os.path.join(self.exploits_path, "xupload.html")
expected = ["[XUpload ActiveX] Overflow in AddFolder method"]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2012_4792(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2012-4792.html")
expected = [
"[Microsoft Internet Explorer] Microsoft Internet Explorer CButton Object Use-After-Free Vulnerability (CVE-2012-4792)",
"LoadLibraryA",
"user32",
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2012_4792_2(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2012-4792-2.html")
expected = [
"[Microsoft Internet Explorer] Microsoft Internet Explorer CButton Object Use-After-Free Vulnerability (CVE-2012-4792)",
"LoadLibraryA",
"URLDownloadToFileA",
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2012_4792_3(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2012-4792-3.html")
expected = [
"[Microsoft Internet Explorer] Microsoft Internet Explorer CButton Object Use-After-Free Vulnerability (CVE-2012-4792)",
"WinExec",
"ExitProcess",
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2010_1885(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2010-1885.html")
expected = [
"Microsoft Internet Explorer HCP Scheme Detected",
"Microsoft Windows Help Center Malformed Escape Sequences Incorrect Handling",
'[WScript.Shell ActiveX] Executing: Run("calc.exe")',
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2010_1885_2(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2010-1885-2.html")
expected = [
"Microsoft Internet Explorer HCP Scheme Detected",
"Microsoft Windows Help Center Malformed Escape Sequences Incorrect Handling",
'[WScript.Shell ActiveX] Executing: Run("calc.exe")',
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2010_1885_3(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2010-1885-3.html")
expected = [
"Microsoft Internet Explorer HCP Scheme Detected",
"Microsoft Windows Help Center Malformed Escape Sequences Incorrect Handling",
"[WScript.Shell ActiveX] Run (Stage 1) Saving file 52bfb8491cbf6c39d44d37d3c59ef406",
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2017_0022(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2017-0022.html")
expected = ["Microsoft Internet Explorer RES Scheme Detected"]
self.do_perform_test(caplog, sample, expected)
def test_RDSDataSpace2(self, caplog):
sample = os.path.join(self.exploits_path, "RDSDataSpace2.htm")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Microsoft.XMLHTTP)",
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Adodb.Stream)",
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] GetSpecialFolder("2")',
'[WScript.Shell ActiveX] Expanding environment string "%TEMP%"',
"[Adodb.Stream ActiveX] open",
"[Scripting.FileSystemObject ActiveX] BuildPath",
"[Adodb.Stream ActiveX] Write",
"[Adodb.Stream ActiveX] SaveToFile",
"[Adodb.Stream ActiveX] Close",
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Shell.Application)",
"[Shell.Application ActiveX] ShellExecute",
]
self.do_perform_test(caplog, sample, expected)
def test_testVsaIDEDTE(self, caplog):
sample = os.path.join(self.exploits_path, "testVsaIDEDTE.html")
expected = ["[VsaIDE.DTE ActiveX] CreateObject (WScript.Network)"]
self.do_perform_test(caplog, sample, expected)
def test_testVsmIDEDTE(self, caplog):
sample = os.path.join(self.exploits_path, "testVsmIDEDTE.html")
expected = ["[VsmIDE.DTE ActiveX] CreateObject (WScript.Network)"]
self.do_perform_test(caplog, sample, expected)
def test_AolAttack(self, caplog):
sample = os.path.join(self.exploits_path, "AolAttack.html")
expected = ["[AOL ActiveX] Attack in LinkSBIcons function", "CVE-2006-5820"]
self.do_perform_test(caplog, sample, expected)
def test_ChinaGames(self, caplog):
sample = os.path.join(self.exploits_path, "ChinaGames.html")
expected = [
"[CGAgent ActiveX] CreateChinagames Method Buffer Overflow",
"CVE-2009-1800",
]
self.do_perform_test(caplog, sample, expected)
def test_OWCSpreadsheet(self, caplog):
sample = os.path.join(self.exploits_path, "OWCSpreadsheet.html")
expected = [
"[OWC 10/11.Spreadsheet ActiveX] Attack in Evaluate function",
"[OWC 10/11.Spreadsheet ActiveX] Attack in _Evaluate function",
]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2013_2423(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2013-2423.html")
expected = [
"[JNLP Detected]",
"[Java WebStart] Java Security Warning Bypass (CVE-2013-2423)",
]
self.do_perform_test(caplog, sample, expected)
def test_JavaDeploymentToolkit(self, caplog):
sample = os.path.join(self.exploits_path, "JavaDeploymentToolkit.html")
expected = ["Launching: http: -J-jar http://192.168.1.100/exploit.jar none"]
self.do_perform_test(caplog, sample, expected)
def test_CVE_2021_40444(self, caplog):
sample = os.path.join(self.exploits_path, "test-CVE-2021-40444.html")
expected = [
"[Microsoft XMLHTTP ActiveX] open('GET', 'http://127.0.0.1/calc.cab', False)",
"[Microsoft XMLHTTP ActiveX] Fetching from URL http://127.0.0.1/calc.cab (method: GET)",
]
self.do_perform_test(caplog, sample, expected)
def test_Qakbot(self, caplog):
sample = os.path.join(self.exploits_path, "qakbot.html")
expected = [
"File 'doc/Valid445.lnk' is encrypted, password required for extraction",
]
self.do_perform_test(caplog, sample, expected, useragent="osx10chrome97")
def test_Mimikatz(self, caplog):
sample = os.path.join(self.exploits_path, "mimikatz.js")
expected = [
"ActiveXObject: system.text.asciiencoding",
"[System.Text.ASCIIEncoding] GetByteCount_2 count = 20164",
"[System.Text.ASCIIEncoding] GetBytes_4",
"ActiveXObject: system.security.cryptography.frombase64transform",
"[System.Security.Cryptography.FromBase64ToTransform] TransformFinalBlock",
"ActiveXObject: system.io.memorystream",
"[System.IO.MemoryStream] Write",
"ActiveXObject: system.runtime.serialization.formatters.binary.binaryformatter",
"ActiveXObject: system.collections.arraylist",
"[System.Runtime.Serialization.Formatters.Binary.BinaryFormatter] Deserialize_2",
"[System.Collections.ArrayList] Add",
"[System.Collections.ArrayList] ToArray",
]
self.do_perform_test(caplog, sample, expected)
| 54,874
|
Python
|
.py
| 1,083
| 41.195753
| 166
| 0.649462
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,692
|
test_screenshot.py
|
buffer_thug/tests/functional/test_screenshot.py
|
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestScreenshot(object):
def do_perform_test(self, caplog, url, expected, type_="remote"):
thug = ThugAPI()
thug.set_useragent("win7ie90")
thug.disable_screenshot()
thug.enable_screenshot()
thug.set_file_logging()
thug.set_json_logging()
thug.set_ssl_verify()
thug.log_init(url)
m = getattr(thug, "run_{}".format(type_))
m(url)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_antifork(self, caplog):
expected = []
self.do_perform_test(caplog, "https://buffer.antifork.org", expected)
def test_invalid_ctype(self, caplog):
expected = []
self.do_perform_test(
caplog, "https://buffer.antifork.org/images/antifork.jpg", expected
)
| 1,079
|
Python
|
.py
| 30
| 27.1
| 79
| 0.601736
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,693
|
test_classifiers.py
|
buffer_thug/tests/functional/test_classifiers.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestClassifiers(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
classifiers_path = os.path.join(cwd_path, os.pardir, "samples/classifiers")
signatures_path = os.path.join(cwd_path, os.pardir, "signatures")
def catchall(self, url, *args):
log.warning("[CATCHALL Custom Classifier] URL: %s", url)
def do_perform_remote_test(self, caplog, url, expected):
thug = ThugAPI()
thug.set_useragent("win7ie90")
thug.set_image_processing()
thug.set_threshold(2)
thug.disable_cert_logging()
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(url)
thug.add_htmlclassifier(
os.path.join(self.signatures_path, "html_signature_12.yar")
)
thug.add_imageclassifier(
os.path.join(self.signatures_path, "image_signature_14.yar")
)
thug.add_imageclassifier(
os.path.join(self.signatures_path, "image_signature_15.yar")
)
thug.run_remote(url)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def do_perform_test(self, caplog, sample, expected):
thug = ThugAPI()
thug.set_useragent("winxpie70")
thug.set_threshold(2)
thug.disable_cert_logging()
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(sample)
thug.reset_customclassifiers()
thug.add_customclassifier("url", self.catchall)
thug.reset_customclassifiers()
thug.add_customclassifier("html", self.catchall)
thug.add_customclassifier("url", self.catchall)
thug.add_customclassifier("js", self.catchall)
thug.add_customclassifier("vbs", self.catchall)
thug.add_customclassifier("sample", self.catchall)
thug.add_customclassifier("cookie", self.catchall)
thug.add_customclassifier("text", self.catchall)
thug.add_htmlclassifier(
os.path.join(self.signatures_path, "html_signature_1.yar")
)
thug.add_jsclassifier(os.path.join(self.signatures_path, "js_signature_2.yar"))
thug.add_urlclassifier(
os.path.join(self.signatures_path, "url_signature_3.yar")
)
thug.add_urlfilter(os.path.join(self.signatures_path, "url_filter_4.yar"))
thug.add_textclassifier(
os.path.join(self.signatures_path, "text_signature_5.yar")
)
thug.add_vbsclassifier(
os.path.join(self.signatures_path, "vbs_signature_6.yar")
)
thug.add_urlclassifier(
os.path.join(self.signatures_path, "url_signature_7.yar")
)
thug.add_urlclassifier(
os.path.join(self.signatures_path, "url_signature_13.yar")
)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_html_classifier_1(self, caplog):
sample = os.path.join(self.classifiers_path, "test1.html")
expected = [
"[HTML Classifier]",
"samples/classifiers/test1.html (Rule: html_signature_1, Classification: strVar)",
]
self.do_perform_test(caplog, sample, expected)
def test_js_classifier_2(self, caplog):
sample = os.path.join(self.classifiers_path, "test2.html")
expected = [
"[JS Classifier]",
"samples/classifiers/test2.html (Rule: js_signature_2, Classification: )",
]
self.do_perform_test(caplog, sample, expected)
def test_url_classifier_3(self, caplog):
sample = os.path.join(self.classifiers_path, "test3.html")
expected = [
"[URL Classifier] URL: https://antifork.org (Rule: url_signature_3, Classification: )",
"[CATCHALL Custom Classifier] URL: https://antifork.org",
]
self.do_perform_test(caplog, sample, expected)
def test_url_filter_4(self, caplog):
sample = os.path.join(self.classifiers_path, "test4.html")
expected = [
"[URLFILTER Classifier] URL: http://www.google.com (Rule: url_filter_4, Classification: )",
"[CATCHALL Custom Classifier] URL: http://www.google.com",
]
self.do_perform_test(caplog, sample, expected)
def test_text_signature_5(self, caplog):
sample = os.path.join(self.classifiers_path, "test5.html")
expected = [
"[TEXT Classifier]",
"samples/classifiers/test5.html (Rule: text_signature_5, Classification: )",
]
self.do_perform_test(caplog, sample, expected)
def test_vbs_signature_6(self, caplog):
sample = os.path.join(self.classifiers_path, "test6.html")
expected = [
"[VBS Classifier]",
"samples/classifiers/test6.html (Rule: vbs_signature_6, Classification: )",
]
self.do_perform_test(caplog, sample, expected)
def test_url_classifier_7(self, caplog):
sample = os.path.join(self.classifiers_path, "test7.html")
expected = [
"[discard_meta_domain_whitelist] Whitelisted domain: buffer.github.io",
"[CATCHALL Custom Classifier] URL: https://buffer.github.io/thug/",
]
self.do_perform_test(caplog, sample, expected)
def test_vbs_signature_8(self, caplog):
sample = os.path.join(self.classifiers_path, "test8.html")
expected = [
"[VBS Classifier]",
"samples/classifiers/test8.html (Rule: vbs_signature_6, Classification: )",
]
self.do_perform_test(caplog, sample, expected)
def test_html_classifier_12(self, caplog):
expected = ["[discard_meta_domain_whitelist] Whitelisted domain: antifork.org"]
self.do_perform_remote_test(caplog, "buffer.antifork.org", expected)
def test_url_classifier_13(self, caplog):
sample = os.path.join(self.classifiers_path, "test13.html")
expected = [
"[URL Classifier] URL: https://www.antifork.org/ (Rule: url_signature_13, Classification: antifork.org)"
]
self.do_perform_test(caplog, sample, expected)
def test_url_classifier_14(self, caplog):
expected = [
"[IMAGE Classifier] URL: https://buffer.antifork.org/images/antifork.jpg (Rule: image_signature_14, Classification: Antifork)",
"[discard_meta_domain_whitelist] Whitelisted domain: buffer.antifork.org (URL: https://buffer.antifork.org/images/antifork.jpg)",
]
self.do_perform_remote_test(caplog, "https://buffer.antifork.org", expected)
| 7,027
|
Python
|
.py
| 153
| 36.300654
| 141
| 0.630454
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,694
|
test_jquery.py
|
buffer_thug/tests/functional/test_jquery.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestJQuerySamples(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
jquery_path = os.path.join(cwd_path, os.pardir, "samples/jQuery")
def do_perform_test(self, caplog, sample, expected):
thug = ThugAPI()
thug.set_useragent("win7ie90")
thug.set_events("click,storage")
thug.disable_cert_logging()
thug.set_file_logging()
thug.set_json_logging()
thug.set_features_logging()
thug.set_ssl_verify()
thug.get_ssl_verify()
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_jquery_1(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-1.html")
expected = ["[Window] Alert Text: Ready"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_2(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-2.html")
expected = [
'<a class="foobar" href="http://www.google.com" id="myId">jQuery</a>'
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_3(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-3.html")
expected = [
'<div class="notMe">',
'<div class="myClass" foo="bar">div class="myClass"</div>',
'<span class="myClass" foo="bar">span class="myClass"</span>',
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_4(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-4.html")
expected = ['<div foo="bar" id="notMe" name="whoa">Aieeee</div>']
self.do_perform_test(caplog, sample, expected)
def test_jquery_5(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-5.html")
expected = ['<div class="myClass" foo="bar" name="whoa">Aieeee</div>']
self.do_perform_test(caplog, sample, expected)
def test_jquery_6(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-6.html")
expected = [
'<div class="myClass"><p>Just a modified p</p></div>',
'<div class="myClass"><foo>Just a foo</foo></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_7(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-7.html")
expected = ["<h3>New text for the third h3</h3>"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_8(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-8.html")
expected = [
"<h3>New text for the first h1</h3>",
"<h3>New text for the third h3</h3>",
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_9(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-9.html")
expected = [
'<p>Yet another p</p><div class="container1">',
'<div class="inner1">Hello<p>Just a p</p></div>',
'<div class="inner2">Goodbye<p>Just another p</p></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_10(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-10.html")
expected = ["<ul><li>list item</li></ul>"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_11(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-11.html")
expected = ['<div id="target"><td>Hello World</td></div>']
self.do_perform_test(caplog, sample, expected)
def test_jquery_12(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-12.html")
expected = ["[Window] Alert Text: 2", "[Window] Alert Text: Foo"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_14(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-14.html")
expected = ["[Window] Alert Text: 1", "[Window] Alert Text: child"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_15(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-15.html")
expected = ["[Window] Alert Text: parent"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_16(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-16.html")
expected = [
"[Window] Alert Text: child",
"[Window] Alert Text: parent",
"[Window] Alert Text: grandparent",
]
self.do_perform_test(caplog, sample, expected)
def disabled_test_jquery_17(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-17.html")
expected = ["[Window] Alert Text: child", "[Window] Alert Text: parent"]
self.do_perform_test(caplog, sample, expected)
def disabled_test_jquery_18(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-18.html")
expected = ["[Window] Alert Text: child"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_19(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-19.html")
expected = ["[Window] Alert Text: child"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_20(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-20.html")
expected = [
"[Window] Alert Text: parent",
"[Window] Alert Text: surrogateParent1",
"[Window] Alert Text: surrogateParent2",
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_21(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-21.html")
expected = [
"[Window] Alert Text: child",
"[Window] Alert Text: parent",
"[Window] Alert Text: surrogateParent1",
"[Window] Alert Text: surrogateParent2",
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_22(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-22.html")
expected = ["[Window] Alert Text: surrogateParent1"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_24(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-24.html")
expected = [
"[Window] Alert Text: surrogateParent1",
"[Window] Alert Text: surrogateParent2",
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_25(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-25.html")
expected = ["[Window] Alert Text: surrogateParent1"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_26(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-26.html")
expected = ["[Window] Alert Text: surrogateParent2"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_27(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-27.html")
expected = [
"[Window] Alert Text: parent",
"[Window] Alert Text: surrogateParent1",
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_28(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-28.html")
expected = ["[Window] Alert Text: surrogateParent1"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_29(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-29.html")
expected = ["[Window] Alert Text: parent"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_32(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-32.html")
expected = [
"[Window] Alert Text: Inside the callback",
"__version__",
"__configuration_path__",
]
self.do_perform_test(caplog, sample, expected)
def test_jquery_33(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-33.html")
expected = [
"[Window] Alert Text: Done",
"[Window] Alert Text: The request is complete",
]
self.do_perform_test(caplog, sample, expected)
| 8,756
|
Python
|
.py
| 184
| 38.347826
| 81
| 0.614299
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,695
|
test_url_standard.py
|
buffer_thug/tests/functional/test_url_standard.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestURLStandard(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
misc_path = os.path.join(cwd_path, os.pardir, "samples/misc")
def do_perform_test(self, caplog, sample, expected):
thug = ThugAPI()
thug.set_useragent("osx10chrome97")
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_url(self, caplog):
sample = os.path.join(self.misc_path, "testURL.html")
expected = [
"URL1 pathname: /foo/bar",
"URL1 protocol: https:",
"URL2 href: https://www.example.com:8080/cats#foo",
"URL2 host: www.example.com:8080",
"URL2 hostname: www.example.com",
"URL2 origin: https://www.example.com:8080",
"URL2 pathname: /cats",
"URL2 protocol: https:",
"URL2 port: 8080",
"URL2 hash: #foo",
"URL3 href: https://example.com",
"URL4 href: https://example.com:8081",
"URL5 href: https://example.com/dogs#foo",
"URL6 search: foo=bar",
"URL6 href: https://username2@www.example.com:8080/?foo=bar",
"URL7 username: username2",
"URL7 password: password2",
"URL7 href: https://username2:password2@www.example.com:8080",
"URL8 href: https://:password@www.example.com",
"URL8 href: https://:password2@www.example.com",
]
self.do_perform_test(caplog, sample, expected)
def test_urlsearchparams(self, caplog):
sample = os.path.join(self.misc_path, "testURLSearchParams.html")
expected = [
"params1.toString() = q=URLUtils.searchParams&topic=api",
"params2.toString() = key=730d67&foo=bar",
"params3.toString() before set = p=params3&foo=bar&foo=baz",
'params3.get("p") === "params3": true',
'params3.get("q") === null: true',
'params3.has("foo"): true',
'params3.get("foo"): bar',
"params3.toString() after set = p=params3&foo=overwrited",
"params3.toString() after delete = p=params3",
'params3.has("foo") after delete: false',
'params4.has("query"): true',
'params4.get("query"): value',
'params5.has("foo"): true',
'params6.has("foo"): true',
"params7.toString() before sort = foo=foz&foo=bar&bar=baz",
"params7.toString() after sort = bar=baz&foo=foz&foo=bar",
]
self.do_perform_test(caplog, sample, expected)
| 2,911
|
Python
|
.py
| 65
| 33.907692
| 74
| 0.571328
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,696
|
test_inspector.py
|
buffer_thug/tests/functional/test_inspector.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestInspector(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
misc_path = os.path.join(cwd_path, os.pardir, "samples/misc")
signatures_path = os.path.join(cwd_path, os.pardir, "signatures")
def do_perform_test(self, caplog, sample, expected):
thug = ThugAPI()
thug.set_useragent("winxpie70")
thug.set_ssl_verify()
thug.log_init(sample)
thug.add_htmlclassifier(os.path.join(self.signatures_path, "inspector.yar"))
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_inspector_1(self, caplog):
sample = os.path.join(self.misc_path, "testInspector.html")
expected = [
"[HTMLInspector] Detected potential code obfuscation",
"[HTML Classifier]",
"samples/misc/testInspector.html (Rule: OnlineID, Classification: )",
]
self.do_perform_test(caplog, sample, expected)
| 1,251
|
Python
|
.py
| 30
| 33.033333
| 84
| 0.637117
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,697
|
test_misc_ie70.py
|
buffer_thug/tests/functional/test_misc_ie70.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestMiscSamplesIE(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
misc_path = os.path.join(cwd_path, os.pardir, "samples/misc")
def do_perform_test(self, caplog, sample, expected):
thug = ThugAPI()
thug.set_useragent("winxpie70")
thug.set_events("click")
thug.set_connect_timeout(2)
thug.disable_cert_logging()
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_plugindetect1(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"]
self.do_perform_test(caplog, sample, expected)
def test_plugindetect2(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html")
expected = [
"AdobeReader version: 9,1,0,0",
"Flash version: 10,0,64,0",
"Java version: 1,6,0,32",
"ActiveXObject: javawebstart.isinstalled.1.6.0.0",
"ActiveXObject: javaplugin.160_32",
]
self.do_perform_test(caplog, sample, expected)
def test_test1(self, caplog):
sample = os.path.join(self.misc_path, "test1.html")
expected = ["[Window] Alert Text: one"]
self.do_perform_test(caplog, sample, expected)
def test_test2(self, caplog):
sample = os.path.join(self.misc_path, "test2.html")
expected = ["[Window] Alert Text: Java enabled: true"]
self.do_perform_test(caplog, sample, expected)
def test_test3(self, caplog):
sample = os.path.join(self.misc_path, "test3.html")
expected = ["[Window] Alert Text: foo"]
self.do_perform_test(caplog, sample, expected)
def test_testAppendChild(self, caplog):
sample = os.path.join(self.misc_path, "testAppendChild.html")
expected = [
"Don't care about me",
"Just a sample",
"Attempt to append a null element failed",
"Attempt to append an invalid element failed",
"Attempt to append a text element failed",
"Attempt to append a read-only element failed",
]
self.do_perform_test(caplog, sample, expected)
def test_testClipboardData(self, caplog):
sample = os.path.join(self.misc_path, "testClipboardData.html")
expected = ["Test ClipboardData"]
self.do_perform_test(caplog, sample, expected)
def test_testCloneNode(self, caplog):
sample = os.path.join(self.misc_path, "testCloneNode.html")
expected = [
'<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>'
]
self.do_perform_test(caplog, sample, expected)
def test_testCloneNode2(self, caplog):
sample = os.path.join(self.misc_path, "testCloneNode2.html")
expected = [
"[Window] Alert Text: [object HTMLButtonElement]",
"[Window] Alert Text: Clone node",
"[Window] Alert Text: None",
"[Window] Alert Text: [object Attr]",
"[Window] Alert Text: True",
]
self.do_perform_test(caplog, sample, expected)
def test_testCreateStyleSheet(self, caplog):
sample = os.path.join(self.misc_path, "testCreateStyleSheet.html")
expected = [
"[Window] Alert Text: style1.css",
"[Window] Alert Text: style2.css",
"[Window] Alert Text: style3.css",
"[Window] Alert Text: style4.css",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentAll(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentAll.html")
expected = ["http://www.google.com"]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentWrite1(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentWrite1.html")
expected = [
"Foobar",
"Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>",
]
self.do_perform_test(caplog, sample, expected)
def test_testInnerHTML(self, caplog):
sample = os.path.join(self.misc_path, "testInnerHTML.html")
expected = ["dude", "Fred Flinstone"]
self.do_perform_test(caplog, sample, expected)
def test_testInsertBefore(self, caplog):
sample = os.path.join(self.misc_path, "testInsertBefore.html")
expected = [
"<div>Just a sample</div><div>I'm your reference!</div></body></html>",
"[ERROR] Attempting to insert null element",
"[ERROR] Attempting to insert an invalid element",
"[ERROR] Attempting to insert using an invalid reference element",
"[ERROR] Attempting to insert a text node using an invalid reference element",
]
self.do_perform_test(caplog, sample, expected)
def test_testPlugins(self, caplog):
sample = os.path.join(self.misc_path, "testPlugins.html")
expected = [
"Shockwave Flash 10.0.64.0",
"Windows Media Player 7",
"Adobe Acrobat",
]
self.do_perform_test(caplog, sample, expected)
def test_testMetaXUACompatibleEdge(self, caplog):
sample = os.path.join(self.misc_path, "testMetaXUACompatibleEdge.html")
expected = ["[Window] Alert Text: 7"]
self.do_perform_test(caplog, sample, expected)
def test_testMetaXUACompatibleEmulateIE(self, caplog):
sample = os.path.join(self.misc_path, "testMetaXUACompatibleEmulateIE.html")
expected = ["[Window] Alert Text: 7"]
self.do_perform_test(caplog, sample, expected)
def test_testMetaXUACompatibleIE(self, caplog):
sample = os.path.join(self.misc_path, "testMetaXUACompatibleIE.html")
expected = ["[Window] Alert Text: 7"]
self.do_perform_test(caplog, sample, expected)
def test_testNode(self, caplog):
sample = os.path.join(self.misc_path, "testNode.html")
expected = ["thelink", "thediv"]
self.do_perform_test(caplog, sample, expected)
def test_testNode2(self, caplog):
sample = os.path.join(self.misc_path, "testNode2.html")
expected = ["thelink", "thediv2"]
self.do_perform_test(caplog, sample, expected)
def test_testScope(self, caplog):
sample = os.path.join(self.misc_path, "testScope.html")
expected = [
"foobar",
"foo",
"bar",
"True",
"3",
"2012-10-07 11:13:00",
"3.14159265359",
"/foo/i",
]
self.do_perform_test(caplog, sample, expected)
def test_testSetInterval(self, caplog):
sample = os.path.join(self.misc_path, "testSetInterval.html")
expected = ["[Window] Alert Text: Hello"]
self.do_perform_test(caplog, sample, expected)
def test_testText(self, caplog):
sample = os.path.join(self.misc_path, "testText.html")
expected = [
'<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>'
]
self.do_perform_test(caplog, sample, expected)
def test_testWindowOnload(self, caplog):
sample = os.path.join(self.misc_path, "testWindowOnload.html")
expected = ["[Window] Alert Text: Fired"]
self.do_perform_test(caplog, sample, expected)
def test_test_click(self, caplog):
sample = os.path.join(self.misc_path, "test_click.html")
expected = [
"[window open redirection] about:blank -> https://buffer.github.io/thug/"
]
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML1(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html")
expected = ['<div id="five">five</div><div id="one">one</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML2(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html")
expected = ['<div id="two"><div id="six">six</div>two</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML3(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html")
expected = ['<div id="three">three<div id="seven">seven</div></div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML4(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html")
expected = ['<div id="four">four</div><div id="eight">eight</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML5(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html")
expected = ["insertAdjacentHTML does not support notcorrect operation"]
self.do_perform_test(caplog, sample, expected)
def test_testCurrentScript(self, caplog):
sample = os.path.join(self.misc_path, "testCurrentScript.html")
expected = [
"[Window] Alert Text: This page has scripts",
"[Window] Alert Text: text/javascript",
"[Window] Alert Text: Just a useless script",
]
self.do_perform_test(caplog, sample, expected)
def test_testCCInterpreter(self, caplog):
sample = os.path.join(self.misc_path, "testCCInterpreter.html")
expected = [
"JavaScript version: 5.7",
"Running on the 32-bit version of Windows",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextNode(self, caplog):
sample = os.path.join(self.misc_path, "testTextNode.html")
expected = [
"nodeName: #text",
"nodeType: 3",
"Object: [object Text]",
"nodeValue: Hello World",
"Length: 11",
"Substring(2,5): llo W",
"New nodeValue (replace): HelloAWorld",
"New nodeValue (delete 1): HelloWorld",
"Index error (delete 2)",
"New nodeValue (delete 3): Hello",
"New nodeValue (append): Hello Test",
"Index error (insert 1)",
"New nodeValue (insert 2): Hello New Test",
"New nodeValue (reset): Reset",
]
self.do_perform_test(caplog, sample, expected)
def test_testCommentNode(self, caplog):
sample = os.path.join(self.misc_path, "testCommentNode.html")
expected = [
"nodeName: #comment",
"nodeType: 8",
"Object: [object Comment]",
"nodeValue: <!--Hello World-->",
"Length: 18",
"Substring(2,5): --Hel",
"New nodeValue (replace): <!--HAllo World-->",
"New nodeValue (delete 1): <!--Hllo World-->",
"Index error (delete 2)",
"New nodeValue (delete 3): <!--H",
"New nodeValue (append): <!--H Test",
"Index error (insert 1)",
"New nodeValue (insert 2): <!--H New Test",
"New nodeValue (reset): Reset",
]
self.do_perform_test(caplog, sample, expected)
def test_testDOMImplementation(self, caplog):
sample = os.path.join(self.misc_path, "testDOMImplementation.html")
expected = [
"hasFeature('core'): true",
]
self.do_perform_test(caplog, sample, expected)
def test_testAttrNode(self, caplog):
sample = os.path.join(self.misc_path, "testAttrNode.html")
expected = [
"Object: [object Attr]",
"nodeName: test",
"nodeType: 2",
"nodeValue: foo",
"Length: undefined",
"New nodeValue: test2",
"Parent: null",
"Owner: null",
"Name: test",
"Specified: true",
"childNodes length: 0",
]
self.do_perform_test(caplog, sample, expected)
def test_testReplaceChild(self, caplog):
sample = os.path.join(self.misc_path, "testReplaceChild.html")
expected = [
"firstChild: Old child",
"lastChild: Old child",
"innerText: Old child",
"[ERROR] Attempting to replace with a null element",
"[ERROR] Attempting to replace a null element",
"[ERROR] Attempting to replace with an invalid element",
"[ERROR] Attempting to replace an invalid element",
"[ERROR] Attempting to replace on a read-only element failed",
"Alert Text: New child",
'<div id="foobar"><!--Just a comment--></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testCookie(self, caplog):
sample = os.path.join(self.misc_path, "testCookie.html")
expected = ["favorite_food=tripe", "name=oeschger"]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment1(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment1.html")
expected = [
"<div><p>Test</p></div>",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment2(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment2.html")
expected = [
'<div id="foobar"><b>This is B</b></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentType(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentType.html")
expected = [
"Doctype: [object DocumentType]",
"Doctype name: html",
"Doctype nodeName: html",
"Doctype nodeType: 10",
"Doctype nodeValue: null",
"Doctype publicId: ",
"Doctype systemId: ",
"Doctype textContent: null",
]
self.do_perform_test(caplog, sample, expected)
def test_testRemoveChild(self, caplog):
sample = os.path.join(self.misc_path, "testRemoveChild.html")
expected = [
"<div>Don't care about me</div>",
"[ERROR] Attempting to remove null element",
"[ERROR] Attempting to remove an invalid element",
"[ERROR] Attempting to remove a read-only element",
"[ERROR] Attempting to remove an element not in the tree",
"[ERROR] Attempting to remove from a read-only element",
]
self.do_perform_test(caplog, sample, expected)
def test_testNamedNodeMap(self, caplog):
sample = os.path.join(self.misc_path, "testNamedNodeMap.html")
expected = [
"hasAttributes (before removal): true",
"hasAttribute('id'): true",
"First test: id->p1",
"Second test: id->p1",
"Third test: id->p1",
"Fourth test: id->p1",
"Fifth test failed",
"Not existing: null",
"hasAttributes (after removal): false",
"Sixth test: foo->bar",
"Seventh test: foo->bar2",
"Final attributes length: 1",
]
self.do_perform_test(caplog, sample, expected)
def test_testEntityReference(self, caplog):
sample = os.path.join(self.misc_path, "testEntityReference.html")
expected = [
"node: [object EntityReference]",
"name: &",
"nodeName: &",
"nodeType: 5",
"nodeValue: null",
]
self.do_perform_test(caplog, sample, expected)
def test_getElementsByTagName(self, caplog):
sample = os.path.join(self.misc_path, "testGetElementsByTagName.html")
expected = [
"[object HTMLHtmlElement]",
"[object HTMLHeadElement]",
"[object HTMLBodyElement]",
"[object HTMLParagraphElement]",
"[object HTMLScriptElement]",
]
self.do_perform_test(caplog, sample, expected)
def test_createElement(self, caplog):
sample = os.path.join(self.misc_path, "testCreateElement.html")
expected = ["[object HTMLParagraphElement]"]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentElement(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentElement.html")
expected = ['<a href="http://www.google.com">Google</a>']
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute1(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute1.html")
expected = ["Attribute: bar", "Attribute (after removal): null"]
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute3(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute3.html")
expected = [
"Alert Text: foo",
"Alert Text: bar",
"Alert Text: test",
"Alert Text: foobar",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLCollection(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLCollection.html")
expected = [
'<div id="odiv1">Page one</div>',
'<div name="odiv2">Page two</div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testApplyElement(self, caplog):
sample = os.path.join(self.misc_path, "testApplyElement.html")
expected = [
'<div id="outer"><div id="test"><div>Just a sample</div></div></div>',
'<div id="outer"><div>Just a div<div id="test"><div>Just a sample</div></div></div></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testWindow(self, caplog):
sample = os.path.join(self.misc_path, "testWindow.html")
expected = [
"window: [object Window]",
"self: [object Window]",
"top: [object Window]",
"length: 0",
"history: [object History]",
"pageXOffset: 0",
"pageYOffset: 0",
"screen: [object Screen]",
"screenLeft: 0",
"screenX: 0",
"confirm: true",
]
self.do_perform_test(caplog, sample, expected)
def test_testObject1(self, caplog):
sample = os.path.join(self.misc_path, "testObject1.html")
expected = [
"[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf"
]
self.do_perform_test(caplog, sample, expected)
def test_testReplaceChild2(self, caplog):
sample = os.path.join(self.misc_path, "testReplaceChild2.html")
expected = ['<div id="foobar"><div id="test"></div></div>']
self.do_perform_test(caplog, sample, expected)
def test_testNavigator(self, caplog):
sample = os.path.join(self.misc_path, "testNavigator.html")
expected = [
"window: [object Window]",
"appCodeName: Mozilla",
"appName: Microsoft Internet Explorer",
"appVersion: 4.0 (Windows; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)",
"cookieEnabled: true",
"onLine: true",
"platform: Win32",
]
self.do_perform_test(caplog, sample, expected)
def test_testAdodbStream(self, caplog):
sample = os.path.join(self.misc_path, "testAdodbStream.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Adodb.Stream)",
"[Window] Alert Text: Stream content: Test",
"[Window] Alert Text: Stream content (first 2 chars): Te",
"[Window] Alert Text: Stream size: 4",
"[Adodb.Stream ActiveX] SaveToFile(test.txt, 2)",
"[Adodb.Stream ActiveX] LoadFromFile(test1234.txt)",
"[Window] Alert Text: Attempting to load from a not existing file",
"[Adodb.Stream ActiveX] LoadFromFile(test.txt)",
"[Window] Alert Text: ReadText: Test",
"[Window] Alert Text: ReadText(3): Tes",
"[Window] Alert Text: ReadText(10): Test",
"[Adodb.Stream ActiveX] Changed position in fileobject to: (2)",
"[Window] Alert Text: stTest2",
"[Adodb.Stream ActiveX] Close",
]
self.do_perform_test(caplog, sample, expected)
def test_testScriptingFileSystemObject(self, caplog):
sample = os.path.join(self.misc_path, "testScriptingFileSystemObject.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS for GetSpecialFolder("0")',
'[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS\\system32 for GetSpecialFolder("1")',
'[WScript.Shell ActiveX] Expanding environment string "%TEMP%"',
"[Window] Alert Text: FolderExists('C:\\Windows\\System32'): true",
"[Window] Alert Text: FileExists(''): true",
"[Window] Alert Text: FileExists('C:\\Windows\\System32\\drivers\\etc\\hosts'): true",
"[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true",
'[Window] Alert Text: GetExtensionName("C:\\Windows\\System32\\test.txt"): .txt',
"[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true",
"[Window] Alert Text: [After CopyFile] FileExists('C:\\Windows\\System32\\test2.txt'): true",
"[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test2.txt'): false",
"[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test3.txt'): true",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLOptionsCollection(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html")
expected = [
"length: 4",
"item(0): Volvo",
"namedItem('audi'): Audi",
"namedItem('mercedes').value: mercedes",
"[After remove] item(0): Saab",
"[After first add] length: 4",
"[After first add] item(3): foobar",
"[After second add] length: 5",
"[After second add] item(3): test1234",
"Not found error",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextStream(self, caplog):
sample = os.path.join(self.misc_path, "testTextStream.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] CreateTextFile("test.txt", "False", "False")',
"[After first write] ReadAll: foobar",
"[After first write] Line: 1",
"[After first write] Column: 7",
"[After first write] AtEndOfLine: true",
"[After first write] AtEndOfStream: true",
"[After second write] Line: 2",
"[After second write] Column: 1",
"[After second write] AtEndOfLine: false",
"[After second write] AtEndOfStream: false",
"[After third write] Line: 5",
"[After third write] Column: 16",
"[After third write] AtEndOfLine: false",
"[After third write] AtEndOfStream: false",
"[After fourth write] Line: 6",
"[After fourth write] Column: 1",
"[After fourth write] AtEndOfLine: false",
"[After fourth write] AtEndOfStream: false",
"[After fourth write] First char: s",
"[After fourth write] Second char: o",
"[After fourth write] Third char: m",
"[After fourth write] Line: some other textnext line",
"[After skip] Read(5): ttest",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLAnchorElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html")
expected = [
"a.protocol: https:",
"a.host: www.example.com:1234",
"a.hostname: www.example.com",
"a.port: 1234",
"b.protocol: :",
"b.host: ",
"b.hostname: ",
"b.port: ",
"c.protocol: https:",
"c.host: www.example.com",
"c.hostname: www.example.com",
"c.port: ",
"e.pathname: /foo/index.html",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLTableElement3(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLTableElement3.html")
expected = [
"tHead: [object HTMLTableSectionElement]",
"tFoot: [object HTMLTableSectionElement]",
"caption: [object HTMLTableCaptionElement]",
"row: [object HTMLTableRowElement]",
"tBodies: [object HTMLCollection]",
"cell: [object HTMLTableCellElement]",
"cell.innerHTML: New cell 1",
"row.deleteCell(10) failed",
"row.deleteCell(20) failed",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextArea(self, caplog):
sample = os.path.join(self.misc_path, "testTextArea.html")
expected = ["type: textarea", "cols: 100", "rows: 25"]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLDocument(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLDocument.html")
expected = [
"document.title: Test",
"document.title: Foobar",
"anchors: [object HTMLCollection]",
"anchors length: 1",
"anchors[0].name: foobar",
"applets: [object HTMLCollection]",
"applets length: 2",
"applets[0].code: HelloWorld.class",
"links: [object HTMLCollection]",
"links length: 1",
"links[0].href: https://github.com/buffer/thug/",
"images: [object HTMLCollection]",
"images length: 1",
"images[0].href: test.jpg",
"disabled: false",
"head: [object HTMLHeadElement]",
"referrer: ",
"URL: about:blank",
"Alert Text: Hello, world",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLFormElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLFormElement.html")
expected = [
"[object HTMLFormElement]",
"f.elements: [object HTMLFormControlsCollection]",
"f.length: 4",
"f.name: [object HTMLFormControlsCollection]",
"f.acceptCharset: ",
"f.action: /cgi-bin/test",
"f.enctype: application/x-www-form-urlencoded",
"f.encoding: application/x-www-form-urlencoded",
"f.method: POST",
"f.target: ",
]
self.do_perform_test(caplog, sample, expected)
def test_testFile(self, caplog):
sample = os.path.join(self.misc_path, "testFile.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] GetFile("D:\\ Program Files\\ Common Files\\test.txt")',
"[File ActiveX] Path = D:\\ Program Files\\ Common Files\\test.txt, Attributes = 32",
"Drive (test.txt): D:",
"ShortPath (test.txt): D:\\\\ Progr~1\\\\ Commo~1\\\\test.txt",
"ShortName (test.txt): test.txt",
"Attributes: 1",
'[Scripting.FileSystemObject ActiveX] GetFile("test2.txt")',
"[File ActiveX] Path = test2.txt, Attributes = 32",
"Drive (test2.txt): C:",
"ShortPath (test2.txt): test2.txt",
"ShortName (test2.txt): test2.txt",
"Copy(test3.txt, True)",
"Move(test4.txt)",
"Delete(False)",
"OpenAsTextStream(ForReading, 0)",
]
self.do_perform_test(caplog, sample, expected)
def test_testWScriptNetwork(self, caplog):
sample = os.path.join(self.misc_path, "testWScriptNetwork.html")
expected = [
"[WScript.Network ActiveX] Got request to PrinterConnections",
"[WScript.Network ActiveX] Got request to EnumNetworkDrives",
'[WScript.Shell ActiveX] Expanding environment string "%USERDOMAIN%"',
'[WScript.Shell ActiveX] Expanding environment string "%USERNAME%"',
'[WScript.Shell ActiveX] Expanding environment string "%COMPUTERNAME%"',
]
self.do_perform_test(caplog, sample, expected)
def test_testApplet(self, caplog):
sample = os.path.join(self.misc_path, "testApplet.html")
expected = ["[applet redirection]"]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLImageElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLImageElement.html")
expected = [
"src (before changes): test.jpg",
"src (after first change): test2.jpg",
"onerror handler fired",
]
self.do_perform_test(caplog, sample, expected)
def test_testTitle(self, caplog):
sample = os.path.join(self.misc_path, "testTitle.html")
expected = ["New title: Foobar"]
self.do_perform_test(caplog, sample, expected)
def test_testCSSStyleDeclaration(self, caplog):
sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html")
expected = [
"style: [object CSSStyleDeclaration]",
"length: 1",
"cssText: color: blue;",
"color: blue",
"item(0): color",
"item(100):",
"getPropertyValue('color'): blue",
"length (after removeProperty): 0",
"cssText: foo: bar;",
]
self.do_perform_test(caplog, sample, expected)
def test_testFormProperty(self, caplog):
sample = os.path.join(self.misc_path, "testFormProperty.html")
expected = ["[object HTMLFormElement]", "formA"]
self.do_perform_test(caplog, sample, expected)
def test_testVBScript(self, caplog):
sample = os.path.join(self.misc_path, "testVBScript.html")
expected = ["[VBS embedded URL redirection]", "http://192.168.1.100/putty.exe"]
self.do_perform_test(caplog, sample, expected)
def test_testFontFaceRule1(self, caplog):
sample = os.path.join(self.misc_path, "testFontFaceRule1.html")
expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"]
self.do_perform_test(caplog, sample, expected)
def test_testFontFaceRule2(self, caplog):
sample = os.path.join(self.misc_path, "testFontFaceRule2.html")
expected = [
"[font face redirection]",
"https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf",
]
self.do_perform_test(caplog, sample, expected)
def test_testSilverLight(self, caplog):
sample = os.path.join(self.misc_path, "testSilverLight.html")
expected = [
"[SilverLight] isVersionSupported('4.0')",
"Version 4.0 supported: true",
]
self.do_perform_test(caplog, sample, expected)
def test_testMSXML2Document(self, caplog):
sample = os.path.join(self.misc_path, "testMSXML2Document.html")
expected = [
"[MSXML2.DOMDocument] Microsoft XML Core Services MSXML Uninitialized Memory Corruption",
"CVE-2012-1889",
]
self.do_perform_test(caplog, sample, expected)
| 32,341
|
Python
|
.py
| 686
| 36.610787
| 153
| 0.598401
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,698
|
test_misc_ie110.py
|
buffer_thug/tests/functional/test_misc_ie110.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestMiscSamplesIE(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
misc_path = os.path.join(cwd_path, os.pardir, "samples/misc")
def do_perform_test(self, caplog, sample, expected):
thug = ThugAPI()
thug.set_useragent("win10ie110")
thug.set_events("click,storage")
thug.set_connect_timeout(2)
thug.disable_cert_logging()
thug.set_features_logging()
thug.set_file_logging()
thug.set_ssl_verify()
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_plugindetect1(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"]
self.do_perform_test(caplog, sample, expected)
def test_plugindetect2(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html")
expected = [
"AdobeReader version: 9,1,0,0",
"Flash version: 10,0,64,0",
"Java version: 1,6,0,32",
"ActiveXObject: javawebstart.isinstalled.1.6.0.0",
"ActiveXObject: javaplugin.160_32",
]
self.do_perform_test(caplog, sample, expected)
def test_test1(self, caplog):
sample = os.path.join(self.misc_path, "test1.html")
expected = ["[Window] Alert Text: one"]
self.do_perform_test(caplog, sample, expected)
def test_test2(self, caplog):
sample = os.path.join(self.misc_path, "test2.html")
expected = ["[Window] Alert Text: Java enabled: true"]
self.do_perform_test(caplog, sample, expected)
def test_test3(self, caplog):
sample = os.path.join(self.misc_path, "test3.html")
expected = ["[Window] Alert Text: foo"]
self.do_perform_test(caplog, sample, expected)
def test_testAppendChild(self, caplog):
sample = os.path.join(self.misc_path, "testAppendChild.html")
expected = [
"Don't care about me",
"Just a sample",
"Attempt to append a null element failed",
"Attempt to append an invalid element failed",
"Attempt to append a text element failed",
"Attempt to append a read-only element failed",
]
self.do_perform_test(caplog, sample, expected)
def test_testClipboardData(self, caplog):
sample = os.path.join(self.misc_path, "testClipboardData.html")
expected = ["Test ClipboardData"]
self.do_perform_test(caplog, sample, expected)
def test_testCloneNode(self, caplog):
sample = os.path.join(self.misc_path, "testCloneNode.html")
expected = [
'<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>'
]
self.do_perform_test(caplog, sample, expected)
def test_testCloneNode2(self, caplog):
sample = os.path.join(self.misc_path, "testCloneNode2.html")
expected = [
"[Window] Alert Text: [object HTMLButtonElement]",
"[Window] Alert Text: Clone node",
"[Window] Alert Text: None",
"[Window] Alert Text: [object Attr]",
"[Window] Alert Text: True",
]
self.do_perform_test(caplog, sample, expected)
def test_testCreateHTMLDocument(self, caplog):
sample = os.path.join(self.misc_path, "testCreateHTMLDocument.html")
expected = [
"[object HTMLDocument]",
"[object HTMLBodyElement]",
"<p>This is a new paragraph.</p>",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentWrite1(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentWrite1.html")
expected = [
"Foobar",
"Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>",
]
self.do_perform_test(caplog, sample, expected)
def test_testExternalSidebar(self, caplog):
sample = os.path.join(self.misc_path, "testExternalSidebar.html")
expected = ["[Window] Alert Text: Internet Explorer >= 7.0 or Chrome"]
self.do_perform_test(caplog, sample, expected)
def test_testGetElementsByClassName(self, caplog):
sample = os.path.join(self.misc_path, "testGetElementsByClassName.html")
expected = ["First", "Hello World!", "Second"]
self.do_perform_test(caplog, sample, expected)
def test_testInnerHTML(self, caplog):
sample = os.path.join(self.misc_path, "testInnerHTML.html")
expected = ["dude", "Fred Flinstone"]
self.do_perform_test(caplog, sample, expected)
def test_testInsertBefore(self, caplog):
sample = os.path.join(self.misc_path, "testInsertBefore.html")
expected = [
"<div>Just a sample</div><div>I'm your reference!</div></body></html>",
"[ERROR] Attempting to insert null element",
"[ERROR] Attempting to insert an invalid element",
"[ERROR] Attempting to insert using an invalid reference element",
"[ERROR] Attempting to insert a text node using an invalid reference element",
]
self.do_perform_test(caplog, sample, expected)
def test_testLocalStorage(self, caplog):
sample = os.path.join(self.misc_path, "testLocalStorage.html")
expected = ["Alert Text: Fired", "Alert Text: bar", "Alert Text: south"]
self.do_perform_test(caplog, sample, expected)
def test_testPlugins(self, caplog):
sample = os.path.join(self.misc_path, "testPlugins.html")
expected = [
"Shockwave Flash 10.0.64.0",
"Windows Media Player 7",
"Adobe Acrobat",
]
self.do_perform_test(caplog, sample, expected)
def test_testMetaXUACompatibleEmulateIE(self, caplog):
sample = os.path.join(self.misc_path, "testMetaXUACompatibleEmulateIE.html")
expected = ["[Window] Alert Text: 8"]
self.do_perform_test(caplog, sample, expected)
def test_testNode(self, caplog):
sample = os.path.join(self.misc_path, "testNode.html")
expected = ["thelink", "thediv"]
self.do_perform_test(caplog, sample, expected)
def test_testNode2(self, caplog):
sample = os.path.join(self.misc_path, "testNode2.html")
expected = ["thelink", "thediv2"]
self.do_perform_test(caplog, sample, expected)
def test_testQuerySelector(self, caplog):
sample = os.path.join(self.misc_path, "testQuerySelector.html")
expected = ["Alert Text: Have a Good life.", "CoursesWeb.net"]
self.do_perform_test(caplog, sample, expected)
def test_testQuerySelector2(self, caplog):
sample = os.path.join(self.misc_path, "testQuerySelector2.html")
expected = ["CoursesWeb.net", "MarPlo.net", "php.net"]
self.do_perform_test(caplog, sample, expected)
def test_testScope(self, caplog):
sample = os.path.join(self.misc_path, "testScope.html")
expected = [
"foobar",
"foo",
"bar",
"True",
"3",
"2012-10-07 11:13:00",
"3.14159265359",
"/foo/i",
]
self.do_perform_test(caplog, sample, expected)
def test_testSessionStorage(self, caplog):
sample = os.path.join(self.misc_path, "testSessionStorage.html")
expected = ["key1", "key2", "value1", "value3"]
self.do_perform_test(caplog, sample, expected)
def test_testSetInterval(self, caplog):
sample = os.path.join(self.misc_path, "testSetInterval.html")
expected = ["[Window] Alert Text: Hello"]
self.do_perform_test(caplog, sample, expected)
def test_testText(self, caplog):
sample = os.path.join(self.misc_path, "testText.html")
expected = [
'<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>'
]
self.do_perform_test(caplog, sample, expected)
def test_testWindowOnload(self, caplog):
sample = os.path.join(self.misc_path, "testWindowOnload.html")
expected = ["[Window] Alert Text: Fired"]
self.do_perform_test(caplog, sample, expected)
def test_test_click(self, caplog):
sample = os.path.join(self.misc_path, "test_click.html")
expected = [
"[window open redirection] about:blank -> https://buffer.github.io/thug/"
]
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML1(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html")
expected = ['<div id="five">five</div><div id="one">one</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML2(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html")
expected = ['<div id="two"><div id="six">six</div>two</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML3(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html")
expected = ['<div id="three">three<div id="seven">seven</div></div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML4(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html")
expected = ['<div id="four">four</div><div id="eight">eight</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML5(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html")
expected = ["insertAdjacentHTML does not support notcorrect operation"]
self.do_perform_test(caplog, sample, expected)
def test_testCurrentScript(self, caplog):
sample = os.path.join(self.misc_path, "testCurrentScript.html")
expected = [
"[Window] Alert Text: This page has scripts",
"[Window] Alert Text: text/javascript",
"[Window] Alert Text: Just a useless script",
]
self.do_perform_test(caplog, sample, expected)
def test_testCCInterpreter(self, caplog):
sample = os.path.join(self.misc_path, "testCCInterpreter.html")
expected = [
"JavaScript version: 11",
"Running on the 32-bit version of Windows",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextNode(self, caplog):
sample = os.path.join(self.misc_path, "testTextNode.html")
expected = [
"nodeName: #text",
"nodeType: 3",
"Object: [object Text]",
"nodeValue: Hello World",
"Length: 11",
"Substring(2,5): llo W",
"New nodeValue (replace): HelloAWorld",
"New nodeValue (delete 1): HelloWorld",
"Index error (delete 2)",
"New nodeValue (delete 3): Hello",
"New nodeValue (append): Hello Test",
"Index error (insert 1)",
"New nodeValue (insert 2): Hello New Test",
"New nodeValue (reset): Reset",
]
self.do_perform_test(caplog, sample, expected)
def test_testCommentNode(self, caplog):
sample = os.path.join(self.misc_path, "testCommentNode.html")
expected = [
"nodeName: #comment",
"nodeType: 8",
"Object: [object Comment]",
"nodeValue: <!--Hello World-->",
"Length: 18",
"Substring(2,5): --Hel",
"New nodeValue (replace): <!--HAllo World-->",
"New nodeValue (delete 1): <!--Hllo World-->",
"Index error (delete 2)",
"New nodeValue (delete 3): <!--H",
"New nodeValue (append): <!--H Test",
"Index error (insert 1)",
"New nodeValue (insert 2): <!--H New Test",
"New nodeValue (reset): Reset",
]
self.do_perform_test(caplog, sample, expected)
def test_testDOMImplementation(self, caplog):
sample = os.path.join(self.misc_path, "testDOMImplementation.html")
expected = [
"hasFeature('core'): true",
]
self.do_perform_test(caplog, sample, expected)
def test_testAttrNode(self, caplog):
sample = os.path.join(self.misc_path, "testAttrNode.html")
expected = [
"Object: [object Attr]",
"nodeName: test",
"nodeType: 2",
"nodeValue: foo",
"Length: undefined",
"New nodeValue: test2",
"Parent: null",
"Owner: null",
"Name: test",
"Specified: true",
"childNodes length: 0",
]
self.do_perform_test(caplog, sample, expected)
def test_testReplaceChild(self, caplog):
sample = os.path.join(self.misc_path, "testReplaceChild.html")
expected = [
"firstChild: Old child",
"lastChild: Old child",
"[innerText: Old child",
"ERROR] Attempting to replace with a null element",
"[ERROR] Attempting to replace a null element",
"[ERROR] Attempting to replace with an invalid element",
"[ERROR] Attempting to replace an invalid element",
"[ERROR] Attempting to replace on a read-only element failed",
"Alert Text: New child",
'<div id="foobar"><!--Just a comment--></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testCookie(self, caplog):
sample = os.path.join(self.misc_path, "testCookie.html")
expected = ["favorite_food=tripe", "name=oeschger"]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment1(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment1.html")
expected = [
"<div><p>Test</p></div>",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment2(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment2.html")
expected = [
'<div id="foobar"><b>This is B</b></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment3(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment3.html")
expected = [
"foo:bar",
]
self.do_perform_test(caplog, sample, expected)
def test_testClassList1(self, caplog):
sample = os.path.join(self.misc_path, "testClassList1.html")
expected = [
'[Initial value] <div class="foo"></div>',
'[After remove and add] <div class="anotherclass"></div>',
"[Item] anotherclass",
"[Empty item] null",
"[Toggle visible] true",
'[After toggle] <div class="anotherclass"></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testClassList4(self, caplog):
sample = os.path.join(self.misc_path, "testClassList4.html")
expected = [
'[After remove and add] <div class="anotherclass"></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentType(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentType.html")
expected = [
"Doctype: [object DocumentType]",
"Doctype name: html",
"Doctype nodeName: html",
"Doctype nodeType: 10",
"Doctype nodeValue: null",
"Doctype publicId: ",
"Doctype systemId: ",
"Doctype textContent: null",
]
self.do_perform_test(caplog, sample, expected)
def test_testRemoveChild(self, caplog):
sample = os.path.join(self.misc_path, "testRemoveChild.html")
expected = [
"<div>Don't care about me</div>",
"[ERROR] Attempting to remove null element",
"[ERROR] Attempting to remove an invalid element",
"[ERROR] Attempting to remove a read-only element",
"[ERROR] Attempting to remove an element not in the tree",
"[ERROR] Attempting to remove from a read-only element",
]
self.do_perform_test(caplog, sample, expected)
def test_testNamedNodeMap(self, caplog):
sample = os.path.join(self.misc_path, "testNamedNodeMap.html")
expected = [
"hasAttributes (before removal): true",
"hasAttribute('id'): true",
"First test: id->p1",
"Second test: id->p1",
"Third test: id->p1",
"Fourth test: id->p1",
"Fifth test failed",
"Not existing: null",
"hasAttributes (after removal): false",
"Sixth test: foo->bar",
"Seventh test: foo->bar2",
"Final attributes length: 1",
]
self.do_perform_test(caplog, sample, expected)
def test_testEntityReference(self, caplog):
sample = os.path.join(self.misc_path, "testEntityReference.html")
expected = [
"node: [object EntityReference]",
"name: &",
"nodeName: &",
"nodeType: 5",
"nodeValue: null",
]
self.do_perform_test(caplog, sample, expected)
def test_getElementsByTagName(self, caplog):
sample = os.path.join(self.misc_path, "testGetElementsByTagName.html")
expected = [
"[object HTMLHtmlElement]",
"[object HTMLHeadElement]",
"[object HTMLBodyElement]",
"[object HTMLParagraphElement]",
"[object HTMLScriptElement]",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentElement(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentElement.html")
expected = ['<a href="http://www.google.com">Google</a>']
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute1(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute1.html")
expected = ["Attribute: bar", "Attribute (after removal): null"]
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute3(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute3.html")
expected = [
"Alert Text: foo",
"Alert Text: bar",
"Alert Text: test",
"Alert Text: foobar",
]
self.do_perform_test(caplog, sample, expected)
def test_testCDATASection(self, caplog):
sample = os.path.join(self.misc_path, "testCDATASection.html")
expected = [
"nodeName: #cdata-section",
"nodeType: 4",
"<xml><![CDATA[Some <CDATA> data & then some]]></xml>",
]
self.do_perform_test(caplog, sample, expected)
def test_testApplyElement(self, caplog):
sample = os.path.join(self.misc_path, "testApplyElement.html")
expected = [
'<div id="outer"><div id="test"><div>Just a sample</div></div></div>',
'<div id="outer"><div>Just a div<div id="test"><div>Just a sample</div></div></div></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testProcessingInstruction(self, caplog):
sample = os.path.join(self.misc_path, "testProcessingInstruction.html")
expected = [
"[object ProcessingInstruction]",
"nodeName: xml-stylesheet",
"nodeType: 7",
'nodeValue: href="mycss.css" type="text/css"',
"target: xml-stylesheet",
]
self.do_perform_test(caplog, sample, expected)
def test_testWindow(self, caplog):
sample = os.path.join(self.misc_path, "testWindow.html")
expected = [
"window: [object Window]",
"self: [object Window]",
"top: [object Window]",
"length: 0",
"history: [object History]",
"pageXOffset: 0",
"pageYOffset: 0",
"screen: [object Screen]",
"screenLeft: 0",
"screenX: 0",
"confirm: true",
]
self.do_perform_test(caplog, sample, expected)
def test_testObject1(self, caplog):
sample = os.path.join(self.misc_path, "testObject1.html")
expected = [
"[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf"
]
self.do_perform_test(caplog, sample, expected)
def test_testReplaceChild2(self, caplog):
sample = os.path.join(self.misc_path, "testReplaceChild2.html")
expected = ['<div id="foobar"><div id="test"></div></div>']
self.do_perform_test(caplog, sample, expected)
def test_testNavigator(self, caplog):
sample = os.path.join(self.misc_path, "testNavigator.html")
expected = [
"window: [object Window]",
"appCodeName: Mozilla",
"appName: Netscape",
"appVersion: 5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko",
"cookieEnabled: true",
"onLine: true",
"platform: Win32",
]
self.do_perform_test(caplog, sample, expected)
def test_testAdodbStream(self, caplog):
sample = os.path.join(self.misc_path, "testAdodbStream.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Adodb.Stream)",
"[Window] Alert Text: Stream content: Test",
"[Window] Alert Text: Stream content (first 2 chars): Te",
"[Window] Alert Text: Stream size: 4",
"[Adodb.Stream ActiveX] SaveToFile(test.txt, 2)",
"[Adodb.Stream ActiveX] LoadFromFile(test1234.txt)",
"[Window] Alert Text: Attempting to load from a not existing file",
"[Adodb.Stream ActiveX] LoadFromFile(test.txt)",
"[Window] Alert Text: ReadText: Test",
"[Window] Alert Text: ReadText(3): Tes",
"[Window] Alert Text: ReadText(10): Test",
"[Adodb.Stream ActiveX] Changed position in fileobject to: (2)",
"[Window] Alert Text: stTest2",
"[Adodb.Stream ActiveX] Close",
]
self.do_perform_test(caplog, sample, expected)
def test_testScriptingFileSystemObject(self, caplog):
sample = os.path.join(self.misc_path, "testScriptingFileSystemObject.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS for GetSpecialFolder("0")',
'[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS\\system32 for GetSpecialFolder("1")',
'[WScript.Shell ActiveX] Expanding environment string "%TEMP%"',
"[Window] Alert Text: FolderExists('C:\\Windows\\System32'): true",
"[Window] Alert Text: FileExists(''): true",
"[Window] Alert Text: FileExists('C:\\Windows\\System32\\drivers\\etc\\hosts'): true",
"[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true",
'[Window] Alert Text: GetExtensionName("C:\\Windows\\System32\\test.txt"): .txt',
"[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true",
"[Window] Alert Text: [After CopyFile] FileExists('C:\\Windows\\System32\\test2.txt'): true",
"[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test2.txt'): false",
"[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test3.txt'): true",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLOptionsCollection(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html")
expected = [
"length: 4",
"item(0): Volvo",
"namedItem('audi'): Audi",
"namedItem('mercedes').value: mercedes",
"[After remove] item(0): Saab",
"[After first add] length: 4",
"[After first add] item(3): foobar",
"[After second add] length: 5",
"[After second add] item(3): test1234",
"Not found error",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextStream(self, caplog):
sample = os.path.join(self.misc_path, "testTextStream.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] CreateTextFile("test.txt", "False", "False")',
"[After first write] ReadAll: foobar",
"[After first write] Line: 1",
"[After first write] Column: 7",
"[After first write] AtEndOfLine: true",
"[After first write] AtEndOfStream: true",
"[After second write] Line: 2",
"[After second write] Column: 1",
"[After second write] AtEndOfLine: false",
"[After second write] AtEndOfStream: false",
"[After third write] Line: 5",
"[After third write] Column: 16",
"[After third write] AtEndOfLine: false",
"[After third write] AtEndOfStream: false",
"[After fourth write] Line: 6",
"[After fourth write] Column: 1",
"[After fourth write] AtEndOfLine: false",
"[After fourth write] AtEndOfStream: false",
"[After fourth write] First char: s",
"[After fourth write] Second char: o",
"[After fourth write] Third char: m",
"[After fourth write] Line: some other textnext line",
"[After skip] Read(5): ttest",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLAnchorElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html")
expected = [
"a.protocol: https:",
"a.host: www.example.com:1234",
"a.hostname: www.example.com",
"a.port: 1234",
"b.protocol: :",
"b.host: ",
"b.hostname: ",
"b.port: ",
"c.protocol: https:",
"c.host: www.example.com",
"c.hostname: www.example.com",
"c.port: ",
"e.pathname: /foo/index.html",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLTableElement3(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLTableElement3.html")
expected = [
"tHead: [object HTMLTableSectionElement]",
"tFoot: [object HTMLTableSectionElement]",
"caption: [object HTMLTableCaptionElement]",
"row: [object HTMLTableRowElement]",
"tBodies: [object HTMLCollection]",
"cell: [object HTMLTableCellElement]",
"cell.innerHTML: New cell 1",
"row.deleteCell(10) failed",
"row.deleteCell(20) failed",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextArea(self, caplog):
sample = os.path.join(self.misc_path, "testTextArea.html")
expected = ["type: textarea", "cols: 100", "rows: 25"]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLDocument(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLDocument.html")
expected = [
"document.title: Test",
"document.title: Foobar",
"anchors: [object HTMLCollection]",
"anchors length: 1",
"anchors[0].name: foobar",
"applets: [object HTMLCollection]",
"applets length: 2",
"applets[0].code: HelloWorld.class",
"links: [object HTMLCollection]",
"links length: 1",
"links[0].href: https://github.com/buffer/thug/",
"images: [object HTMLCollection]",
"images length: 1",
"images[0].href: test.jpg",
"disabled: false",
"head: [object HTMLHeadElement]",
"referrer: ",
"URL: about:blank",
"Alert Text: Hello, world",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLFormElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLFormElement.html")
expected = [
"[object HTMLFormElement]",
"f.elements: [object HTMLFormControlsCollection]",
"f.length: 4",
"f.name: [object HTMLFormControlsCollection]",
"f.acceptCharset: ",
"f.action: /cgi-bin/test",
"f.enctype: application/x-www-form-urlencoded",
"f.encoding: application/x-www-form-urlencoded",
"f.method: POST",
"f.target: ",
]
self.do_perform_test(caplog, sample, expected)
def test_testFile(self, caplog):
sample = os.path.join(self.misc_path, "testFile.html")
expected = [
"[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)",
'[Scripting.FileSystemObject ActiveX] GetFile("D:\\ Program Files\\ Common Files\\test.txt")',
"[File ActiveX] Path = D:\\ Program Files\\ Common Files\\test.txt, Attributes = 32",
"Drive (test.txt): D:",
"ShortPath (test.txt): D:\\\\ Progr~1\\\\ Commo~1\\\\test.txt",
"ShortName (test.txt): test.txt",
"Attributes: 1",
'[Scripting.FileSystemObject ActiveX] GetFile("test2.txt")',
"[File ActiveX] Path = test2.txt, Attributes = 32",
"Drive (test2.txt): C:",
"ShortPath (test2.txt): test2.txt",
"ShortName (test2.txt): test2.txt",
"Copy(test3.txt, True)",
"Move(test4.txt)",
"Delete(False)",
"OpenAsTextStream(ForReading, 0)",
]
self.do_perform_test(caplog, sample, expected)
def test_testWScriptNetwork(self, caplog):
sample = os.path.join(self.misc_path, "testWScriptNetwork.html")
expected = [
"[WScript.Network ActiveX] Got request to PrinterConnections",
"[WScript.Network ActiveX] Got request to EnumNetworkDrives",
'[WScript.Shell ActiveX] Expanding environment string "%USERDOMAIN%"',
'[WScript.Shell ActiveX] Expanding environment string "%USERNAME%"',
'[WScript.Shell ActiveX] Expanding environment string "%COMPUTERNAME%"',
]
self.do_perform_test(caplog, sample, expected)
def test_testApplet(self, caplog):
sample = os.path.join(self.misc_path, "testApplet.html")
expected = ["[applet redirection]"]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLImageElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLImageElement.html")
expected = [
"src (before changes): test.jpg",
"src (after first change): test2.jpg",
"onerror handler fired",
]
self.do_perform_test(caplog, sample, expected)
def test_testTitle(self, caplog):
sample = os.path.join(self.misc_path, "testTitle.html")
expected = ["New title: Foobar"]
self.do_perform_test(caplog, sample, expected)
def test_testCSSStyleDeclaration(self, caplog):
sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html")
expected = [
"style: [object CSSStyleDeclaration]",
"length: 1",
"cssText: color: blue;",
"color: blue",
"item(0): color",
"item(100):",
"getPropertyValue('color'): blue",
"length (after removeProperty): 0",
"cssText: foo: bar;",
]
self.do_perform_test(caplog, sample, expected)
def test_testFormProperty(self, caplog):
sample = os.path.join(self.misc_path, "testFormProperty.html")
expected = ["[object HTMLFormElement]", "formA"]
self.do_perform_test(caplog, sample, expected)
def test_testVBScript(self, caplog):
sample = os.path.join(self.misc_path, "testVBScript.html")
expected = ["[VBS embedded URL redirection]", "http://192.168.1.100/putty.exe"]
self.do_perform_test(caplog, sample, expected)
def test_testFontFaceRule1(self, caplog):
sample = os.path.join(self.misc_path, "testFontFaceRule1.html")
expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"]
self.do_perform_test(caplog, sample, expected)
def test_testFontFaceRule2(self, caplog):
sample = os.path.join(self.misc_path, "testFontFaceRule2.html")
expected = [
"[font face redirection]",
"https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf",
]
self.do_perform_test(caplog, sample, expected)
def test_testSilverLight(self, caplog):
sample = os.path.join(self.misc_path, "testSilverLight.html")
expected = [
"[SilverLight] isVersionSupported('4.0')",
"Version 4.0 supported: true",
]
self.do_perform_test(caplog, sample, expected)
def test_testMSXML2Document(self, caplog):
sample = os.path.join(self.misc_path, "testMSXML2Document.html")
expected = [
"[MSXML2.DOMDocument] Microsoft XML Core Services MSXML Uninitialized Memory Corruption",
"CVE-2012-1889",
]
self.do_perform_test(caplog, sample, expected)
def test_testConsole(self, caplog):
sample = os.path.join(self.misc_path, "testConsole.html")
expected = [
"[object Console]",
"[Console] assert(True, 'Test assert')",
"[Console] count() = 1",
"[Console] count('foobar') = 1",
"[Console] count('foobar') = 2",
"[Console] error('Test error')",
"[Console] log('Hello world!')",
"[Console] group()",
"[Console] log('Hello again, this time inside a group!')",
"[Console] groupEnd()",
"[Console] groupCollapsed()",
"[Console] info('Hello again')",
"[Console] warn('Hello again')",
]
self.do_perform_test(caplog, sample, expected)
| 35,212
|
Python
|
.py
| 746
| 36.674263
| 180
| 0.597249
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,699
|
test_misc_firefox.py
|
buffer_thug/tests/functional/test_misc_firefox.py
|
import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestMiscSamplesFirefox(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
misc_path = os.path.join(cwd_path, os.pardir, "samples/misc")
def do_perform_test(self, caplog, sample, expected, useragent="linuxfirefox40"):
thug = ThugAPI()
thug.set_useragent(useragent)
thug.set_events("click,storage")
thug.set_connect_timeout(2)
thug.set_delay(500)
thug.disable_cert_logging()
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(sample)
thug.run_local(sample)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def test_plugindetect1(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html")
expected = [
"Flash version: 10.0.64.0",
]
self.do_perform_test(caplog, sample, expected)
def test_plugindetect2(self, caplog):
sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html")
expected = ["Flash version: 10,0,64,0", "Java version: 1,6,0,32"]
self.do_perform_test(caplog, sample, expected)
def test_test1(self, caplog):
sample = os.path.join(self.misc_path, "test1.html")
expected = ["[Window] Alert Text: one"]
self.do_perform_test(caplog, sample, expected)
def test_test2(self, caplog):
sample = os.path.join(self.misc_path, "test2.html")
expected = ["[Window] Alert Text: Java enabled: true"]
self.do_perform_test(caplog, sample, expected)
def test_test3(self, caplog):
sample = os.path.join(self.misc_path, "test3.html")
expected = ["[Window] Alert Text: foo"]
self.do_perform_test(caplog, sample, expected)
def test_test5(self, caplog):
sample = os.path.join(self.misc_path, "test5.html")
expected = []
self.do_perform_test(caplog, sample, expected, "win7firefox3")
def test_testAppendChild(self, caplog):
sample = os.path.join(self.misc_path, "testAppendChild.html")
expected = [
"Don't care about me",
"Just a sample",
"Attempt to append a null element failed",
"Attempt to append an invalid element failed",
"Attempt to append a text element failed",
"Attempt to append a read-only element failed",
]
self.do_perform_test(caplog, sample, expected)
def test_testCloneNode(self, caplog):
sample = os.path.join(self.misc_path, "testCloneNode.html")
expected = [
'<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>'
]
self.do_perform_test(caplog, sample, expected)
def test_testCloneNode2(self, caplog):
sample = os.path.join(self.misc_path, "testCloneNode2.html")
expected = [
"[Window] Alert Text: [object HTMLButtonElement]",
"[Window] Alert Text: Clone node",
"[Window] Alert Text: None",
"[Window] Alert Text: [object Attr]",
"[Window] Alert Text: True",
]
self.do_perform_test(caplog, sample, expected)
def test_testCreateHTMLDocument(self, caplog):
sample = os.path.join(self.misc_path, "testCreateHTMLDocument.html")
expected = [
"[object HTMLDocument]",
"[object HTMLBodyElement]",
"<p>This is a new paragraph.</p>",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentWrite1(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentWrite1.html")
expected = [
"Foobar",
"Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>",
]
self.do_perform_test(caplog, sample, expected)
def test_testExternalSidebar(self, caplog):
sample = os.path.join(self.misc_path, "testExternalSidebar.html")
expected = ["[Window] Alert Text: Firefox"]
self.do_perform_test(caplog, sample, expected)
def test_testGetElementsByClassName(self, caplog):
sample = os.path.join(self.misc_path, "testGetElementsByClassName.html")
expected = ["First", "Hello World!", "Second"]
self.do_perform_test(caplog, sample, expected)
def test_testInnerHTML(self, caplog):
sample = os.path.join(self.misc_path, "testInnerHTML.html")
expected = ["dude", "Fred Flinstone"]
self.do_perform_test(caplog, sample, expected)
def test_testInsertBefore(self, caplog):
sample = os.path.join(self.misc_path, "testInsertBefore.html")
expected = [
"<div>Just a sample</div><div>I'm your reference!</div></body></html>",
"[ERROR] Attempting to insert null element",
"[ERROR] Attempting to insert an invalid element",
"[ERROR] Attempting to insert using an invalid reference element",
"[ERROR] Attempting to insert a text node using an invalid reference element",
]
self.do_perform_test(caplog, sample, expected)
def test_testLocalStorage(self, caplog):
sample = os.path.join(self.misc_path, "testLocalStorage.html")
expected = ["Alert Text: Fired", "Alert Text: bar", "Alert Text: south"]
self.do_perform_test(caplog, sample, expected)
def test_testPlugins(self, caplog):
sample = os.path.join(self.misc_path, "testPlugins.html")
expected = [
"Shockwave Flash 10.0.64.0",
"Windows Media Player 7",
"Adobe Acrobat",
]
self.do_perform_test(caplog, sample, expected)
def test_testNode(self, caplog):
sample = os.path.join(self.misc_path, "testNode.html")
expected = ["thelink", "thediv"]
self.do_perform_test(caplog, sample, expected)
def test_testNode2(self, caplog):
sample = os.path.join(self.misc_path, "testNode2.html")
expected = ["thelink", "thediv2"]
self.do_perform_test(caplog, sample, expected)
def test_testQuerySelector(self, caplog):
sample = os.path.join(self.misc_path, "testQuerySelector.html")
expected = ["Alert Text: Have a Good life.", "CoursesWeb.net"]
self.do_perform_test(caplog, sample, expected)
def test_testQuerySelector2(self, caplog):
sample = os.path.join(self.misc_path, "testQuerySelector2.html")
expected = ["CoursesWeb.net", "MarPlo.net", "php.net"]
self.do_perform_test(caplog, sample, expected)
def test_testScope(self, caplog):
sample = os.path.join(self.misc_path, "testScope.html")
expected = [
"foobar",
"foo",
"bar",
"True",
"3",
"2012-10-07 11:13:00",
"3.14159265359",
"/foo/i",
]
self.do_perform_test(caplog, sample, expected)
def test_testSessionStorage(self, caplog):
sample = os.path.join(self.misc_path, "testSessionStorage.html")
expected = ["key1", "key2", "value1", "value3"]
self.do_perform_test(caplog, sample, expected)
def test_testSetInterval(self, caplog):
sample = os.path.join(self.misc_path, "testSetInterval.html")
expected = ["[Window] Alert Text: Hello"]
self.do_perform_test(caplog, sample, expected)
def test_testText(self, caplog):
sample = os.path.join(self.misc_path, "testText.html")
expected = [
'<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>'
]
self.do_perform_test(caplog, sample, expected)
def test_testWindowOnload(self, caplog):
sample = os.path.join(self.misc_path, "testWindowOnload.html")
expected = ["[Window] Alert Text: Fired"]
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML1(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html")
expected = ['<div id="five">five</div><div id="one">one</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML2(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html")
expected = ['<div id="two"><div id="six">six</div>two</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML3(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html")
expected = ['<div id="three">three<div id="seven">seven</div></div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML4(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html")
expected = ['<div id="four">four</div><div id="eight">eight</div>']
self.do_perform_test(caplog, sample, expected)
def test_testInsertAdjacentHTML5(self, caplog):
sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html")
expected = ["insertAdjacentHTML does not support notcorrect operation"]
self.do_perform_test(caplog, sample, expected)
def test_testCurrentScript(self, caplog):
sample = os.path.join(self.misc_path, "testCurrentScript.html")
expected = [
"[Window] Alert Text: This page has scripts",
"[Window] Alert Text: text/javascript",
"[Window] Alert Text: Just a useless script",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextNode(self, caplog):
sample = os.path.join(self.misc_path, "testTextNode.html")
expected = [
"nodeName: #text",
"nodeType: 3",
"Object: [object Text]",
"nodeValue: Hello World",
"Length: 11",
"Substring(2,5): llo W",
"New nodeValue (replace): HelloAWorld",
"New nodeValue (delete 1): HelloWorld",
"Index error (delete 2)",
"New nodeValue (delete 3): Hello",
"New nodeValue (append): Hello Test",
"Index error (insert 1)",
"New nodeValue (insert 2): Hello New Test",
"New nodeValue (reset): Reset",
]
self.do_perform_test(caplog, sample, expected)
def test_testCommentNode(self, caplog):
sample = os.path.join(self.misc_path, "testCommentNode.html")
expected = [
"nodeName: #comment",
"nodeType: 8",
"Object: [object Comment]",
"nodeValue: <!--Hello World-->",
"Length: 18",
"Substring(2,5): --Hel",
"New nodeValue (replace): <!--HAllo World-->",
"New nodeValue (delete 1): <!--Hllo World-->",
"Index error (delete 2)",
"New nodeValue (delete 3): <!--H",
"New nodeValue (append): <!--H Test",
"Index error (insert 1)",
"New nodeValue (insert 2): <!--H New Test",
"New nodeValue (reset): Reset",
]
self.do_perform_test(caplog, sample, expected)
def test_testDOMImplementation(self, caplog):
sample = os.path.join(self.misc_path, "testDOMImplementation.html")
expected = [
"hasFeature('core'): true",
]
self.do_perform_test(caplog, sample, expected)
def test_testAttrNode(self, caplog):
sample = os.path.join(self.misc_path, "testAttrNode.html")
expected = [
"Object: [object Attr]",
"nodeName: test",
"nodeType: 2",
"nodeValue: foo",
"Length: undefined",
"New nodeValue: test2",
"Parent: null",
"Owner: null",
"Name: test",
"Specified: true",
"childNodes length: 0",
]
self.do_perform_test(caplog, sample, expected)
def test_testReplaceChild(self, caplog):
sample = os.path.join(self.misc_path, "testReplaceChild.html")
expected = [
"firstChild: Old child",
"lastChild: Old child",
"innerText: Old child",
"[ERROR] Attempting to replace with a null element",
"[ERROR] Attempting to replace a null element",
"[ERROR] Attempting to replace with an invalid element",
"[ERROR] Attempting to replace an invalid element",
"[ERROR] Attempting to replace on a read-only element failed",
"Alert Text: New child",
'<div id="foobar"><!--Just a comment--></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testCookie(self, caplog):
sample = os.path.join(self.misc_path, "testCookie.html")
expected = ["favorite_food=tripe", "name=oeschger"]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment1(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment1.html")
expected = [
"<div><p>Test</p></div>",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment2(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment2.html")
expected = [
'<div id="foobar"><b>This is B</b></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentFragment3(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentFragment3.html")
expected = [
"foo:bar",
]
self.do_perform_test(caplog, sample, expected)
def test_testClassList2(self, caplog):
sample = os.path.join(self.misc_path, "testClassList2.html")
expected = [
'[Initial value] <div class="foo"></div>',
'[After remove and add] <div class="anotherclass"></div>',
"[Item] anotherclass",
"[Empty item] null",
"[Toggle visible] true",
'[After multiple adds] <div class="anotherclass visible foo bar baz"></div>',
'[After multiple removes] <div class="anotherclass visible"></div>',
'[After replace] <div class="visible justanotherclass"></div>',
'[After toggle] <div class="justanotherclass"></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testClassList4(self, caplog):
sample = os.path.join(self.misc_path, "testClassList4.html")
expected = [
'[After remove and add] <div class="anotherclass"></div>',
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentType(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentType.html")
expected = [
"Doctype: [object DocumentType]",
"Doctype name: html",
"Doctype nodeName: html",
"Doctype nodeType: 10",
"Doctype nodeValue: null",
"Doctype publicId: ",
"Doctype systemId: ",
"Doctype textContent: null",
]
self.do_perform_test(caplog, sample, expected)
def test_testRemoveChild(self, caplog):
sample = os.path.join(self.misc_path, "testRemoveChild.html")
expected = [
"<div>Don't care about me</div>",
"[ERROR] Attempting to remove null element",
"[ERROR] Attempting to remove an invalid element",
"[ERROR] Attempting to remove a read-only element",
"[ERROR] Attempting to remove an element not in the tree",
"[ERROR] Attempting to remove from a read-only element",
]
self.do_perform_test(caplog, sample, expected)
def test_testNamedNodeMap(self, caplog):
sample = os.path.join(self.misc_path, "testNamedNodeMap.html")
expected = [
"hasAttributes (before removal): true",
"hasAttribute('id'): true",
"First test: id->p1",
"Second test: id->p1",
"Third test: id->p1",
"Fourth test: id->p1",
"Fifth test failed",
"Not existing: null",
"hasAttributes (after removal): false",
"Sixth test: foo->bar",
"Seventh test: foo->bar2",
"Final attributes length: 1",
]
self.do_perform_test(caplog, sample, expected)
def test_testEntityReference(self, caplog):
sample = os.path.join(self.misc_path, "testEntityReference.html")
expected = [
"node: [object EntityReference]",
"name: &",
"nodeName: &",
"nodeType: 5",
"nodeValue: null",
]
self.do_perform_test(caplog, sample, expected)
def test_getElementsByTagName(self, caplog):
sample = os.path.join(self.misc_path, "testGetElementsByTagName.html")
expected = [
"[object HTMLHtmlElement]",
"[object HTMLHeadElement]",
"[object HTMLBodyElement]",
"[object HTMLParagraphElement]",
"[object HTMLScriptElement]",
]
self.do_perform_test(caplog, sample, expected)
def test_testDocumentElement(self, caplog):
sample = os.path.join(self.misc_path, "testDocumentElement.html")
expected = ['<a href="http://www.google.com">Google</a>']
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute1(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute1.html")
expected = ["Attribute: bar", "Attribute (after removal): null"]
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute2(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute2.html")
expected = [
"[element workaround redirection] about:blank -> https://buffer.github.io/thug/notexists.html",
"[element workaround redirection] about:blank -> https://buffer.github.io/thug/",
]
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute3(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute3.html")
expected = [
"Alert Text: foo",
"Alert Text: bar",
"Alert Text: test",
"Alert Text: foobar",
]
self.do_perform_test(caplog, sample, expected)
def test_testSetAttribute4(self, caplog):
sample = os.path.join(self.misc_path, "testSetAttribute4.html")
expected = ['<input id="foo" style="fontSize:0" type="range"/>']
self.do_perform_test(caplog, sample, expected)
def test_testCDATASection(self, caplog):
sample = os.path.join(self.misc_path, "testCDATASection.html")
expected = [
"nodeName: #cdata-section",
"nodeType: 4",
"<xml><![CDATA[Some <CDATA> data & then some]]></xml>",
]
self.do_perform_test(caplog, sample, expected)
def test_testProcessingInstruction(self, caplog):
sample = os.path.join(self.misc_path, "testProcessingInstruction.html")
expected = [
"[object ProcessingInstruction]",
"nodeName: xml-stylesheet",
"nodeType: 7",
'nodeValue: href="mycss.css" type="text/css"',
"target: xml-stylesheet",
]
self.do_perform_test(caplog, sample, expected)
def test_testWindow(self, caplog):
sample = os.path.join(self.misc_path, "testWindow.html")
expected = [
"window: [object Window]",
"self: [object Window]",
"top: [object Window]",
"length: 0",
"history: [object History]",
"pageXOffset: 0",
"pageYOffset: 0",
"screen: [object Screen]",
"screenLeft: 0",
"screenX: 0",
"confirm: true",
]
self.do_perform_test(caplog, sample, expected)
def test_testObject1(self, caplog):
sample = os.path.join(self.misc_path, "testObject1.html")
expected = [
"[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf"
]
self.do_perform_test(caplog, sample, expected)
def test_testReplaceChild2(self, caplog):
sample = os.path.join(self.misc_path, "testReplaceChild2.html")
expected = ['<div id="foobar"><div id="test"></div></div>']
self.do_perform_test(caplog, sample, expected)
def test_testNavigator(self, caplog):
sample = os.path.join(self.misc_path, "testNavigator.html")
expected = [
"window: [object Window]",
"appCodeName: Mozilla",
"appName: Netscape",
"appVersion: 5.0 (Windows)",
"cookieEnabled: true",
"onLine: true",
"platform: Win32",
]
self.do_perform_test(caplog, sample, expected, "win7firefox3")
def test_testHTMLOptionsCollection(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html")
expected = [
"length: 4",
"item(0): Volvo",
"namedItem('audi'): Audi",
"namedItem('mercedes').value: mercedes",
"[After remove] item(0): Saab",
"[After first add] length: 4",
"[After first add] item(3): foobar",
"[After second add] length: 5",
"[After second add] item(3): test1234",
"Not found error",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLAnchorElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html")
expected = [
"a.protocol: https:",
"a.host: www.example.com:1234",
"a.hostname: www.example.com",
"a.port: 1234",
"b.protocol: :",
"b.host: ",
"b.hostname: ",
"b.port: ",
"c.protocol: https:",
"c.host: www.example.com",
"c.hostname: www.example.com",
"c.port: ",
"e.pathname: /foo/index.html",
]
self.do_perform_test(caplog, sample, expected)
def test_testTextArea(self, caplog):
sample = os.path.join(self.misc_path, "testTextArea.html")
expected = ["type: textarea", "cols: 100", "rows: 25"]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLDocument(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLDocument.html")
expected = [
"document.title: Test",
"document.title: Foobar",
"anchors: [object HTMLCollection]",
"anchors length: 1",
"anchors[0].name: foobar",
"applets: [object HTMLCollection]",
"applets length: 2",
"applets[0].code: HelloWorld.class",
"links: [object HTMLCollection]",
"links length: 1",
"links[0].href: https://github.com/buffer/thug/",
"images: [object HTMLCollection]",
"images length: 1",
"images[0].href: test.jpg",
"disabled: false",
"head: [object HTMLHeadElement]",
"referrer: ",
"URL: about:blank",
"Alert Text: Hello, world",
]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLFormElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLFormElement.html")
expected = [
"[object HTMLFormElement]",
"f.elements: [object HTMLFormControlsCollection]",
"f.length: 4",
"f.name: [object HTMLFormControlsCollection]",
"f.acceptCharset: ",
"f.action: /cgi-bin/test",
"f.enctype: application/x-www-form-urlencoded",
"f.encoding: application/x-www-form-urlencoded",
"f.method: POST",
"f.target: ",
]
self.do_perform_test(caplog, sample, expected)
def test_testApplet(self, caplog):
sample = os.path.join(self.misc_path, "testApplet.html")
expected = ["[applet redirection]"]
self.do_perform_test(caplog, sample, expected)
def test_testFrame(self, caplog):
sample = os.path.join(self.misc_path, "testFrame.html")
expected = [
"[frame redirection]",
"Alert Text: https://buffer.github.io/thug/",
"Alert Text: data:text/html,<script>alert('Hello world');</script>",
]
self.do_perform_test(caplog, sample, expected)
def test_testIFrame(self, caplog):
sample = os.path.join(self.misc_path, "testIFrame.html")
expected = ["[iframe redirection]", "width: 3", "height: 4"]
self.do_perform_test(caplog, sample, expected)
def test_testHTMLImageElement(self, caplog):
sample = os.path.join(self.misc_path, "testHTMLImageElement.html")
expected = [
"src (before changes): test.jpg",
"src (after first change): test2.jpg",
"onerror handler fired",
]
self.do_perform_test(caplog, sample, expected)
def test_testTitle(self, caplog):
sample = os.path.join(self.misc_path, "testTitle.html")
expected = ["New title: Foobar"]
self.do_perform_test(caplog, sample, expected)
def test_testSidebar(self, caplog):
sample = os.path.join(self.misc_path, "testSidebar.html")
expected = ["Google: 1", "Amazon: 0"]
self.do_perform_test(caplog, sample, expected)
def test_testCSSStyleDeclaration(self, caplog):
sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html")
expected = [
"style: [object CSSStyleDeclaration]",
"length: 1",
"cssText: color: blue;",
"color: blue",
"item(0): color",
"item(100):",
"getPropertyValue('color'): blue",
"length (after removeProperty): 0",
"cssText: foo: bar;",
]
self.do_perform_test(caplog, sample, expected)
def test_testFormProperty(self, caplog):
sample = os.path.join(self.misc_path, "testFormProperty.html")
expected = ["[object HTMLFormElement]", "formA"]
self.do_perform_test(caplog, sample, expected)
def test_testFontFaceRule1(self, caplog):
sample = os.path.join(self.misc_path, "testFontFaceRule1.html")
expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"]
self.do_perform_test(caplog, sample, expected)
def test_testFontFaceRule2(self, caplog):
sample = os.path.join(self.misc_path, "testFontFaceRule2.html")
expected = [
"[font face redirection]",
"https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf",
]
self.do_perform_test(caplog, sample, expected)
def test_testHistory(self, caplog):
sample = os.path.join(self.misc_path, "testHistory.html")
expected = [
"history: [object History]",
"window: [object Window]",
"navigationMode (before change): automatic",
"navigationMode (after change): fast",
]
self.do_perform_test(caplog, sample, expected)
def test_testConsole(self, caplog):
sample = os.path.join(self.misc_path, "testConsole.html")
expected = [
"[object Console]",
"[Console] assert(True, 'Test assert')",
"[Console] count() = 1",
"[Console] count('foobar') = 1",
"[Console] count('foobar') = 2",
"[Console] error('Test error')",
"[Console] log('Hello world!')",
"[Console] group()",
"[Console] log('Hello again, this time inside a group!')",
"[Console] groupEnd()",
"[Console] groupCollapsed()",
"[Console] info('Hello again')",
"[Console] warn('Hello again')",
]
self.do_perform_test(caplog, sample, expected)
def test_testCrypto(self, caplog):
sample = os.path.join(self.misc_path, "testCrypto.html")
expected = ["enableSmartCardEvents: false", "version: 2.4"]
self.do_perform_test(caplog, sample, expected)
| 28,730
|
Python
|
.py
| 632
| 35.151899
| 153
| 0.595207
|
buffer/thug
| 978
| 204
| 0
|
GPL-2.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|