From 75db8aeb57a433493ee9624d608e7b44e0b786ed Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 1 Jul 2019 17:59:09 -0400 Subject: [PATCH 01/65] Add Black as a test dependency. Add Black to travis --- .travis.yml | 1 + pyproject.toml | 2 ++ tests_requirements.txt | 1 + 3 files changed, 4 insertions(+) create mode 100644 pyproject.toml diff --git a/.travis.yml b/.travis.yml index f560a722..c22743fe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,7 @@ script: - coverage run -m unittest discover - flake8 canvasapi tests - mdl . .github + - black --check canvasapi tests after_success: - coveralls notifications: diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..0097e9f6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,2 @@ +[tool.black] +skip-string-normalization = true diff --git a/tests_requirements.txt b/tests_requirements.txt index bee0b572..975b73f2 100644 --- a/tests_requirements.txt +++ b/tests_requirements.txt @@ -1,5 +1,6 @@ -r requirements.txt +black coverage flake8 requests-mock From 5b3128764ce3d1f439871b844522266b63c41fd6 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 1 Jul 2019 18:21:50 -0400 Subject: [PATCH 02/65] Add pre-commit as a dependency. Add pre-commit config to use black. Make black only install on py3.6+ --- .pre-commit-config.yaml | 6 ++++++ dev_requirements.txt | 1 + tests_requirements.txt | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..9d0cb7b7 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,6 @@ +repos: + - repo: https://github.com/ambv/black + rev: stable + hooks: + - id: black + language_version: python3.7 diff --git a/dev_requirements.txt b/dev_requirements.txt index faf1554c..f2a3d40a 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -1,5 +1,6 @@ -r tests_requirements.txt +pre-commit; python_version < '3.6' Sphinx sphinx-rtd-theme svn+https://svn.code.sf.net/p/docutils/code/trunk/docutils#egg=docutils diff --git a/tests_requirements.txt b/tests_requirements.txt index 975b73f2..adb8ac9f 100644 --- a/tests_requirements.txt +++ b/tests_requirements.txt @@ -1,6 +1,6 @@ -r requirements.txt -black +black; python_version < '3.6' coverage flake8 requests-mock From a2d31a9e0d6ef8569fed116e66cb56fa067d84cc Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 1 Jul 2019 18:32:39 -0400 Subject: [PATCH 03/65] Invert python version requirements to actually be 3.6 or above --- dev_requirements.txt | 2 +- tests_requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dev_requirements.txt b/dev_requirements.txt index f2a3d40a..7b4a4e43 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -1,6 +1,6 @@ -r tests_requirements.txt -pre-commit; python_version < '3.6' +pre-commit; python_version >= '3.6' Sphinx sphinx-rtd-theme svn+https://svn.code.sf.net/p/docutils/code/trunk/docutils#egg=docutils diff --git a/tests_requirements.txt b/tests_requirements.txt index adb8ac9f..06f873c3 100644 --- a/tests_requirements.txt +++ b/tests_requirements.txt @@ -1,6 +1,6 @@ -r requirements.txt -black; python_version < '3.6' +black; python_version >= '3.6' coverage flake8 requests-mock From 9ab6d1200f94f2646c16a1ae48c99476e3997ae6 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 2 Jul 2019 14:03:29 -0400 Subject: [PATCH 04/65] Add run_black script to only run on Python 3.6+. Moved run_tests to scripts folder. --- .travis.yml | 2 +- scripts/run_black.sh | 11 +++++++++++ run_tests.sh => scripts/run_tests.sh | 0 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100755 scripts/run_black.sh rename run_tests.sh => scripts/run_tests.sh (100%) diff --git a/.travis.yml b/.travis.yml index c22743fe..f0df48a8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,7 +20,7 @@ script: - coverage run -m unittest discover - flake8 canvasapi tests - mdl . .github - - black --check canvasapi tests + - ./scripts/run_black.sh after_success: - coveralls notifications: diff --git a/scripts/run_black.sh b/scripts/run_black.sh new file mode 100755 index 00000000..b3c1e96f --- /dev/null +++ b/scripts/run_black.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -ev + +PYTHON_VERSION=`python -c 'import sys; version=sys.version_info[:3]; print("{0}.{1}".format(*version))'` + +major_ver=${PYTHON_VERSION:0:1} +minor_ver=${PYTHON_VERSION:2:3} + +if (( "$major_ver" >= 3 && "$minor_ver" >= 6 )); then + black --check canvasapi tests +fi diff --git a/run_tests.sh b/scripts/run_tests.sh similarity index 100% rename from run_tests.sh rename to scripts/run_tests.sh From 9f403edd5fffa76f031b9fe537b9360e0ace0f07 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 8 Jul 2019 15:38:48 -0400 Subject: [PATCH 05/65] Start new changelog entry --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfc00583..0cfcabda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Change Log +## Unreleased + ## [0.13.0] - 2019-07-08 ### New Endpoint Coverage From d8badeddc382bf1f9a3034ab5c002c98c270314e Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 9 Jul 2019 16:54:59 -0400 Subject: [PATCH 06/65] Blacken library --- canvasapi/account.py | 2006 ++++++++++++------------ canvasapi/appointment_group.py | 5 +- canvasapi/assignment.py | 60 +- canvasapi/authentication_provider.py | 5 +- canvasapi/avatar.py | 1 - canvasapi/blueprint.py | 160 +- canvasapi/bookmark.py | 6 +- canvasapi/calendar_event.py | 5 +- canvasapi/canvas.py | 266 ++-- canvasapi/canvas_object.py | 8 +- canvasapi/communication_channel.py | 36 +- canvasapi/content_migration.py | 63 +- canvasapi/conversation.py | 18 +- canvasapi/course.py | 364 ++--- canvasapi/current_user.py | 47 +- canvasapi/discussion_topic.py | 125 +- canvasapi/enrollment.py | 14 +- canvasapi/enrollment_term.py | 6 +- canvasapi/exceptions.py | 8 + canvasapi/external_feed.py | 1 - canvasapi/external_tool.py | 20 +- canvasapi/favorite.py | 9 +- canvasapi/file.py | 16 +- canvasapi/folder.py | 31 +- canvasapi/grading_period.py | 5 +- canvasapi/grading_standard.py | 1 - canvasapi/group.py | 175 +-- canvasapi/login.py | 6 +- canvasapi/module.py | 44 +- canvasapi/notification_preference.py | 1 - canvasapi/outcome.py | 54 +- canvasapi/page.py | 39 +- canvasapi/page_view.py | 1 - canvasapi/paginated_list.py | 19 +- canvasapi/peer_review.py | 1 - canvasapi/planner.py | 12 +- canvasapi/poll.py | 39 +- canvasapi/poll_choice.py | 16 +- canvasapi/poll_session.py | 25 +- canvasapi/poll_submission.py | 1 - canvasapi/progress.py | 6 +- canvasapi/quiz.py | 143 +- canvasapi/quiz_group.py | 15 +- canvasapi/rubric.py | 1 - canvasapi/section.py | 113 +- canvasapi/sis_import.py | 9 +- canvasapi/submission.py | 50 +- canvasapi/tab.py | 3 +- canvasapi/upload.py | 6 +- canvasapi/user.py | 133 +- tests/test_account.py | 86 +- tests/test_appointment_group.py | 1 - tests/test_assignment.py | 62 +- tests/test_authentication_providers.py | 25 +- tests/test_blueprint.py | 42 +- tests/test_bookmark.py | 8 +- tests/test_calendar_event.py | 1 - tests/test_canvas.py | 97 +- tests/test_communication_channel.py | 34 +- tests/test_content_export.py | 2 +- tests/test_content_migration.py | 35 +- tests/test_conversation.py | 5 +- tests/test_course.py | 155 +- tests/test_current_user.py | 11 +- tests/test_discussion_topic.py | 15 +- tests/test_enrollment.py | 6 +- tests/test_enrollment_term.py | 17 +- tests/test_external_feed.py | 1 - tests/test_external_tool.py | 9 +- tests/test_favorite.py | 7 +- tests/test_file.py | 5 +- tests/test_folder.py | 1 - tests/test_grading_period.py | 27 +- tests/test_grading_standard.py | 5 +- tests/test_group.py | 74 +- tests/test_login.py | 12 +- tests/test_module.py | 21 +- tests/test_notification_preference.py | 7 +- tests/test_outcome.py | 150 +- tests/test_page.py | 6 +- tests/test_page_view.py | 1 - tests/test_paginated_list.py | 147 +- tests/test_peer_review.py | 7 +- tests/test_planner.py | 17 +- tests/test_poll.py | 14 +- tests/test_poll_choice.py | 32 +- tests/test_poll_session.py | 41 +- tests/test_poll_submission.py | 11 +- tests/test_progress.py | 3 +- tests/test_quiz_group.py | 12 +- tests/test_rubric.py | 5 +- tests/test_section.py | 87 +- tests/test_sis_import.py | 13 +- tests/test_tab.py | 12 +- tests/test_uploader.py | 21 +- tests/test_user.py | 35 +- tests/test_validate_docstrings.py | 51 +- tests/util.py | 15 +- 98 files changed, 2595 insertions(+), 3054 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 25ac27e6..95a9826d 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -17,10 +17,103 @@ @python_2_unicode_compatible class Account(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) + def abort_sis_imports_pending(self, **kwargs): + """ + Aborts all pending (created, but not processed or processing) + SIS imports for the current account. + + :calls: `PUT /api/v1/accounts/:account_id/sis_imports/abort_all_pending \ + `_ + + :returns: True if the API responds with aborted=True, False otherwise. + :rtype: bool + """ + response = self._requester.request( + 'PUT', + 'accounts/{}/sis_imports/abort_all_pending'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + return response.json().get('aborted', False) + + def activate_role(self, role, **kwargs): + """ + Reactivate an inactive role. + + :calls: `POST /api/v1/accounts/:account_id/roles/:id/activate \ + `_ + + :param role: The object or ID of the role. + :type role: :class:`canvasapi.account.Role` or int + :rtype: :class:`canvasapi.account.Role` + """ + role_id = obj_or_id(role, "role", (Role,)) + + response = self._requester.request( + 'POST', + 'accounts/{}/roles/{}/activate'.format(self.id, role_id), + _kwargs=combine_kwargs(**kwargs), + ) + return Role(self._requester, response.json()) + + def add_authentication_providers(self, **kwargs): + """ + Add external authentication providers for the account + + :calls: `POST /api/v1/accounts/:account_id/authentication_providers \ + `_ + + :rtype: :class:`canvasapi.authentication_provider.AuthenticationProvider` + """ + from canvasapi.authentication_provider import AuthenticationProvider + + response = self._requester.request( + 'POST', + 'accounts/{}/authentication_providers'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + authentication_providers_json = response.json() + authentication_providers_json.update({'account_id': self.id}) + + return AuthenticationProvider(self._requester, authentication_providers_json) + + def add_grading_standards(self, title, grading_scheme_entry, **kwargs): + """ + Create a new grading standard for the account. + + :calls: `POST /api/v1/accounts/:account_id/grading_standards \ + `_ + + :param title: The title for the Grading Standard + :type title: str + :param grading_scheme: A list of dictionaries containing keys for "name" and "value" + :type grading_scheme: list[dict] + :rtype: :class:`canvasapi.grading_standards.GradingStandard` + """ + if not isinstance(grading_scheme_entry, list) or len(grading_scheme_entry) <= 0: + raise ValueError("Param `grading_scheme_entry` must be a non-empty list.") + + for entry in grading_scheme_entry: + if not isinstance(entry, dict): + raise ValueError("grading_scheme_entry must consist of dictionaries.") + if "name" not in entry or "value" not in entry: + raise ValueError( + "Dictionaries with keys 'name' and 'value' are required." + ) + kwargs["grading_scheme_entry"] = grading_scheme_entry + + response = self._requester.request( + 'POST', + 'accounts/%s/grading_standards' % (self.id), + title=title, + _kwargs=combine_kwargs(**kwargs), + ) + + return GradingStandard(self._requester, response.json()) + def close_notification_for_user(self, user, notification): """ If the user no long wants to see a notification, it can be @@ -43,7 +136,9 @@ def close_notification_for_user(self, user, notification): response = self._requester.request( 'DELETE', - 'accounts/{}/users/{}/account_notifications/{}'.format(self.id, user_id, notif_id) + 'accounts/{}/users/{}/account_notifications/{}'.format( + self.id, user_id, notif_id + ), ) return AccountNotification(self._requester, response.json()) @@ -59,10 +154,66 @@ def create_account(self, **kwargs): response = self._requester.request( 'POST', 'accounts/{}/root_accounts'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Account(self._requester, response.json()) + def create_admin(self, user, **kwargs): + """ + Flag an existing user as an admin of the current account. + + :calls: `POST /api/v1/accounts/:account_id/admins \ + `_ + + :param user: The user object or ID to promote to admin. + :type user: :class:`canvasapi.user.User` or int + + :rtype: :class:`canvasapi.account.Admin` + """ + from canvasapi.user import User + + user_id = obj_or_id(user, "user", (User,)) + kwargs['user_id'] = user_id + + response = self._requester.request( + 'POST', + 'accounts/{}/admins'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + return Admin(self._requester, response.json()) + + def create_content_migration(self, migration_type, **kwargs): + """ + Create a content migration. + + :calls: `POST /api/v1/accounts/:account_id/content_migrations \ + `_ + + :param migration_type: The migrator type to use in this migration + :type migration_type: str or :class:`canvasapi.content_migration.Migrator` + + :rtype: :class:`canvasapi.content_migration.ContentMigration` + """ + from canvasapi.content_migration import ContentMigration, Migrator + + if isinstance(migration_type, Migrator): + kwargs['migration_type'] = migration_type.type + elif isinstance(migration_type, string_types): + kwargs['migration_type'] = migration_type + else: + raise TypeError('Parameter migration_type must be of type Migrator or str') + + response = self._requester.request( + 'POST', + 'accounts/{}/content_migrations'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({'account_id': self.id}) + + return ContentMigration(self._requester, response_json) + def create_course(self, **kwargs): """ Create a course. @@ -73,62 +224,92 @@ def create_course(self, **kwargs): :rtype: :class:`canvasapi.course.Course` """ from canvasapi.course import Course + response = self._requester.request( 'POST', 'accounts/{}/courses'.format(self.id), account_id=self.id, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Course(self._requester, response.json()) - def create_subaccount(self, account, **kwargs): + def create_enrollment_term(self, **kwargs): """ - Add a new sub-account to a given account. - - :calls: `POST /api/v1/accounts/:account_id/sub_accounts \ - `_ + Create an enrollment term. - :param account: The name of the account - :type account: str + :calls: `POST /api/v1/accounts/:account_id/terms \ + `_ - :rtype: :class:`canvasapi.account.Account` + :rtype: :class:`canvasapi.enrollment_term.EnrollmentTerm` """ - if isinstance(account, dict) and 'name' in account: - kwargs['account'] = account - else: - raise RequiredFieldMissing("Dictionary with key 'name' is required.") + from canvasapi.enrollment_term import EnrollmentTerm response = self._requester.request( 'POST', - 'accounts/{}/sub_accounts'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/terms'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return Account(self._requester, response.json()) + enrollment_term_json = response.json() + enrollment_term_json.update({'account_id': self.id}) - def create_user(self, pseudonym, **kwargs): + return EnrollmentTerm(self._requester, enrollment_term_json) + + def create_external_tool( + self, name, privacy_level, consumer_key, shared_secret, **kwargs + ): """ - Create and return a new user and pseudonym for an account. + Create an external tool in the current account. - :calls: `POST /api/v1/accounts/:account_id/users \ - `_ + :calls: `POST /api/v1/accounts/:account_id/external_tools \ + `_ - :param pseudonym: The pseudonym of the account. - :type pseudonym: dict - :rtype: :class:`canvasapi.user.User` + :param name: The name of the tool + :type name: str + :param privacy_level: What information to send to the external + tool. Options are "anonymous", "name_only", "public" + :type privacy_level: str + :param consumer_key: The consumer key for the external tool + :type consumer_key: str + :param shared_secret: The shared secret with the external tool + :type shared_secret: str + :rtype: :class:`canvasapi.external_tool.ExternalTool` """ - from canvasapi.user import User + from canvasapi.external_tool import ExternalTool - if isinstance(pseudonym, dict) and 'unique_id' in pseudonym: - kwargs['pseudonym'] = pseudonym - else: - raise RequiredFieldMissing("Dictionary with key 'unique_id' is required.") + response = self._requester.request( + 'POST', + 'accounts/{}/external_tools'.format(self.id), + name=name, + privacy_level=privacy_level, + consumer_key=consumer_key, + shared_secret=shared_secret, + _kwargs=combine_kwargs(**kwargs), + ) + response_json = response.json() + response_json.update({'account_id': self.id}) + + return ExternalTool(self._requester, response_json) + + def create_group_category(self, name, **kwargs): + """ + Create a Group Category + + :calls: `POST /api/v1/accounts/:account_id/group_categories \ + `_ + + :param name: Name of group category. + :type name: str + :rtype: :class:`canvasapi.group.GroupCategory` + """ + from canvasapi.group import GroupCategory response = self._requester.request( 'POST', - 'accounts/{}/users'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/group_categories'.format(self.id), + name=name, + _kwargs=combine_kwargs(**kwargs), ) - return User(self._requester, response.json()) + return GroupCategory(self._requester, response.json()) def create_notification(self, account_notification, **kwargs): """ @@ -142,341 +323,159 @@ def create_notification(self, account_notification, **kwargs): :rtype: :class:`canvasapi.account.AccountNotification` """ required_key_list = ['subject', 'message', 'start_at', 'end_at'] - required_keys_present = all((x in account_notification for x in required_key_list)) + required_keys_present = all( + (x in account_notification for x in required_key_list) + ) if isinstance(account_notification, dict) and required_keys_present: kwargs['account_notification'] = account_notification else: - raise RequiredFieldMissing(( - "account_notification must be a dictionary with keys " - "'subject', 'message', 'start_at', and 'end_at'." - )) + raise RequiredFieldMissing( + ( + "account_notification must be a dictionary with keys " + "'subject', 'message', 'start_at', and 'end_at'." + ) + ) response = self._requester.request( 'POST', 'accounts/{}/account_notifications'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return AccountNotification(self._requester, response.json()) - def delete(self): + def create_role(self, label, **kwargs): """ - Delete the current account - - Note: Cannot delete an account with active courses or active - sub accounts. Cannot delete a root account. + Create a new course-level or account-level role. - :calls: `DELETE /api/v1/accounts/:account_id/sub_accounts/:id \ - `_ + :calls: `POST /api/v1/accounts/:account_id/roles \ + `_ - :returns: True if successfully deleted; False otherwise. - :rtype: bool + :param label: The label for the role. + :type label: str + :rtype: :class:`canvasapi.account.Role` """ - if not hasattr(self, 'parent_account_id') or not self.parent_account_id: - raise CanvasException("Cannot delete a root account.") - response = self._requester.request( - 'DELETE', - 'accounts/{}/sub_accounts/{}'.format(self.parent_account_id, self.id) + 'POST', + 'accounts/{}/roles'.format(self.id), + label=label, + _kwargs=combine_kwargs(**kwargs), ) + return Role(self._requester, response.json()) - return response.json().get('workflow_state') == 'deleted' - - def delete_user(self, user): + def create_sis_import(self, attachment, **kwargs): """ - Delete a user record from a Canvas root account. - - If a user is associated with multiple root accounts (in a - multi-tenant instance of Canvas), this action will NOT remove - them from the other accounts. - - WARNING: This API will allow a user to remove themselves from - the account. If they do this, they won't be able to make API - calls or log into Canvas at that account. + Create a new SIS import for the current account. - :calls: `DELETE /api/v1/accounts/:account_id/users/:user_id \ - `_ + :calls: `POST /api/v1/accounts/:account_id/sis_imports \ + `_ - :param user: The user object or ID to delete. - :type user: :class:`canvasapi.user.User` or int + :param attachment: A file handler or path of the file to import. + :type attachment: file or str - :rtype: :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.sis_import.SisImport` """ - from canvasapi.user import User - user_id = obj_or_id(user, "user", (User,)) + attachment, is_path = file_or_path(attachment) - response = self._requester.request( - 'DELETE', - 'accounts/{}/users/{}'.format(self.id, user_id) - ) - return User(self._requester, response.json()) + try: + response = self._requester.request( + 'POST', + 'accounts/{}/sis_imports'.format(self.id), + file={'attachment': attachment}, + _kwargs=combine_kwargs(**kwargs), + ) - def get_courses(self, **kwargs): - """ - Retrieve the list of courses in this account. + response_json = response.json() + response_json.update({'account_id': self.id}) - :calls: `GET /api/v1/accounts/:account_id/courses \ - `_ + return SisImport(self._requester, response_json) + finally: + if is_path: + attachment.close() - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` + def create_subaccount(self, account, **kwargs): """ - from canvasapi.course import Course - - return PaginatedList( - Course, - self._requester, - 'GET', - 'accounts/{}/courses'.format(self.id), - _kwargs=combine_kwargs(**kwargs) - ) + Add a new sub-account to a given account. - def get_external_tool(self, tool): - """ - :calls: `GET /api/v1/accounts/:account_id/external_tools/:external_tool_id \ - `_ + :calls: `POST /api/v1/accounts/:account_id/sub_accounts \ + `_ - :param tool: The object or ID of the tool - :type tool: :class:`canvasapi.external_tool.ExternalTool` or int + :param account: The name of the account + :type account: str - :rtype: :class:`canvasapi.external_tool.ExternalTool` + :rtype: :class:`canvasapi.account.Account` """ - from canvasapi.external_tool import ExternalTool - - tool_id = obj_or_id(tool, "tool", (ExternalTool,)) + if isinstance(account, dict) and 'name' in account: + kwargs['account'] = account + else: + raise RequiredFieldMissing("Dictionary with key 'name' is required.") response = self._requester.request( - 'GET', - 'accounts/{}/external_tools/{}'.format(self.id, tool_id), - ) - tool_json = response.json() - tool_json.update({'account_id': self.id}) - - return ExternalTool(self._requester, tool_json) - - def get_external_tools(self, **kwargs): - """ - :calls: `GET /api/v1/accounts/:account_id/external_tools \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.external_tool.ExternalTool` - """ - from canvasapi.external_tool import ExternalTool - - return PaginatedList( - ExternalTool, - self._requester, - 'GET', - 'accounts/{}/external_tools'.format(self.id), - {'account_id': self.id}, - _kwargs=combine_kwargs(**kwargs) - ) - - def get_index_of_reports(self, report_type): - """ - Retrieve all reports that have been run for the account of a specific type. - - :calls: `GET /api/v1/accounts/:account_id/reports/:report \ - `_ - - :param report_type: The type of report. - :type report_type: str - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.AccountReport` - """ - return PaginatedList( - AccountReport, - self._requester, - 'GET', - 'accounts/{}/reports/{}'.format(self.id, report_type) - ) - - def get_reports(self): - """ - Return a list of reports for the current context. - - :calls: `GET /api/v1/accounts/:account_id/reports \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.AccountReport` - """ - return PaginatedList( - AccountReport, - self._requester, - 'GET', - 'accounts/{}/reports'.format(self.id) - ) - - def get_subaccounts(self, recursive=False): - """ - List accounts that are sub-accounts of the given account. - - :calls: `GET /api/v1/accounts/:account_id/sub_accounts \ - `_ - - :param recursive: If true, the entire account tree underneath this account will \ - be returned. If false, only direct sub-accounts of this account will be returned. - :type recursive: bool - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.Account` - """ - return PaginatedList( - Account, - self._requester, - 'GET', + 'POST', 'accounts/{}/sub_accounts'.format(self.id), - recursive=recursive - ) - - def get_users(self, **kwargs): - """ - Retrieve a list of users associated with this account. - - :calls: `GET /api/v1/accounts/:account_id/users \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` - """ - from canvasapi.user import User - - return PaginatedList( - User, - self._requester, - 'GET', - 'accounts/{}/users'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) + return Account(self._requester, response.json()) - def get_user_notifications(self, user): + def create_user(self, pseudonym, **kwargs): """ - Return a list of all global notifications in the account for - this user. Any notifications that have been closed by the user - will not be returned. - - :calls: `GET /api/v1/accounts/:account_id/users/:user_id/account_notifications \ - `_ + Create and return a new user and pseudonym for an account. - :param user: The user object or ID to retrieve notifications for. - :type user: :class:`canvasapi.user.User` or int + :calls: `POST /api/v1/accounts/:account_id/users \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.AccountNotification` + :param pseudonym: The pseudonym of the account. + :type pseudonym: dict + :rtype: :class:`canvasapi.user.User` """ from canvasapi.user import User - user_id = obj_or_id(user, "user", (User,)) - - return PaginatedList( - AccountNotification, - self._requester, - 'GET', - 'accounts/{}/users/{}/account_notifications'.format(self.id, user_id) - ) - - def update(self, **kwargs): - """ - Update an existing account. - - :calls: `PUT /api/v1/accounts/:id \ - `_ - - :returns: True if the account was updated, False otherwise. - :rtype: bool - """ - response = self._requester.request( - 'PUT', - 'accounts/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) - ) - - if 'name' in response.json(): - super(Account, self).set_attributes(response.json()) - return True + if isinstance(pseudonym, dict) and 'unique_id' in pseudonym: + kwargs['pseudonym'] = pseudonym else: - return False - - def list_roles(self, **kwargs): - """ - List the roles available to an account. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_roles` instead. - - :calls: `GET /api/v1/accounts/:account_id/roles \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.Role` - """ - warnings.warn( - "`list_roles` is being deprecated and will be removed in a future version." - " Use `get_roles` instead", - DeprecationWarning - ) - - return self.get_roles(**kwargs) - - def get_roles(self, **kwargs): - """ - List the roles available to an account. - - :calls: `GET /api/v1/accounts/:account_id/roles \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.Role` - """ + raise RequiredFieldMissing("Dictionary with key 'unique_id' is required.") - return PaginatedList( - Role, - self._requester, - 'GET', - 'accounts/{}/roles'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + response = self._requester.request( + 'POST', + 'accounts/{}/users'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) + return User(self._requester, response.json()) - def get_role(self, role): - """ - Retrieve a role by ID. - - :calls: `GET /api/v1/accounts/:account_id/roles/:id \ - `_ - - :param role: The object or ID of the role. - :type role: :class:`canvasapi.account.Role` or int - - :rtype: :class:`canvasapi.account.Role` + def create_user_login(self, user, login, **kwargs): """ - role_id = obj_or_id(role, "role", (Role,)) + Create a new login for an existing user in the given account - response = self._requester.request( - 'GET', - 'accounts/{}/roles/{}'.format(self.id, role_id) - ) - return Role(self._requester, response.json()) + :calls: `POST /api/v1/accounts/:account_id/logins \ + `_ - def create_role(self, label, **kwargs): + :param user: The attributes of the user to create a login for + :type user: `dict` + :param login: The attributes of the login to create + :type login: `dict` + :rtype: :class:`canvasapi.login.Login` """ - Create a new course-level or account-level role. + from canvasapi.login import Login - :calls: `POST /api/v1/accounts/:account_id/roles \ - `_ + if isinstance(user, dict) and 'id' in user: + kwargs['user'] = user + else: + raise RequiredFieldMissing(("user must be a dictionary with keys " "'id'.")) + + if isinstance(login, dict) and 'unique_id' in login: + kwargs['login'] = login + else: + raise RequiredFieldMissing( + ("login must be a dictionary with keys " "'unique_id'.") + ) - :param label: The label for the role. - :type label: str - :rtype: :class:`canvasapi.account.Role` - """ response = self._requester.request( 'POST', - 'accounts/{}/roles'.format(self.id), - label=label, - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/logins'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return Role(self._requester, response.json()) + return Login(self._requester, response.json()) def deactivate_role(self, role, **kwargs): """ @@ -495,361 +494,283 @@ def deactivate_role(self, role, **kwargs): response = self._requester.request( 'DELETE', 'accounts/{}/roles/{}'.format(self.id, role_id), - _kwargs=combine_kwargs(**kwargs) - ) - return Role(self._requester, response.json()) - - def activate_role(self, role, **kwargs): - """ - Reactivate an inactive role. - - :calls: `POST /api/v1/accounts/:account_id/roles/:id/activate \ - `_ - - :param role: The object or ID of the role. - :type role: :class:`canvasapi.account.Role` or int - :rtype: :class:`canvasapi.account.Role` - """ - role_id = obj_or_id(role, "role", (Role,)) - - response = self._requester.request( - 'POST', - 'accounts/{}/roles/{}/activate'.format(self.id, role_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Role(self._requester, response.json()) - def update_role(self, role, **kwargs): + def delete(self): """ - Update permissions for an existing role. + Delete the current account - :calls: `PUT /api/v1/accounts/:account_id/roles/:id \ - `_ + Note: Cannot delete an account with active courses or active + sub accounts. Cannot delete a root account. - :param role: The object or ID of the role. - :type role: :class:`canvasapi.account.Role` or int + :calls: `DELETE /api/v1/accounts/:account_id/sub_accounts/:id \ + `_ - :rtype: :class:`canvasapi.account.Role` + :returns: True if successfully deleted; False otherwise. + :rtype: bool """ - role_id = obj_or_id(role, "role", (Role,)) + if not hasattr(self, 'parent_account_id') or not self.parent_account_id: + raise CanvasException("Cannot delete a root account.") response = self._requester.request( - 'PUT', - 'accounts/{}/roles/{}'.format(self.id, role_id), - _kwargs=combine_kwargs(**kwargs) + 'DELETE', + 'accounts/{}/sub_accounts/{}'.format(self.parent_account_id, self.id), ) - return Role(self._requester, response.json()) - def get_enrollment(self, enrollment, **kwargs): + return response.json().get('workflow_state') == 'deleted' + + def delete_grading_period(self, grading_period): """ - Get an enrollment object by ID. + Delete a grading period for an account. - :calls: `GET /api/v1/accounts/:account_id/enrollments/:id \ - `_ + :calls: `DELETE /api/v1/accounts/:account_id/grading_periods/:id \ + `_ - :param enrollment: The object or ID of the enrollment to retrieve. - :type enrollment: :class:`canvasapi.enrollment.Enrollment` or int + :param grading_period: The GradingPeriod object or ID to delete. + :type grading_period: :class:`canvasapi.grading_period.GradingPeriod` or int - :rtype: :class:`canvasapi.enrollment.Enrollment` + :returns: True if the grading period was deleted, False otherwise. + :rtype: bool """ - from canvasapi.enrollment import Enrollment - enrollment_id = obj_or_id(enrollment, "enrollment", (Enrollment,)) + grading_period_id = obj_or_id( + grading_period, "grading_period", (GradingPeriod,) + ) response = self._requester.request( - 'GET', - 'accounts/{}/enrollments/{}'.format(self.id, enrollment_id), - _kwargs=combine_kwargs(**kwargs) + 'DELETE', + 'accounts/{}/grading_periods/{}'.format(self.id, grading_period_id), ) - return Enrollment(self._requester, response.json()) - - def list_groups(self, **kwargs): - """ - Return a list of active groups for the specified account. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_groups` instead. - :calls: `GET /api/v1/accounts/:account_id/groups \ - `_ + return response.json().get('delete') - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + def delete_user(self, user): """ - warnings.warn( - "`list_groups` is being deprecated and will be removed in a future version." - " Use `get_groups` instead", - DeprecationWarning - ) + Delete a user record from a Canvas root account. - return self.get_groups(**kwargs) + If a user is associated with multiple root accounts (in a + multi-tenant instance of Canvas), this action will NOT remove + them from the other accounts. - def get_groups(self, **kwargs): - """ - Return a list of active groups for the specified account. + WARNING: This API will allow a user to remove themselves from + the account. If they do this, they won't be able to make API + calls or log into Canvas at that account. - :calls: `GET /api/v1/accounts/:account_id/groups \ - `_ + :calls: `DELETE /api/v1/accounts/:account_id/users/:user_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` - """ - from canvasapi.group import Group - return PaginatedList( - Group, - self._requester, - 'GET', - 'accounts/{}/groups'.format(self.id), - _kwargs=combine_kwargs(**kwargs) - ) + :param user: The user object or ID to delete. + :type user: :class:`canvasapi.user.User` or int - def create_group_category(self, name, **kwargs): + :rtype: :class:`canvasapi.user.User` """ - Create a Group Category - - :calls: `POST /api/v1/accounts/:account_id/group_categories \ - `_ + from canvasapi.user import User - :param name: Name of group category. - :type name: str - :rtype: :class:`canvasapi.group.GroupCategory` - """ - from canvasapi.group import GroupCategory + user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'POST', - 'accounts/{}/group_categories'.format(self.id), - name=name, - _kwargs=combine_kwargs(**kwargs) + 'DELETE', 'accounts/{}/users/{}'.format(self.id, user_id) ) - return GroupCategory(self._requester, response.json()) + return User(self._requester, response.json()) - def list_group_categories(self, **kwargs): + def get_admins(self, **kwargs): """ - List group categories for a context. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_group_categories` instead. + Get the paginated list of admins for the current account. - :calls: `GET /api/v1/accounts/:account_id/group_categories \ - `_ + :calls: `GET /api/v1/accounts/:account_id/admins \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupCategory` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.account.Admin` """ - warnings.warn( - "`list_group_categories` is being deprecated and will be removed " - "in a future version. Use `get_group_categories` instead", - DeprecationWarning - ) - return self.get_group_categories(**kwargs) + return PaginatedList( + Admin, + self._requester, + 'GET', + 'accounts/{}/admins'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) - def get_group_categories(self, **kwargs): + def get_all_outcome_links_in_context(self): """ - List group categories for a context. + Get all outcome links for context - BETA - :calls: `GET /api/v1/accounts/:account_id/group_categories \ - `_ + :calls: `GET /api/v1/accounts/:account_id/outcome_group_links \ + `_ + :returns: Paginated List of OutcomesLinks in the context. :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupCategory` + :class:`canvasapi.outcome.OutcomeLink` """ - from canvasapi.group import GroupCategory + from canvasapi.outcome import OutcomeLink return PaginatedList( - GroupCategory, + OutcomeLink, self._requester, 'GET', - 'accounts/{}/group_categories'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/outcome_group_links'.format(self.id), ) - def create_external_tool(self, name, privacy_level, consumer_key, shared_secret, **kwargs): + def get_authentication_provider(self, authentication_provider, **kwargs): """ - Create an external tool in the current account. + Get the specified authentication provider - :calls: `POST /api/v1/accounts/:account_id/external_tools \ - `_ + :calls: `GET /api/v1/accounts/:account_id/authentication_providers/:id \ + `_ - :param name: The name of the tool - :type name: str - :param privacy_level: What information to send to the external - tool. Options are "anonymous", "name_only", "public" - :type privacy_level: str - :param consumer_key: The consumer key for the external tool - :type consumer_key: str - :param shared_secret: The shared secret with the external tool - :type shared_secret: str - :rtype: :class:`canvasapi.external_tool.ExternalTool` + :param authentication_provider: The object or ID of the authentication provider + :type authentication_provider: + :class:`canvasapi.authentication_provider.AuthenticationProvider` or int + + :rtype: :class:`canvasapi.authentication_provider.AuthenticationProvider` """ - from canvasapi.external_tool import ExternalTool + from canvasapi.authentication_provider import AuthenticationProvider + + authentication_providers_id = obj_or_id( + authentication_provider, + "authentication provider", + (AuthenticationProvider,), + ) response = self._requester.request( - 'POST', - 'accounts/{}/external_tools'.format(self.id), - name=name, - privacy_level=privacy_level, - consumer_key=consumer_key, - shared_secret=shared_secret, - _kwargs=combine_kwargs(**kwargs) + 'GET', + 'accounts/{}/authentication_providers/{}'.format( + self.id, authentication_providers_id + ), + _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({'account_id': self.id}) - return ExternalTool(self._requester, response_json) + return AuthenticationProvider(self._requester, response.json()) - def create_enrollment_term(self, **kwargs): + def get_authentication_providers(self, **kwargs): """ - Create an enrollment term. + Return the list of authentication providers - :calls: `POST /api/v1/accounts/:account_id/terms \ - `_ + :calls: `GET /api/v1/accounts/:account_id/authentication_providers \ + `_ - :rtype: :class:`canvasapi.enrollment_term.EnrollmentTerm` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.authentication_provider.AuthenticationProvider` """ - from canvasapi.enrollment_term import EnrollmentTerm + from canvasapi.authentication_provider import AuthenticationProvider - response = self._requester.request( - 'POST', - 'accounts/{}/terms'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + return PaginatedList( + AuthenticationProvider, + self._requester, + 'GET', + 'accounts/{}/authentication_providers'.format(self.id), + {'account_id': self.id}, + _kwargs=combine_kwargs(**kwargs), ) - enrollment_term_json = response.json() - enrollment_term_json.update({'account_id': self.id}) - - return EnrollmentTerm(self._requester, enrollment_term_json) - def list_enrollment_terms(self, **kwargs): + def get_content_migration(self, content_migration, **kwargs): """ - List enrollment terms for a context. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_enrollment_terms` instead. + Retrive a content migration by its ID - :calls: `GET /api/v1/accounts/:account_id/terms \ - `_ + :calls: `GET /api/v1/accounts/:account_id/content_migrations/:id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.enrollment_term.EnrollmentTerm` + :param content_migration: The object or ID of the content migration to retrieve. + :type contnet_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + + :rtype: :class:`canvasapi.content_migration.ContentMigration` """ - warnings.warn( - "`list_enrollment_terms` is being deprecated and will be removed " - "in a future version. Use `get_enrollment_terms` instead", - DeprecationWarning + from canvasapi.content_migration import ContentMigration + + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) ) - return self.get_enrollment_terms(**kwargs) + response = self._requester.request( + 'GET', + 'accounts/{}/content_migrations/{}'.format(self.id, migration_id), + _kwargs=combine_kwargs(**kwargs), + ) - def get_enrollment_terms(self, **kwargs): + response_json = response.json() + response_json.update({'account_id': self.id}) + + return ContentMigration(self._requester, response_json) + + def get_content_migrations(self, **kwargs): """ - List enrollment terms for a context. + List content migrations that the current account can view or manage. - :calls: `GET /api/v1/accounts/:account_id/terms \ - `_ + :calls: `GET /api/v1/accounts/:account_id/content_migrations/ \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.enrollment_term.EnrollmentTerm` + :class:`canvasapi.content_migration.ContentMigration` """ - from canvasapi.enrollment_term import EnrollmentTerm + from canvasapi.content_migration import ContentMigration return PaginatedList( - EnrollmentTerm, + ContentMigration, self._requester, 'GET', - 'accounts/{}/terms'.format(self.id), + 'accounts/{}/content_migrations'.format(self.id), {'account_id': self.id}, - _root='enrollment_terms', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) - def list_user_logins(self, **kwargs): + def get_courses(self, **kwargs): """ - Given a user ID, return that user's logins for the given account. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_user_logins` instead. + Retrieve the list of courses in this account. - :calls: `GET /api/v1/accounts/:account_id/logins \ - `_ + :calls: `GET /api/v1/accounts/:account_id/courses \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.login.Login` + :class:`canvasapi.course.Course` """ - warnings.warn( - "`list_user_logins` is being deprecated and will be removed in a " - "future version. Use `get_user_logins` instead", - DeprecationWarning - ) + from canvasapi.course import Course - return self.get_user_logins(**kwargs) + return PaginatedList( + Course, + self._requester, + 'GET', + 'accounts/{}/courses'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) - def get_user_logins(self, **kwargs): + def get_department_level_grade_data_completed(self): """ - Given a user ID, return that user's logins for the given account. + Return the distribution of all concluded grades in the default term - :calls: `GET /api/v1/accounts/:account_id/logins \ - `_ + :calls: `GET /api/v1/accounts/:account_id/analytics/completed/grades \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.login.Login` + :rtype: dict """ - from canvasapi.login import Login - return PaginatedList( - Login, - self._requester, - 'GET', - 'accounts/{}/logins'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + response = self._requester.request( + 'GET', 'accounts/{}/analytics/completed/grades'.format(self.id) ) + return response.json() - def create_user_login(self, user, login, **kwargs): + def get_department_level_grade_data_current(self): """ - Create a new login for an existing user in the given account + Return the distribution of all available grades in the default term - :calls: `POST /api/v1/accounts/:account_id/logins \ - `_ + :calls: `GET /api/v1/accounts/:account_id/analytics/current/grades \ + `_ - :param user: The attributes of the user to create a login for - :type user: `dict` - :param login: The attributes of the login to create - :type login: `dict` - :rtype: :class:`canvasapi.login.Login` + :rtype: dict """ - from canvasapi.login import Login - - if isinstance(user, dict) and 'id' in user: - kwargs['user'] = user - else: - raise RequiredFieldMissing(( - "user must be a dictionary with keys " - "'id'." - )) - - if isinstance(login, dict) and 'unique_id' in login: - kwargs['login'] = login - else: - raise RequiredFieldMissing(( - "login must be a dictionary with keys " - "'unique_id'." - )) response = self._requester.request( - 'POST', - 'accounts/{}/logins'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'accounts/{}/analytics/current/grades'.format(self.id) ) - return Login(self._requester, response.json()) + return response.json() - def get_department_level_participation_data_with_given_term(self, term_id): + def get_department_level_grade_data_with_given_term(self, term_id): """ - Return page view hits all available or concluded courses in the given term + Return the distribution of all available or concluded grades with the given term - :calls: `GET /api/v1/accounts/:account_id/analytics/terms/:term_id/activity \ - `_ + :calls: `GET /api/v1/accounts/:account_id/analytics/terms/:term_id/grades \ + `_ :param term_id: The ID of the term, or the strings "current" or "completed" :type term_id: int or str @@ -858,49 +779,46 @@ def get_department_level_participation_data_with_given_term(self, term_id): """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/terms/{}/activity'.format(self.id, term_id) + 'GET', 'accounts/{}/analytics/terms/{}/grades'.format(self.id, term_id) ) return response.json() - def get_department_level_participation_data_current(self): + def get_department_level_participation_data_completed(self): """ - Return page view hits all available courses in the default term + Return page view hits all concluded courses in the default term - :calls: `GET /api/v1/accounts/:account_id/analytics/current/activity \ + :calls: `GET /api/v1/accounts/:account_id/analytics/completed/activity \ `_ :rtype: dict """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/current/activity'.format(self.id) + 'GET', 'accounts/{}/analytics/completed/activity'.format(self.id) ) return response.json() - def get_department_level_participation_data_completed(self): + def get_department_level_participation_data_current(self): """ - Return page view hits all concluded courses in the default term + Return page view hits all available courses in the default term - :calls: `GET /api/v1/accounts/:account_id/analytics/completed/activity \ + :calls: `GET /api/v1/accounts/:account_id/analytics/current/activity \ `_ :rtype: dict """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/completed/activity'.format(self.id) + 'GET', 'accounts/{}/analytics/current/activity'.format(self.id) ) return response.json() - def get_department_level_grade_data_with_given_term(self, term_id): + def get_department_level_participation_data_with_given_term(self, term_id): """ - Return the distribution of all available or concluded grades with the given term + Return page view hits all available or concluded courses in the given term - :calls: `GET /api/v1/accounts/:account_id/analytics/terms/:term_id/grades \ - `_ + :calls: `GET /api/v1/accounts/:account_id/analytics/terms/:term_id/activity \ + `_ :param term_id: The ID of the term, or the strings "current" or "completed" :type term_id: int or str @@ -909,40 +827,37 @@ def get_department_level_grade_data_with_given_term(self, term_id): """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/terms/{}/grades'.format(self.id, term_id) + 'GET', 'accounts/{}/analytics/terms/{}/activity'.format(self.id, term_id) ) return response.json() - def get_department_level_grade_data_current(self): + def get_department_level_statistics_completed(self): """ - Return the distribution of all available grades in the default term + Return all available numeric statistics about the department in the default term - :calls: `GET /api/v1/accounts/:account_id/analytics/current/grades \ - `_ + :calls: `GET /api/v1/accounts/:account_id/analytics/current/statistics \ + `_ :rtype: dict """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/current/grades'.format(self.id) + 'GET', 'accounts/{}/analytics/completed/statistics'.format(self.id) ) return response.json() - def get_department_level_grade_data_completed(self): + def get_department_level_statistics_current(self): """ - Return the distribution of all concluded grades in the default term + Return all available numeric statistics about the department in the default term - :calls: `GET /api/v1/accounts/:account_id/analytics/completed/grades \ - `_ + :calls: `GET /api/v1/accounts/:account_id/analytics/current/statistics \ + `_ :rtype: dict """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/completed/grades'.format(self.id) + 'GET', 'accounts/{}/analytics/current/statistics'.format(self.id) ) return response.json() @@ -960,189 +875,214 @@ def get_department_level_statistics_with_given_term(self, term_id): """ response = self._requester.request( - 'GET', - 'accounts/{}/analytics/terms/{}/statistics'.format(self.id, term_id) + 'GET', 'accounts/{}/analytics/terms/{}/statistics'.format(self.id, term_id) ) return response.json() - def get_department_level_statistics_current(self): + def get_enrollment(self, enrollment, **kwargs): """ - Return all available numeric statistics about the department in the default term + Get an enrollment object by ID. - :calls: `GET /api/v1/accounts/:account_id/analytics/current/statistics \ - `_ + :calls: `GET /api/v1/accounts/:account_id/enrollments/:id \ + `_ - :rtype: dict + :param enrollment: The object or ID of the enrollment to retrieve. + :type enrollment: :class:`canvasapi.enrollment.Enrollment` or int + + :rtype: :class:`canvasapi.enrollment.Enrollment` """ + from canvasapi.enrollment import Enrollment + + enrollment_id = obj_or_id(enrollment, "enrollment", (Enrollment,)) response = self._requester.request( 'GET', - 'accounts/{}/analytics/current/statistics'.format(self.id) + 'accounts/{}/enrollments/{}'.format(self.id, enrollment_id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() + return Enrollment(self._requester, response.json()) - def get_department_level_statistics_completed(self): + def get_enrollment_terms(self, **kwargs): """ - Return all available numeric statistics about the department in the default term + List enrollment terms for a context. - :calls: `GET /api/v1/accounts/:account_id/analytics/current/statistics \ - `_ + :calls: `GET /api/v1/accounts/:account_id/terms \ + `_ - :rtype: dict + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.enrollment_term.EnrollmentTerm` """ + from canvasapi.enrollment_term import EnrollmentTerm - response = self._requester.request( + return PaginatedList( + EnrollmentTerm, + self._requester, 'GET', - 'accounts/{}/analytics/completed/statistics'.format(self.id) + 'accounts/{}/terms'.format(self.id), + {'account_id': self.id}, + _root='enrollment_terms', + _kwargs=combine_kwargs(**kwargs), ) - return response.json() - def add_authentication_providers(self, **kwargs): + def get_external_tool(self, tool): """ - Add external authentication providers for the account + :calls: `GET /api/v1/accounts/:account_id/external_tools/:external_tool_id \ + `_ - :calls: `POST /api/v1/accounts/:account_id/authentication_providers \ - `_ + :param tool: The object or ID of the tool + :type tool: :class:`canvasapi.external_tool.ExternalTool` or int - :rtype: :class:`canvasapi.authentication_provider.AuthenticationProvider` + :rtype: :class:`canvasapi.external_tool.ExternalTool` """ - from canvasapi.authentication_provider import AuthenticationProvider + from canvasapi.external_tool import ExternalTool + + tool_id = obj_or_id(tool, "tool", (ExternalTool,)) response = self._requester.request( - 'POST', - 'accounts/{}/authentication_providers'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'accounts/{}/external_tools/{}'.format(self.id, tool_id) ) - authentication_providers_json = response.json() - authentication_providers_json.update({'account_id': self.id}) + tool_json = response.json() + tool_json.update({'account_id': self.id}) - return AuthenticationProvider(self._requester, authentication_providers_json) + return ExternalTool(self._requester, tool_json) - def list_authentication_providers(self, **kwargs): + def get_external_tools(self, **kwargs): """ - Return the list of authentication providers - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_authentication_providers` instead. - - :calls: `GET /api/v1/accounts/:account_id/authentication_providers \ - `_ + :calls: `GET /api/v1/accounts/:account_id/external_tools \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.authentication_provider.AuthenticationProvider` + :class:`canvasapi.external_tool.ExternalTool` """ - warnings.warn( - "`list_authentication_providers` is being deprecated and will be " - "removed in a future version. Use `get_authentication_providers` " - "instead.", - DeprecationWarning - ) + from canvasapi.external_tool import ExternalTool - return self.get_authentication_providers(**kwargs) + return PaginatedList( + ExternalTool, + self._requester, + 'GET', + 'accounts/{}/external_tools'.format(self.id), + {'account_id': self.id}, + _kwargs=combine_kwargs(**kwargs), + ) - def get_authentication_providers(self, **kwargs): + def get_grading_periods(self, **kwargs): """ - Return the list of authentication providers + Return a list of grading periods for the associated account. - :calls: `GET /api/v1/accounts/:account_id/authentication_providers \ - `_ + :calls: `GET /api/v1/accounts/:account_id/grading_periods \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.authentication_provider.AuthenticationProvider` + :class:`canvasapi.grading_period.GradingPeriod` """ - from canvasapi.authentication_provider import AuthenticationProvider return PaginatedList( - AuthenticationProvider, + GradingPeriod, self._requester, 'GET', - 'accounts/{}/authentication_providers'.format(self.id), + 'accounts/{}/grading_periods'.format(self.id), {'account_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _root="grading_periods", + kwargs=combine_kwargs(**kwargs), ) - def get_authentication_provider(self, authentication_provider, **kwargs): + def get_grading_standards(self, **kwargs): """ - Get the specified authentication provider - - :calls: `GET /api/v1/accounts/:account_id/authentication_providers/:id \ - `_ + Get a PaginatedList of the grading standards available for the account. - :param authentication_provider: The object or ID of the authentication provider - :type authentication_provider: - :class:`canvasapi.authentication_provider.AuthenticationProvider` or int + :calls: `GET /api/v1/accounts/:account_id/grading_standards \ + `_ - :rtype: :class:`canvasapi.authentication_provider.AuthenticationProvider` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.grading_standards.GradingStandard` """ - from canvasapi.authentication_provider import AuthenticationProvider - authentication_providers_id = obj_or_id( - authentication_provider, "authentication provider", ( - AuthenticationProvider, - ) - ) - response = self._requester.request( + return PaginatedList( + GradingStandard, + self._requester, 'GET', - 'accounts/{}/authentication_providers/{}'.format(self.id, authentication_providers_id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/%s/grading_standards' % (self.id), + _kwargs=combine_kwargs(**kwargs), ) - return AuthenticationProvider(self._requester, response.json()) - - def show_account_auth_settings(self, **kwargs): + def get_group_categories(self, **kwargs): """ - Return the current state of each account level setting + List group categories for a context. - :calls: `GET /api/v1/accounts/:account_id/sso_settings \ - `_ + :calls: `GET /api/v1/accounts/:account_id/group_categories \ + `_ - :rtype: :class:`canvasapi.account.SSOSettings` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.group.GroupCategory` """ + from canvasapi.group import GroupCategory - response = self._requester.request( + return PaginatedList( + GroupCategory, + self._requester, 'GET', - 'accounts/{}/sso_settings'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/group_categories'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return SSOSettings(self._requester, response.json()) - - def update_account_auth_settings(self, **kwargs): + def get_groups(self, **kwargs): """ - Return the current state of account level after updated + Return a list of active groups for the specified account. - :calls: `PUT /api/v1/accounts/:account_id/sso_settings \ - `_ + :calls: `GET /api/v1/accounts/:account_id/groups \ + `_ - :rtype: :class:`canvasapi.account.SSOSettings` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` """ + from canvasapi.group import Group - response = self._requester.request( - 'PUT', - 'accounts/{}/sso_settings'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + return PaginatedList( + Group, + self._requester, + 'GET', + 'accounts/{}/groups'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return SSOSettings(self._requester, response.json()) + def get_index_of_reports(self, report_type): + """ + Retrieve all reports that have been run for the account of a specific type. - def get_root_outcome_group(self): + :calls: `GET /api/v1/accounts/:account_id/reports/:report \ + `_ + + :param report_type: The type of report. + :type report_type: str + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.account.AccountReport` """ - Redirect to root outcome group for context + return PaginatedList( + AccountReport, + self._requester, + 'GET', + 'accounts/{}/reports/{}'.format(self.id, report_type), + ) - :calls: `GET /api/v1/accounts/:account_id/root_outcome_group \ - `_ + def get_migration_systems(self, **kwargs): + """ + Return a list of migration systems. - :returns: The OutcomeGroup of the context. - :rtype: :class:`canvasapi.outcome.OutcomeGroup` + :calls: `GET /api/v1/accounts/:account_id/content_migrations/migrators \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.content_migration.Migrator` """ - from canvasapi.outcome import OutcomeGroup + from canvasapi.content_migration import Migrator - response = self._requester.request( + return PaginatedList( + Migrator, + self._requester, 'GET', - 'accounts/{}/root_outcome_group'.format(self.id) + 'accounts/{}/content_migrations/migrators'.format(self.id), + {'account_id': self.id}, + _kwargs=combine_kwargs(**kwargs), ) - return OutcomeGroup(self._requester, response.json()) def get_outcome_group(self, group): """ @@ -1161,8 +1101,7 @@ def get_outcome_group(self, group): outcome_group_id = obj_or_id(group, "outcome group", (OutcomeGroup,)) response = self._requester.request( - 'GET', - 'accounts/{}/outcome_groups/{}'.format(self.id, outcome_group_id) + 'GET', 'accounts/{}/outcome_groups/{}'.format(self.id, outcome_group_id) ) return OutcomeGroup(self._requester, response.json()) @@ -1184,307 +1123,165 @@ def get_outcome_groups_in_context(self): OutcomeGroup, self._requester, 'GET', - 'accounts/{}/outcome_groups'.format(self.id) - ) - - def get_all_outcome_links_in_context(self): - """ - Get all outcome links for context - BETA - - :calls: `GET /api/v1/accounts/:account_id/outcome_group_links \ - `_ - - :returns: Paginated List of OutcomesLinks in the context. - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.outcome.OutcomeLink` - """ - from canvasapi.outcome import OutcomeLink - - return PaginatedList( - OutcomeLink, - self._requester, - 'GET', - 'accounts/{}/outcome_group_links'.format(self.id) - ) - - def add_grading_standards(self, title, grading_scheme_entry, **kwargs): - """ - Create a new grading standard for the account. - - :calls: `POST /api/v1/accounts/:account_id/grading_standards \ - `_ - - :param title: The title for the Grading Standard - :type title: str - :param grading_scheme: A list of dictionaries containing keys for "name" and "value" - :type grading_scheme: list[dict] - :rtype: :class:`canvasapi.grading_standards.GradingStandard` - """ - if not isinstance(grading_scheme_entry, list) or len(grading_scheme_entry) <= 0: - raise ValueError("Param `grading_scheme_entry` must be a non-empty list.") - - for entry in grading_scheme_entry: - if not isinstance(entry, dict): - raise ValueError("grading_scheme_entry must consist of dictionaries.") - if "name" not in entry or "value" not in entry: - raise ValueError("Dictionaries with keys 'name' and 'value' are required.") - kwargs["grading_scheme_entry"] = grading_scheme_entry - - response = self._requester.request( - 'POST', - 'accounts/%s/grading_standards' % (self.id), - title=title, - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/outcome_groups'.format(self.id), ) - return GradingStandard(self._requester, response.json()) - - def get_grading_standards(self, **kwargs): - """ - Get a PaginatedList of the grading standards available for the account. - - :calls: `GET /api/v1/accounts/:account_id/grading_standards \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.grading_standards.GradingStandard` + def get_outcome_import_status(self, outcome_import, **kwargs): """ + Get the status of an already created Outcome import. + Pass 'latest' for the outcome import id for the latest import. - return PaginatedList( - GradingStandard, - self._requester, - 'GET', - 'accounts/%s/grading_standards' % (self.id), - _kwargs=combine_kwargs(**kwargs) - ) - - def get_single_grading_standard(self, grading_standard_id, **kwargs): - """ - Get a single grading standard from the account. + :calls: `GET /api/v1/accounts/:account_id/outcome_imports/:id \ + `_ - :calls: `GET /api/v1/accounts/:account_id/grading_standards/:grading_standard_id \ - `_ + :param outcome_import: The outcome import object or ID to get the status of. + :type outcome_import: :class:`canvasapi.outcome_import.OutcomeImport`, + int, or string: "latest" - :param grading_standard_id: The grading standard id - :type grading_standard_id: int - :rtype: :class:`canvasapi.grading_standards.GradingStandard` + :rtype: :class:`canvasapi.outcome_import.OutcomeImport` """ + if outcome_import == "latest": + outcome_import_id = "latest" + else: + outcome_import_id = obj_or_id( + outcome_import, "outcome_import", (OutcomeImport,) + ) response = self._requester.request( "GET", - 'accounts/%s/grading_standards/%d' % (self.id, grading_standard_id), - _kwargs=combine_kwargs(**kwargs) - ) - return GradingStandard(self._requester, response.json()) - - def get_rubric(self, rubric_id, **kwargs): - """ - Get a single rubric, based on rubric id. - - :calls: `GET /api/v1/accounts/:account_id/rubrics/:id \ - `_ - - :param rubric_id: The ID of the rubric. - :type rubric_id: int - :rtype: :class:`canvasapi.rubric.Rubric` - """ - response = self._requester.request( - 'GET', - 'accounts/%s/rubrics/%s' % (self.id, rubric_id), - _kwargs=combine_kwargs(**kwargs) + "accounts/{}/outcome_imports/{}".format(self.id, outcome_import_id), + _kwargs=combine_kwargs(**kwargs), ) - return Rubric(self._requester, response.json()) - - def list_rubrics(self, **kwargs): - """ - Get the paginated list of active rubrics for the current account. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.account.Account.get_rubrics` instead. - - :calls: `GET /api/v1/accounts/:account_id/rubrics \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.rubric.Rubric` - """ - warnings.warn( - "`list_rubrics` is being deprecated and will be removed in a " - "future version. Use `get_rubrics` instead.", - DeprecationWarning - ) + response_json = response.json() + response_json.update({"account_id": self.id}) - return self.get_rubrics(**kwargs) + return OutcomeImport(self._requester, response_json) - def get_rubrics(self, **kwargs): + def get_reports(self): """ - Get the paginated list of active rubrics for the current account. + Return a list of reports for the current context. - :calls: `GET /api/v1/accounts/:account_id/rubrics \ - `_ + :calls: `GET /api/v1/accounts/:account_id/reports \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.rubric.Rubric` + :class:`canvasapi.account.AccountReport` """ return PaginatedList( - Rubric, - self._requester, - 'GET', - 'accounts/%s/rubrics' % (self.id), - _kwargs=combine_kwargs(**kwargs) + AccountReport, self._requester, 'GET', 'accounts/{}/reports'.format(self.id) ) - def create_content_migration(self, migration_type, **kwargs): + def get_role(self, role): """ - Create a content migration. + Retrieve a role by ID. - :calls: `POST /api/v1/accounts/:account_id/content_migrations \ - `_ + :calls: `GET /api/v1/accounts/:account_id/roles/:id \ + `_ - :param migration_type: The migrator type to use in this migration - :type migration_type: str or :class:`canvasapi.content_migration.Migrator` + :param role: The object or ID of the role. + :type role: :class:`canvasapi.account.Role` or int - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :rtype: :class:`canvasapi.account.Role` """ - from canvasapi.content_migration import ContentMigration, Migrator - - if isinstance(migration_type, Migrator): - kwargs['migration_type'] = migration_type.type - elif isinstance(migration_type, string_types): - kwargs['migration_type'] = migration_type - else: - raise TypeError('Parameter migration_type must be of type Migrator or str') + role_id = obj_or_id(role, "role", (Role,)) response = self._requester.request( - 'POST', - 'accounts/{}/content_migrations'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'accounts/{}/roles/{}'.format(self.id, role_id) ) + return Role(self._requester, response.json()) - response_json = response.json() - response_json.update({'account_id': self.id}) - - return ContentMigration(self._requester, response_json) - - def get_content_migration(self, content_migration, **kwargs): + def get_roles(self, **kwargs): """ - Retrive a content migration by its ID - - :calls: `GET /api/v1/accounts/:account_id/content_migrations/:id \ - `_ + List the roles available to an account. - :param content_migration: The object or ID of the content migration to retrieve. - :type contnet_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + :calls: `GET /api/v1/accounts/:account_id/roles \ + `_ - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.account.Role` """ - from canvasapi.content_migration import ContentMigration - migration_id = obj_or_id(content_migration, "content_migration", (ContentMigration,)) - - response = self._requester.request( + return PaginatedList( + Role, + self._requester, 'GET', - 'accounts/{}/content_migrations/{}'.format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/roles'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({'account_id': self.id}) - - return ContentMigration(self._requester, response_json) - - def get_content_migrations(self, **kwargs): + def get_root_outcome_group(self): """ - List content migrations that the current account can view or manage. + Redirect to root outcome group for context - :calls: `GET /api/v1/accounts/:account_id/content_migrations/ \ - `_ + :calls: `GET /api/v1/accounts/:account_id/root_outcome_group \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.ContentMigration` + :returns: The OutcomeGroup of the context. + :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ - from canvasapi.content_migration import ContentMigration + from canvasapi.outcome import OutcomeGroup - return PaginatedList( - ContentMigration, - self._requester, - 'GET', - 'accounts/{}/content_migrations'.format(self.id), - {'account_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + response = self._requester.request( + 'GET', 'accounts/{}/root_outcome_group'.format(self.id) ) + return OutcomeGroup(self._requester, response.json()) - def get_migration_systems(self, **kwargs): + def get_rubric(self, rubric_id, **kwargs): """ - Return a list of migration systems. + Get a single rubric, based on rubric id. - :calls: `GET /api/v1/accounts/:account_id/content_migrations/migrators \ - `_ + :calls: `GET /api/v1/accounts/:account_id/rubrics/:id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.Migrator` + :param rubric_id: The ID of the rubric. + :type rubric_id: int + :rtype: :class:`canvasapi.rubric.Rubric` """ - from canvasapi.content_migration import Migrator - - return PaginatedList( - Migrator, - self._requester, + response = self._requester.request( 'GET', - 'accounts/{}/content_migrations/migrators'.format(self.id), - {'account_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + 'accounts/%s/rubrics/%s' % (self.id, rubric_id), + _kwargs=combine_kwargs(**kwargs), ) - def get_admins(self, **kwargs): + return Rubric(self._requester, response.json()) + + def get_rubrics(self, **kwargs): """ - Get the paginated list of admins for the current account. + Get the paginated list of active rubrics for the current account. - :calls: `GET /api/v1/accounts/:account_id/admins \ - `_ + :calls: `GET /api/v1/accounts/:account_id/rubrics \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.account.Admin` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.rubric.Rubric` """ - return PaginatedList( - Admin, + Rubric, self._requester, 'GET', - 'accounts/{}/admins'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/%s/rubrics' % (self.id), + _kwargs=combine_kwargs(**kwargs), ) - def create_sis_import(self, attachment, **kwargs): + def get_single_grading_standard(self, grading_standard_id, **kwargs): """ - Create a new SIS import for the current account. - - :calls: `POST /api/v1/accounts/:account_id/sis_imports \ - `_ + Get a single grading standard from the account. - :param attachment: A file handler or path of the file to import. - :type attachment: file or str + :calls: `GET /api/v1/accounts/:account_id/grading_standards/:grading_standard_id \ + `_ - :rtype: :class:`canvasapi.sis_import.SisImport` + :param grading_standard_id: The grading standard id + :type grading_standard_id: int + :rtype: :class:`canvasapi.grading_standards.GradingStandard` """ - attachment, is_path = file_or_path(attachment) - - try: - response = self._requester.request( - 'POST', - 'accounts/{}/sis_imports'.format(self.id), - file={'attachment': attachment}, - _kwargs=combine_kwargs(**kwargs) - ) - - response_json = response.json() - response_json.update({'account_id': self.id}) - - return SisImport(self._requester, response_json) - finally: - if is_path: - attachment.close() + response = self._requester.request( + "GET", + 'accounts/%s/grading_standards/%d' % (self.id, grading_standard_id), + _kwargs=combine_kwargs(**kwargs), + ) + return GradingStandard(self._requester, response.json()) def get_sis_import(self, sis_import, **kwargs): """ @@ -1503,7 +1300,7 @@ def get_sis_import(self, sis_import, **kwargs): response = self._requester.request( 'GET', 'accounts/{}/sis_imports/{}'.format(self.id, sis_import_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -1529,7 +1326,7 @@ def get_sis_imports(self, **kwargs): 'accounts/{}/sis_imports'.format(self.id), {'account_id': self.id}, _root='sis_imports', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_sis_imports_running(self, **kwargs): @@ -1550,51 +1347,94 @@ def get_sis_imports_running(self, **kwargs): 'accounts/{}/sis_imports/importing'.format(self.id), {'account_id': self.id}, _root='sis_imports', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) - def abort_sis_imports_pending(self, **kwargs): + def get_subaccounts(self, recursive=False): """ - Aborts all pending (created, but not processed or processing) - SIS imports for the current account. + List accounts that are sub-accounts of the given account. - :calls: `PUT /api/v1/accounts/:account_id/sis_imports/abort_all_pending \ - `_ + :calls: `GET /api/v1/accounts/:account_id/sub_accounts \ + `_ - :returns: True if the API responds with aborted=True, False otherwise. - :rtype: bool + :param recursive: If true, the entire account tree underneath this account will \ + be returned. If false, only direct sub-accounts of this account will be returned. + :type recursive: bool + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.account.Account` """ - response = self._requester.request( - 'PUT', - 'accounts/{}/sis_imports/abort_all_pending'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + return PaginatedList( + Account, + self._requester, + 'GET', + 'accounts/{}/sub_accounts'.format(self.id), + recursive=recursive, ) - return response.json().get('aborted', False) + def get_user_logins(self, **kwargs): + """ + Given a user ID, return that user's logins for the given account. - def create_admin(self, user, **kwargs): + :calls: `GET /api/v1/accounts/:account_id/logins \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.login.Login` """ - Flag an existing user as an admin of the current account. + from canvasapi.login import Login - :calls: `POST /api/v1/accounts/:account_id/admins \ - `_ + return PaginatedList( + Login, + self._requester, + 'GET', + 'accounts/{}/logins'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) - :param user: The user object or ID to promote to admin. + def get_user_notifications(self, user): + """ + Return a list of all global notifications in the account for + this user. Any notifications that have been closed by the user + will not be returned. + + :calls: `GET /api/v1/accounts/:account_id/users/:user_id/account_notifications \ + `_ + + :param user: The user object or ID to retrieve notifications for. :type user: :class:`canvasapi.user.User` or int - :rtype: :class:`canvasapi.account.Admin` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.account.AccountNotification` + """ + from canvasapi.user import User + + user_id = obj_or_id(user, "user", (User,)) + + return PaginatedList( + AccountNotification, + self._requester, + 'GET', + 'accounts/{}/users/{}/account_notifications'.format(self.id, user_id), + ) + + def get_users(self, **kwargs): + """ + Retrieve a list of users associated with this account. + + :calls: `GET /api/v1/accounts/:account_id/users \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` """ from canvasapi.user import User - user_id = obj_or_id(user, "user", (User,)) - kwargs['user_id'] = user_id - - response = self._requester.request( - 'POST', - 'accounts/{}/admins'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + return PaginatedList( + User, + self._requester, + 'GET', + 'accounts/{}/users'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return Admin(self._requester, response.json()) def import_outcome(self, attachment, **kwargs): """ @@ -1627,113 +1467,263 @@ def import_outcome(self, attachment, **kwargs): if is_path: attachment.close() - def get_outcome_import_status(self, outcome_import, **kwargs): + def list_authentication_providers(self, **kwargs): """ - Get the status of an already created Outcome import. - Pass 'latest' for the outcome import id for the latest import. + Return the list of authentication providers - :calls: `GET /api/v1/accounts/:account_id/outcome_imports/:id \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_authentication_providers` instead. - :param outcome_import: The outcome import object or ID to get the status of. - :type outcome_import: :class:`canvasapi.outcome_import.OutcomeImport`, - int, or string: "latest" + :calls: `GET /api/v1/accounts/:account_id/authentication_providers \ + `_ - :rtype: :class:`canvasapi.outcome_import.OutcomeImport` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.authentication_provider.AuthenticationProvider` """ - if outcome_import == "latest": - outcome_import_id = "latest" - else: - outcome_import_id = obj_or_id( - outcome_import, "outcome_import", (OutcomeImport,) - ) + warnings.warn( + "`list_authentication_providers` is being deprecated and will be " + "removed in a future version. Use `get_authentication_providers` " + "instead.", + DeprecationWarning, + ) - response = self._requester.request( - "GET", - "accounts/{}/outcome_imports/{}".format(self.id, outcome_import_id), - _kwargs=combine_kwargs(**kwargs), + return self.get_authentication_providers(**kwargs) + + def list_enrollment_terms(self, **kwargs): + """ + List enrollment terms for a context. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_enrollment_terms` instead. + + :calls: `GET /api/v1/accounts/:account_id/terms \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.enrollment_term.EnrollmentTerm` + """ + warnings.warn( + "`list_enrollment_terms` is being deprecated and will be removed " + "in a future version. Use `get_enrollment_terms` instead", + DeprecationWarning, ) - response_json = response.json() - response_json.update({"account_id": self.id}) + return self.get_enrollment_terms(**kwargs) - return OutcomeImport(self._requester, response_json) + def list_group_categories(self, **kwargs): + """ + List group categories for a context. - def get_grading_periods(self, **kwargs): + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_group_categories` instead. + + :calls: `GET /api/v1/accounts/:account_id/group_categories \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.group.GroupCategory` """ - Return a list of grading periods for the associated account. + warnings.warn( + "`list_group_categories` is being deprecated and will be removed " + "in a future version. Use `get_group_categories` instead", + DeprecationWarning, + ) - :calls: `GET /api/v1/accounts/:account_id/grading_periods \ - `_ + return self.get_group_categories(**kwargs) + + def list_groups(self, **kwargs): + """ + Return a list of active groups for the specified account. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_groups` instead. + + :calls: `GET /api/v1/accounts/:account_id/groups \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + """ + warnings.warn( + "`list_groups` is being deprecated and will be removed in a future version." + " Use `get_groups` instead", + DeprecationWarning, + ) + + return self.get_groups(**kwargs) + + def list_roles(self, **kwargs): + """ + List the roles available to an account. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_roles` instead. + + :calls: `GET /api/v1/accounts/:account_id/roles \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.grading_period.GradingPeriod` + :class:`canvasapi.account.Role` + """ + warnings.warn( + "`list_roles` is being deprecated and will be removed in a future version." + " Use `get_roles` instead", + DeprecationWarning, + ) + + return self.get_roles(**kwargs) + + def list_rubrics(self, **kwargs): """ + Get the paginated list of active rubrics for the current account. - return PaginatedList( - GradingPeriod, - self._requester, - 'GET', - 'accounts/{}/grading_periods'.format(self.id), - {'account_id': self.id}, - _root="grading_periods", - kwargs=combine_kwargs(**kwargs) + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_rubrics` instead. + + :calls: `GET /api/v1/accounts/:account_id/rubrics \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.rubric.Rubric` + """ + warnings.warn( + "`list_rubrics` is being deprecated and will be removed in a " + "future version. Use `get_rubrics` instead.", + DeprecationWarning, ) - def delete_grading_period(self, grading_period): + return self.get_rubrics(**kwargs) + + def list_user_logins(self, **kwargs): """ - Delete a grading period for an account. + Given a user ID, return that user's logins for the given account. - :calls: `DELETE /api/v1/accounts/:account_id/grading_periods/:id \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.account.Account.get_user_logins` instead. - :param grading_period: The GradingPeriod object or ID to delete. - :type grading_period: :class:`canvasapi.grading_period.GradingPeriod` or int + :calls: `GET /api/v1/accounts/:account_id/logins \ + `_ - :returns: True if the grading period was deleted, False otherwise. + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.login.Login` + """ + warnings.warn( + "`list_user_logins` is being deprecated and will be removed in a " + "future version. Use `get_user_logins` instead", + DeprecationWarning, + ) + + return self.get_user_logins(**kwargs) + + def show_account_auth_settings(self, **kwargs): + """ + Return the current state of each account level setting + + :calls: `GET /api/v1/accounts/:account_id/sso_settings \ + `_ + + :rtype: :class:`canvasapi.account.SSOSettings` + """ + + response = self._requester.request( + 'GET', + 'accounts/{}/sso_settings'.format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + return SSOSettings(self._requester, response.json()) + + def update(self, **kwargs): + """ + Update an existing account. + + :calls: `PUT /api/v1/accounts/:id \ + `_ + + :returns: True if the account was updated, False otherwise. :rtype: bool """ + response = self._requester.request( + 'PUT', 'accounts/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + ) + + if 'name' in response.json(): + super(Account, self).set_attributes(response.json()) + return True + else: + return False + + def update_account_auth_settings(self, **kwargs): + """ + Return the current state of account level after updated + + :calls: `PUT /api/v1/accounts/:account_id/sso_settings \ + `_ - grading_period_id = obj_or_id(grading_period, "grading_period", (GradingPeriod,)) + :rtype: :class:`canvasapi.account.SSOSettings` + """ response = self._requester.request( - 'DELETE', - 'accounts/{}/grading_periods/{}'.format(self.id, grading_period_id), + 'PUT', + 'accounts/{}/sso_settings'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json().get('delete') + return SSOSettings(self._requester, response.json()) + + def update_role(self, role, **kwargs): + """ + Update permissions for an existing role. + + :calls: `PUT /api/v1/accounts/:account_id/roles/:id \ + `_ + + :param role: The object or ID of the role. + :type role: :class:`canvasapi.account.Role` or int + + :rtype: :class:`canvasapi.account.Role` + """ + role_id = obj_or_id(role, "role", (Role,)) + + response = self._requester.request( + 'PUT', + 'accounts/{}/roles/{}'.format(self.id, role_id), + _kwargs=combine_kwargs(**kwargs), + ) + return Role(self._requester, response.json()) @python_2_unicode_compatible class AccountNotification(CanvasObject): - def __str__(self): # pragma: no cover return "{}".format(self.subject) @python_2_unicode_compatible class AccountReport(CanvasObject): - def __str__(self): # pragma: no cover return "{} ({})".format(self.report, self.id) @python_2_unicode_compatible class Role(CanvasObject): - def __str__(self): # pragma: no cover return "{} ({})".format(self.label, self.base_role_type) @python_2_unicode_compatible class SSOSettings(CanvasObject): - def __str__(self): # pragma: no cover - return"{} ({})".format(self.login_handle_name, self.change_password_url) + return "{} ({})".format(self.login_handle_name, self.change_password_url) @python_2_unicode_compatible class Admin(CanvasObject): - def __str__(self): # pragma: no cover return "{} {} ({})".format(self.user['name'], self.user['id'], self.id) diff --git a/canvasapi/appointment_group.py b/canvasapi/appointment_group.py index fa06071c..f12194db 100644 --- a/canvasapi/appointment_group.py +++ b/canvasapi/appointment_group.py @@ -9,7 +9,6 @@ @python_2_unicode_compatible class AppointmentGroup(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) @@ -25,7 +24,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'appointment_groups/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return AppointmentGroup(self._requester, response.json()) @@ -51,7 +50,7 @@ def edit(self, appointment_group, **kwargs): response = self._requester.request( 'PUT', 'appointment_groups/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if 'title' in response.json(): diff --git a/canvasapi/assignment.py b/canvasapi/assignment.py index c51b626e..732ce3a4 100644 --- a/canvasapi/assignment.py +++ b/canvasapi/assignment.py @@ -16,7 +16,6 @@ @python_2_unicode_compatible class Assignment(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -32,7 +31,7 @@ def create_override(self, **kwargs): response = self._requester.request( 'POST', 'courses/{}/assignments/{}/overrides'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update(course_id=self.course_id) @@ -50,7 +49,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/assignments/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Assignment(self._requester, response.json()) @@ -66,7 +65,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/assignments/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if 'name' in response.json(): @@ -88,9 +87,11 @@ def get_gradeable_students(self, **kwargs): UserDisplay, self._requester, 'GET', - 'courses/{}/assignments/{}/gradeable_students'.format(self.course_id, self.id), + 'courses/{}/assignments/{}/gradeable_students'.format( + self.course_id, self.id + ), {'course_id': self.course_id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_override(self, override, **kwargs): @@ -110,11 +111,9 @@ def get_override(self, override, **kwargs): response = self._requester.request( 'GET', 'courses/{}/assignments/{}/overrides/{}'.format( - self.course_id, - self.id, - override_id + self.course_id, self.id, override_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update(course_id=self.course_id) @@ -137,7 +136,7 @@ def get_overrides(self, **kwargs): 'GET', 'courses/{}/assignments/{}/overrides'.format(self.course_id, self.id), {'course_id': self.course_id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_peer_reviews(self, **kwargs): @@ -155,7 +154,7 @@ def get_peer_reviews(self, **kwargs): self._requester, 'GET', 'courses/{}/assignments/{}/peer_reviews'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_submission(self, user, **kwargs): @@ -174,8 +173,10 @@ def get_submission(self, user, **kwargs): response = self._requester.request( 'GET', - 'courses/{}/assignments/{}/submissions/{}'.format(self.course_id, self.id, user_id), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/assignments/{}/submissions/{}'.format( + self.course_id, self.id, user_id + ), + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update(course_id=self.course_id) @@ -198,7 +199,7 @@ def get_submissions(self, **kwargs): 'GET', 'courses/{}/assignments/{}/submissions'.format(self.course_id, self.id), {'course_id': self.course_id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def submit(self, submission, file=None, **kwargs): @@ -238,7 +239,7 @@ def submit(self, submission, file=None, **kwargs): response = self._requester.request( 'POST', 'courses/{}/assignments/{}/submissions'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update(course_id=self.course_id) @@ -259,10 +260,9 @@ def submissions_bulk_update(self, **kwargs): response = self._requester.request( 'POST', 'courses/{}/assignments/{}/submissions/update_grades'.format( - self.course_id, - self.id + self.course_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) @@ -289,9 +289,7 @@ def upload_to_submission(self, file, user='self', **kwargs): return Uploader( self._requester, 'courses/{}/assignments/{}/submissions/{}/files'.format( - self.course_id, - self.id, - user_id + self.course_id, self.id, user_id ), file, **kwargs @@ -300,7 +298,6 @@ def upload_to_submission(self, file, user='self', **kwargs): @python_2_unicode_compatible class AssignmentGroup(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -316,7 +313,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/assignment_groups/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if 'name' in response.json(): @@ -336,14 +333,13 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/assignment_groups/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return AssignmentGroup(self._requester, response.json()) @python_2_unicode_compatible class AssignmentOverride(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) @@ -360,10 +356,8 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/assignments/{}/overrides/{}'.format( - self.course_id, - self.assignment_id, - self.id - ) + self.course_id, self.assignment_id, self.id + ), ) response_json = response.json() @@ -385,10 +379,8 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/assignments/{}/overrides/{}'.format( - self.course_id, - self.assignment_id, - self.id - ) + self.course_id, self.assignment_id, self.id + ), ) response_json = response.json() diff --git a/canvasapi/authentication_provider.py b/canvasapi/authentication_provider.py index ab44fe08..0e6253aa 100644 --- a/canvasapi/authentication_provider.py +++ b/canvasapi/authentication_provider.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class AuthenticationProvider(CanvasObject): - def __str__(self): # pragma: no cover return "{} ({})".format(self.auth_type, self.position) @@ -24,7 +23,7 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', 'accounts/{}/authentication_providers/{}'.format(self.account_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if response.json().get('auth_type'): @@ -43,6 +42,6 @@ def delete(self): """ response = self._requester.request( 'DELETE', - 'accounts/{}/authentication_providers/{}'.format(self.account_id, self.id) + 'accounts/{}/authentication_providers/{}'.format(self.account_id, self.id), ) return AuthenticationProvider(self._requester, response.json()) diff --git a/canvasapi/avatar.py b/canvasapi/avatar.py index 653951cf..867dcfdb 100644 --- a/canvasapi/avatar.py +++ b/canvasapi/avatar.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class Avatar(CanvasObject): - def __str__(self): # pragma: no cover return "{}".format(self.display_name) diff --git a/canvasapi/blueprint.py b/canvasapi/blueprint.py index 3ae44eb7..13dff0e9 100644 --- a/canvasapi/blueprint.py +++ b/canvasapi/blueprint.py @@ -9,55 +9,9 @@ @python_2_unicode_compatible class BlueprintTemplate(CanvasObject): - def __str__(self): return "{}".format(self.id) - def get_associated_courses(self, **kwargs): - """ - Return a list of courses associated with the given blueprint. - - :calls: `GET /api/v1/courses/:course_id/blueprint_templates/:template_id/ \ - associated_courses \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` - """ - from canvasapi.course import Course - - return PaginatedList( - Course, - self._requester, - 'GET', - 'courses/{}/blueprint_templates/{}/associated_courses'.format( - self.course_id, - self.id - ), - _kwargs=combine_kwargs(**kwargs) - ) - - def update_associated_courses(self, **kwargs): - """ - Add or remove new associations for the blueprint template. - - :calls: `PUT \ - /api/v1/courses/:course_id/blueprint_templates/:template_id/update_associations \ - `_ - - :returns: True if the course was added or removed, False otherwise. - :rtype: bool - """ - response = self._requester.request( - 'PUT', - 'courses/{}/blueprint_templates/{}/update_associations'.format( - self.course_id, - self.id - ), - _kwargs=combine_kwargs(**kwargs) - ) - return response.json().get("success", False) - def associated_course_migration(self, **kwargs): """ Start a migration to update content in all associated courses. @@ -71,16 +25,17 @@ def associated_course_migration(self, **kwargs): response = self._requester.request( 'POST', 'courses/{}/blueprint_templates/{}/migrations'.format( - self.course_id, - self.id + self.course_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) return BlueprintMigration(self._requester, response_json) - def change_blueprint_restrictions(self, content_type, content_id, restricted, **kwargs): + def change_blueprint_restrictions( + self, content_type, content_id, restricted, **kwargs + ): """ Set or remove restrictions on a blueprint course object. Must have all three parameters for this function call to work. @@ -105,13 +60,35 @@ def change_blueprint_restrictions(self, content_type, content_id, restricted, ** response = self._requester.request( 'PUT', 'courses/{}/blueprint_templates/{}/restrict_item'.format( - self.course_id, - self.id + self.course_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json().get("success", False) + def get_associated_courses(self, **kwargs): + """ + Return a list of courses associated with the given blueprint. + + :calls: `GET /api/v1/courses/:course_id/blueprint_templates/:template_id/ \ + associated_courses \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.Course` + """ + from canvasapi.course import Course + + return PaginatedList( + Course, + self._requester, + 'GET', + 'courses/{}/blueprint_templates/{}/associated_courses'.format( + self.course_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + def get_unsynced_changes(self, **kwargs): """ Return changes made to associated courses of a blueprint course. @@ -129,10 +106,9 @@ def get_unsynced_changes(self, **kwargs): self._requester, 'GET', 'courses/{}/blueprint_templates/{}/unsynced_changes'.format( - self.course_id, - self.id + self.course_id, self.id ), - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) def list_blueprint_migrations(self, **kwargs): @@ -152,11 +128,10 @@ def list_blueprint_migrations(self, **kwargs): self._requester, 'GET', 'courses/{}/blueprint_templates/{}/migrations'.format( - self.course_id, - self.id + self.course_id, self.id ), {'course_id': self.course_id}, - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) def show_blueprint_migration(self, migration, **kwargs): @@ -178,25 +153,39 @@ def show_blueprint_migration(self, migration, **kwargs): response = self._requester.request( 'GET', 'courses/{}/blueprint_templates/{}/migrations/{}'.format( - self.course_id, - self.id, - migration_id + self.course_id, self.id, migration_id ), - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) return BlueprintMigration(self._requester, response_json) + def update_associated_courses(self, **kwargs): + """ + Add or remove new associations for the blueprint template. + + :calls: `PUT \ + /api/v1/courses/:course_id/blueprint_templates/:template_id/update_associations \ + `_ + + :returns: True if the course was added or removed, False otherwise. + :rtype: bool + """ + response = self._requester.request( + 'PUT', + 'courses/{}/blueprint_templates/{}/update_associations'.format( + self.course_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + return response.json().get("success", False) + @python_2_unicode_compatible class BlueprintMigration(CanvasObject): - def __str__(self): - return "{} {}".format( - self.id, - self.template_id - ) + return "{} {}".format(self.id, self.template_id) def get_details(self, **kwargs): """ @@ -216,11 +205,9 @@ def get_details(self, **kwargs): self._requester, 'GET', 'courses/{}/blueprint_templates/{}/migrations/{}/details'.format( - self.course_id, - self.template_id, - self.id + self.course_id, self.template_id, self.id ), - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) def get_import_details(self, **kwargs): @@ -241,32 +228,22 @@ def get_import_details(self, **kwargs): self._requester, 'GET', 'courses/{}/blueprint_subscriptions/{}/migrations/{}/details'.format( - self.course_id, - self.subscription_id, - self.id + self.course_id, self.subscription_id, self.id ), - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) @python_2_unicode_compatible class ChangeRecord(CanvasObject): - def __str__(self): # pragma: no cover - return "{} {}".format( - self.id, - self.template_id - ) + return "{} {}".format(self.id, self.template_id) @python_2_unicode_compatible class BlueprintSubscription(CanvasObject): - def __str__(self): - return "{} {}".format( - self.id, - self.template_id - ) + return "{} {}".format(self.id, self.template_id) def list_blueprint_imports(self, **kwargs): """ @@ -286,11 +263,10 @@ def list_blueprint_imports(self, **kwargs): self._requester, 'GET', 'courses/{}/blueprint_subscriptions/{}/migrations'.format( - self.course_id, - self.id + self.course_id, self.id ), {'course_id': self.id}, - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) def show_blueprint_import(self, migration, **kwargs): @@ -312,11 +288,9 @@ def show_blueprint_import(self, migration, **kwargs): response = self._requester.request( 'GET', 'courses/{}/blueprint_subscriptions/{}/migrations/{}'.format( - self.course_id, - self.id, - migration_id + self.course_id, self.id, migration_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) diff --git a/canvasapi/bookmark.py b/canvasapi/bookmark.py index fd8ca4db..2e046626 100644 --- a/canvasapi/bookmark.py +++ b/canvasapi/bookmark.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class Bookmark(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -22,8 +21,7 @@ def delete(self): :rtype: :class:`canvasapi.bookmark.Bookmark` """ response = self._requester.request( - 'DELETE', - 'users/self/bookmarks/{}'.format(self.id) + 'DELETE', 'users/self/bookmarks/{}'.format(self.id) ) return Bookmark(self._requester, response.json()) @@ -39,7 +37,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'users/self/bookmarks/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if 'name' in response.json() and 'url' in response.json(): diff --git a/canvasapi/calendar_event.py b/canvasapi/calendar_event.py index d643e33b..18db5b1e 100644 --- a/canvasapi/calendar_event.py +++ b/canvasapi/calendar_event.py @@ -5,7 +5,6 @@ class CalendarEvent(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) @@ -21,7 +20,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'calendar_events/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return CalendarEvent(self._requester, response.json()) @@ -37,7 +36,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'calendar_events/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if 'title' in response.json(): diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py index 680a1ba2..0037da22 100644 --- a/canvasapi/canvas.py +++ b/canvasapi/canvas.py @@ -38,27 +38,27 @@ def __init__(self, base_url, access_token): warnings.warn( "`base_url` no longer requires an API version be specified. " "Rewriting `base_url` to {}".format(new_url), - DeprecationWarning + DeprecationWarning, ) if 'http://' in base_url: warnings.warn( "Canvas may respond unexpectedly when making requests to HTTP " "URLs. If possible, please use HTTPS.", - UserWarning + UserWarning, ) if not base_url.strip(): warnings.warn( "Canvas needs a valid URL, please provide a non-blank `base_url`.", - UserWarning + UserWarning, ) if '://' not in base_url: warnings.warn( "An invalid `base_url` for the Canvas API Instance was used. " "Please provide a valid HTTP or HTTPS URL if possible.", - UserWarning + UserWarning, ) base_url = new_url + '/api/v1/' @@ -75,9 +75,7 @@ def create_account(self, **kwargs): :rtype: :class:`canvasapi.account.Account` """ response = self.__requester.request( - 'POST', - 'accounts', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'accounts', _kwargs=combine_kwargs(**kwargs) ) return Account(self.__requester, response.json()) @@ -104,9 +102,7 @@ def get_account(self, account, use_sis_id=False, **kwargs): uri_str = 'accounts/{}' response = self.__requester.request( - 'GET', - uri_str.format(account_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', uri_str.format(account_id), _kwargs=combine_kwargs(**kwargs) ) return Account(self.__requester, response.json()) @@ -129,7 +125,7 @@ def get_accounts(self, **kwargs): self.__requester, 'GET', 'accounts', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_course_accounts(self): @@ -146,12 +142,7 @@ def get_course_accounts(self): :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.account.Account` """ - return PaginatedList( - Account, - self.__requester, - 'GET', - 'course_accounts', - ) + return PaginatedList(Account, self.__requester, 'GET', 'course_accounts') def get_course(self, course, use_sis_id=False, **kwargs): """ @@ -176,9 +167,7 @@ def get_course(self, course, use_sis_id=False, **kwargs): uri_str = 'courses/{}' response = self.__requester.request( - 'GET', - uri_str.format(course_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) ) return Course(self.__requester, response.json()) @@ -209,10 +198,7 @@ def get_user(self, user, id_type=None): user_id = obj_or_id(user, "user", (User,)) uri = 'users/{}'.format(user_id) - response = self.__requester.request( - 'GET', - uri - ) + response = self.__requester.request('GET', uri) return User(self.__requester, response.json()) def get_current_user(self): @@ -229,11 +215,7 @@ def get_courses(self, **kwargs): :class:`canvasapi.course.Course` """ return PaginatedList( - Course, - self.__requester, - 'GET', - 'courses', - _kwargs=combine_kwargs(**kwargs) + Course, self.__requester, 'GET', 'courses', _kwargs=combine_kwargs(**kwargs) ) def get_activity_stream_summary(self): @@ -245,10 +227,7 @@ def get_activity_stream_summary(self): :rtype: dict """ - response = self.__requester.request( - 'GET', - 'users/self/activity_stream/summary' - ) + response = self.__requester.request('GET', 'users/self/activity_stream/summary') return response.json() def get_todo_items(self): @@ -260,10 +239,7 @@ def get_todo_items(self): :rtype: dict """ - response = self.__requester.request( - 'GET', - 'users/self/todo' - ) + response = self.__requester.request('GET', 'users/self/todo') return response.json() def get_upcoming_events(self): @@ -276,10 +252,7 @@ def get_upcoming_events(self): :rtype: dict """ - response = self.__requester.request( - 'GET', - 'users/self/upcoming_events' - ) + response = self.__requester.request('GET', 'users/self/upcoming_events') return response.json() def get_course_nicknames(self): @@ -295,10 +268,7 @@ def get_course_nicknames(self): from canvasapi.course import CourseNickname return PaginatedList( - CourseNickname, - self.__requester, - 'GET', - 'users/self/course_nicknames' + CourseNickname, self.__requester, 'GET', 'users/self/course_nicknames' ) def get_course_nickname(self, course): @@ -318,8 +288,7 @@ def get_course_nickname(self, course): course_id = obj_or_id(course, "course", (Course,)) response = self.__requester.request( - 'GET', - 'users/self/course_nicknames/{}'.format(course_id) + 'GET', 'users/self/course_nicknames/{}'.format(course_id) ) return CourseNickname(self.__requester, response.json()) @@ -346,9 +315,7 @@ def get_section(self, section, use_sis_id=False, **kwargs): uri_str = 'sections/{}' response = self.__requester.request( - 'GET', - uri_str.format(section_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', uri_str.format(section_id), _kwargs=combine_kwargs(**kwargs) ) return Section(self.__requester, response.json()) @@ -373,9 +340,7 @@ def set_course_nickname(self, course, nickname): course_id = obj_or_id(course, "course", (Course,)) response = self.__requester.request( - 'PUT', - 'users/self/course_nicknames/{}'.format(course_id), - nickname=nickname + 'PUT', 'users/self/course_nicknames/{}'.format(course_id), nickname=nickname ) return CourseNickname(self.__requester, response.json()) @@ -391,10 +356,7 @@ def clear_course_nicknames(self): :rtype: bool """ - response = self.__requester.request( - 'DELETE', - 'users/self/course_nicknames' - ) + response = self.__requester.request('DELETE', 'users/self/course_nicknames') return response.json().get('message') == 'OK' def search_accounts(self, **kwargs): @@ -408,9 +370,7 @@ def search_accounts(self, **kwargs): :rtype: dict """ response = self.__requester.request( - 'GET', - 'accounts/search', - _kwargs=combine_kwargs(**kwargs) + 'GET', 'accounts/search', _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -424,9 +384,7 @@ def create_group(self, **kwargs): :rtype: :class:`canvasapi.group.Group` """ response = self.__requester.request( - 'POST', - 'groups', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'groups', _kwargs=combine_kwargs(**kwargs) ) return Group(self.__requester, response.json()) @@ -456,9 +414,7 @@ def get_group(self, group, use_sis_id=False, **kwargs): uri_str = 'groups/{}' response = self.__requester.request( - 'GET', - uri_str.format(group_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) ) return Group(self.__requester, response.json()) @@ -477,8 +433,7 @@ def get_group_category(self, category): category_id = obj_or_id(category, "category", (GroupCategory,)) response = self.__requester.request( - 'GET', - 'group_categories/{}'.format(category_id) + 'GET', 'group_categories/{}'.format(category_id) ) return GroupCategory(self.__requester, response.json()) @@ -504,9 +459,7 @@ def create_conversation(self, recipients, body, **kwargs): kwargs['body'] = body response = self.__requester.request( - 'POST', - 'conversations', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'conversations', _kwargs=combine_kwargs(**kwargs) ) return [Conversation(self.__requester, convo) for convo in response.json()] @@ -529,7 +482,7 @@ def get_conversation(self, conversation, **kwargs): response = self.__requester.request( 'GET', 'conversations/{}'.format(conversation_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Conversation(self.__requester, response.json()) @@ -550,7 +503,7 @@ def get_conversations(self, **kwargs): self.__requester, 'GET', 'conversations', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def conversations_mark_all_as_read(self): @@ -562,10 +515,7 @@ def conversations_mark_all_as_read(self): :rtype: `bool` """ - response = self.__requester.request( - 'POST', - 'conversations/mark_all_as_read' - ) + response = self.__requester.request('POST', 'conversations/mark_all_as_read') return response.json() == {} def conversations_unread_count(self): @@ -578,10 +528,7 @@ def conversations_unread_count(self): :returns: simple object with unread_count, example: {'unread_count': '7'} :rtype: `dict` """ - response = self.__requester.request( - 'GET', - 'conversations/unread_count' - ) + response = self.__requester.request('GET', 'conversations/unread_count') return response.json() @@ -598,10 +545,7 @@ def conversations_get_running_batches(self): :rtype: `dict` """ - response = self.__requester.request( - 'GET', - 'conversations/batches' - ) + response = self.__requester.request('GET', 'conversations/batches') return response.json() @@ -626,15 +570,14 @@ def conversations_batch_update(self, conversation_ids, event): 'star', 'unstar', 'archive', - 'destroy' + 'destroy', ] try: if event not in ALLOWED_EVENTS: raise ValueError( '{} is not a valid action. Please use one of the following: {}'.format( - event, - ','.join(ALLOWED_EVENTS) + event, ','.join(ALLOWED_EVENTS) ) ) @@ -678,9 +621,7 @@ def create_calendar_event(self, calendar_event, **kwargs): ) response = self.__requester.request( - 'POST', - 'calendar_events', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'calendar_events', _kwargs=combine_kwargs(**kwargs) ) return CalendarEvent(self.__requester, response.json()) @@ -702,7 +643,7 @@ def list_calendar_events(self, **kwargs): warnings.warn( "`list_calendar_events` is being deprecated and will be removed " "in a future version. Use `get_calendar_events` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_calendar_events(**kwargs) @@ -724,7 +665,7 @@ def get_calendar_events(self, **kwargs): self.__requester, 'GET', 'calendar_events', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_calendar_event(self, calendar_event): @@ -741,11 +682,12 @@ def get_calendar_event(self, calendar_event): """ from canvasapi.calendar_event import CalendarEvent - calendar_event_id = obj_or_id(calendar_event, "calendar_event", (CalendarEvent,)) + calendar_event_id = obj_or_id( + calendar_event, "calendar_event", (CalendarEvent,) + ) response = self.__requester.request( - 'GET', - 'calendar_events/{}'.format(calendar_event_id) + 'GET', 'calendar_events/{}'.format(calendar_event_id) ) return CalendarEvent(self.__requester, response.json()) @@ -766,7 +708,9 @@ def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs): """ from canvasapi.calendar_event import CalendarEvent - calendar_event_id = obj_or_id(calendar_event, "calendar_event", (CalendarEvent,)) + calendar_event_id = obj_or_id( + calendar_event, "calendar_event", (CalendarEvent,) + ) if participant_id: uri = 'calendar_events/{}/reservations/{}'.format( @@ -776,9 +720,7 @@ def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs): uri = 'calendar_events/{}/reservations'.format(calendar_event_id) response = self.__requester.request( - 'POST', - uri, - _kwargs=combine_kwargs(**kwargs) + 'POST', uri, _kwargs=combine_kwargs(**kwargs) ) return CalendarEvent(self.__requester, response.json()) @@ -799,7 +741,7 @@ def list_appointment_groups(self, **kwargs): warnings.warn( "`list_appointment_groups` is being deprecated and will be removed" " in a future version. Use `get_appointment_groups` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_appointment_groups(**kwargs) @@ -821,7 +763,7 @@ def get_appointment_groups(self, **kwargs): self.__requester, 'GET', 'appointment_groups', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_appointment_group(self, appointment_group): @@ -843,8 +785,7 @@ def get_appointment_group(self, appointment_group): ) response = self.__requester.request( - 'GET', - 'appointment_groups/{}'.format(appointment_group_id) + 'GET', 'appointment_groups/{}'.format(appointment_group_id) ) return AppointmentGroup(self.__requester, response.json()) @@ -864,15 +805,15 @@ def create_appointment_group(self, appointment_group, **kwargs): from canvasapi.appointment_group import AppointmentGroup if ( - isinstance(appointment_group, dict) and - 'context_codes' in appointment_group and - 'title' in appointment_group + isinstance(appointment_group, dict) + and 'context_codes' in appointment_group + and 'title' in appointment_group ): kwargs['appointment_group'] = appointment_group elif ( - isinstance(appointment_group, dict) and - 'context_codes' not in appointment_group + isinstance(appointment_group, dict) + and 'context_codes' not in appointment_group ): raise RequiredFieldMissing( "Dictionary with key 'context_codes' is missing." @@ -882,9 +823,7 @@ def create_appointment_group(self, appointment_group, **kwargs): raise RequiredFieldMissing("Dictionary with key 'title' is missing.") response = self.__requester.request( - 'POST', - 'appointment_groups', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'appointment_groups', _kwargs=combine_kwargs(**kwargs) ) return AppointmentGroup(self.__requester, response.json()) @@ -908,7 +847,7 @@ def list_user_participants(self, appointment_group, **kwargs): warnings.warn( "`list_user_participants` is being deprecated and will be removed in a future version." " Use `get_user_participants` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_user_participants(appointment_group, **kwargs) @@ -937,7 +876,7 @@ def get_user_participants(self, appointment_group, **kwargs): self.__requester, 'GET', 'appointment_groups/{}/users'.format(appointment_group_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def list_group_participants(self, appointment_group, **kwargs): @@ -959,7 +898,7 @@ def list_group_participants(self, appointment_group, **kwargs): warnings.warn( "`list_group_participants` is being deprecated and will be removed " "in a future version. Use `get_group_participants` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_group_participants(appointment_group, **kwargs) @@ -988,7 +927,7 @@ def get_group_participants(self, appointment_group, **kwargs): self.__requester, 'GET', 'appointment_groups/{}/groups'.format(appointment_group_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_file(self, file, **kwargs): @@ -1006,9 +945,7 @@ def get_file(self, file, **kwargs): file_id = obj_or_id(file, "file", (File,)) response = self.__requester.request( - 'GET', - 'files/{}'.format(file_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'files/{}'.format(file_id), _kwargs=combine_kwargs(**kwargs) ) return File(self.__requester, response.json()) @@ -1026,10 +963,7 @@ def get_folder(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request( - 'GET', - 'folders/{}'.format(folder_id) - ) + response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) return Folder(self.__requester, response.json()) def search_recipients(self, **kwargs): @@ -1047,9 +981,7 @@ def search_recipients(self, **kwargs): kwargs['search'] = ' ' response = self.__requester.request( - 'GET', - 'search/recipients', - _kwargs=combine_kwargs(**kwargs) + 'GET', 'search/recipients', _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -1064,9 +996,7 @@ def search_all_courses(self, **kwargs): :rtype: `list` """ response = self.__requester.request( - 'GET', - 'search/all_courses', - _kwargs=combine_kwargs(**kwargs) + 'GET', 'search/all_courses', _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -1086,10 +1016,7 @@ def get_outcome(self, outcome): from canvasapi.outcome import Outcome outcome_id = obj_or_id(outcome, "outcome", (Outcome,)) - response = self.__requester.request( - 'GET', - 'outcomes/{}'.format(outcome_id) - ) + response = self.__requester.request('GET', 'outcomes/{}'.format(outcome_id)) return Outcome(self.__requester, response.json()) def get_root_outcome_group(self): @@ -1104,10 +1031,7 @@ def get_root_outcome_group(self): """ from canvasapi.outcome import OutcomeGroup - response = self.__requester.request( - 'GET', - 'global/root_outcome_group' - ) + response = self.__requester.request('GET', 'global/root_outcome_group') return OutcomeGroup(self.__requester, response.json()) def get_outcome_group(self, group): @@ -1128,8 +1052,7 @@ def get_outcome_group(self, group): outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,)) response = self.__requester.request( - 'GET', - 'global/outcome_groups/{}'.format(outcome_group_id) + 'GET', 'global/outcome_groups/{}'.format(outcome_group_id) ) return OutcomeGroup(self.__requester, response.json()) @@ -1152,9 +1075,7 @@ def get_progress(self, progress, **kwargs): progress_id = obj_or_id(progress, "progress", (Progress,)) response = self.__requester.request( - 'GET', - 'progress/{}'.format(progress_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'progress/{}'.format(progress_id), _kwargs=combine_kwargs(**kwargs) ) return Progress(self.__requester, response.json()) @@ -1169,12 +1090,13 @@ def get_announcements(self, **kwargs): :class:`canvasapi.discussion_topic.DiscussionTopic` """ from canvasapi.discussion_topic import DiscussionTopic + return PaginatedList( DiscussionTopic, self.__requester, 'GET', 'announcements', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_polls(self, **kwargs): @@ -1195,7 +1117,7 @@ def get_polls(self, **kwargs): 'GET', 'polls', _root='polls', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_poll(self, poll, **kwargs): @@ -1214,9 +1136,7 @@ def get_poll(self, poll, **kwargs): poll_id = obj_or_id(poll, "poll", (Poll,)) response = self.__requester.request( - 'GET', - 'polls/{}'.format(poll_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'polls/{}'.format(poll_id), _kwargs=combine_kwargs(**kwargs) ) return Poll(self.__requester, response.json()['polls'][0]) @@ -1233,7 +1153,11 @@ def create_poll(self, poll, **kwargs): """ from canvasapi.poll import Poll - if isinstance(poll, list) and isinstance(poll[0], dict) and 'question' in poll[0]: + if ( + isinstance(poll, list) + and isinstance(poll[0], dict) + and 'question' in poll[0] + ): kwargs['poll'] = poll else: raise RequiredFieldMissing( @@ -1241,9 +1165,7 @@ def create_poll(self, poll, **kwargs): ) response = self.__requester.request( - 'POST', - 'polls', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'polls', _kwargs=combine_kwargs(**kwargs) ) return Poll(self.__requester, response.json()['polls'][0]) @@ -1264,7 +1186,7 @@ def get_planner_notes(self, **kwargs): self.__requester, 'GET', 'planner_notes', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_planner_note(self, planner_note, **kwargs): @@ -1290,10 +1212,8 @@ def get_planner_note(self, planner_note, **kwargs): response = self.__requester.request( 'GET', - 'planner_notes/{}'.format( - planner_note_id - ), - _kwargs=combine_kwargs(**kwargs) + 'planner_notes/{}'.format(planner_note_id), + _kwargs=combine_kwargs(**kwargs), ) return PlannerNote(self.__requester, response.json()) @@ -1310,9 +1230,7 @@ def create_planner_note(self, **kwargs): from canvasapi.planner import PlannerNote response = self.__requester.request( - 'POST', - 'planner_notes', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'planner_notes', _kwargs=combine_kwargs(**kwargs) ) return PlannerNote(self.__requester, response.json()) @@ -1333,7 +1251,7 @@ def get_planner_overrides(self, **kwargs): self.__requester, 'GET', 'planner/overrides', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_planner_override(self, planner_override, **kwargs): @@ -1350,11 +1268,11 @@ def get_planner_override(self, planner_override, **kwargs): """ from canvasapi.planner import PlannerOverride - if isinstance(planner_override, int) or isinstance(planner_override, PlannerOverride): + if isinstance(planner_override, int) or isinstance( + planner_override, PlannerOverride + ): planner_override_id = obj_or_id( - planner_override, - "planner_override", - (PlannerOverride,) + planner_override, "planner_override", (PlannerOverride,) ) else: raise RequiredFieldMissing( @@ -1363,10 +1281,8 @@ def get_planner_override(self, planner_override, **kwargs): response = self.__requester.request( 'GET', - 'planner/overrides/{}'.format( - planner_override_id - ), - _kwargs=combine_kwargs(**kwargs) + 'planner/overrides/{}'.format(planner_override_id), + _kwargs=combine_kwargs(**kwargs), ) return PlannerOverride(self.__requester, response.json()) @@ -1392,20 +1308,14 @@ def create_planner_override(self, plannable_type, plannable_id, **kwargs): if isinstance(plannable_type, text_type): kwargs['plannable_type'] = plannable_type else: - raise RequiredFieldMissing( - "plannable_type is required as a str." - ) + raise RequiredFieldMissing("plannable_type is required as a str.") if isinstance(plannable_id, integer_types): kwargs['plannable_id'] = plannable_id else: - raise RequiredFieldMissing( - "plannable_id is required as an int." - ) + raise RequiredFieldMissing("plannable_id is required as an int.") response = self.__requester.request( - 'POST', - 'planner/overrides', - _kwargs=combine_kwargs(**kwargs) + 'POST', 'planner/overrides', _kwargs=combine_kwargs(**kwargs) ) return PlannerOverride(self.__requester, response.json()) @@ -1426,5 +1336,5 @@ def get_epub_exports(self, **kwargs): 'GET', 'epub_exports', _root="courses", - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/canvas_object.py b/canvasapi/canvas_object.py index 6f2a26c6..5b0b8c0d 100644 --- a/canvasapi/canvas_object.py +++ b/canvasapi/canvas_object.py @@ -29,7 +29,13 @@ def __init__(self, requester, attributes): def __repr__(self): # pragma: no cover classname = self.__class__.__name__ - attrs = ', '.join(['{}={}'.format(attr, val) for attr, val in self.__dict__.items() if attr != 'attributes']) # noqa + attrs = ', '.join( + [ + '{}={}'.format(attr, val) + for attr, val in self.__dict__.items() + if attr != 'attributes' + ] + ) # noqa return '{}({})'.format(classname, attrs) def to_json(self): diff --git a/canvasapi/communication_channel.py b/canvasapi/communication_channel.py index 53af7537..3be25987 100644 --- a/canvasapi/communication_channel.py +++ b/canvasapi/communication_channel.py @@ -11,7 +11,6 @@ @python_2_unicode_compatible class CommunicationChannel(CanvasObject): - def __str__(self): return "{} ({})".format(self.address, self.id) @@ -34,7 +33,7 @@ def list_preferences(self, **kwargs): warnings.warn( "`list_preferences` is being deprecated and will be removed in a future version." " Use `get_preferences` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_preferences(**kwargs) @@ -53,10 +52,9 @@ def get_preferences(self, **kwargs): response = self._requester.request( 'GET', 'users/{}/communication_channels/{}/notification_preferences'.format( - self.user_id, - self.id + self.user_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json()['notification_preferences'] @@ -83,7 +81,7 @@ def list_preference_categories(self, **kwargs): "`list_preference_categories`" " is being deprecated and will be removed in a future version." " Use `get_preference_categories` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_preference_categories(**kwargs) @@ -103,10 +101,9 @@ def get_preference_categories(self, **kwargs): response = self._requester.request( 'GET', 'users/{}/communication_channels/{}/notification_preference_categories'.format( - self.user_id, - self.id + self.user_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json()['categories'] @@ -127,10 +124,8 @@ def get_preference(self, notification): response = self._requester.request( 'GET', 'users/{}/communication_channels/{}/notification_preferences/{}'.format( - self.user_id, - self.id, - notification - ) + self.user_id, self.id, notification + ), ) data = response.json()['notification_preferences'][0] return NotificationPreference(self._requester, data) @@ -156,10 +151,9 @@ def update_preference(self, notification, frequency, **kwargs): response = self._requester.request( 'PUT', 'users/self/communication_channels/{}/notification_preferences/{}'.format( - self.id, - notification + self.id, notification ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) data = response.json()['notification_preferences'][0] return NotificationPreference(self._requester, data) @@ -187,10 +181,9 @@ def update_preferences_by_catagory(self, category, frequency, **kwargs): response = self._requester.request( 'PUT', 'users/self/communication_channels/{}/notification_preference_categories/{}'.format( - self.id, - category + self.id, category ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json()['notification_preferences'] @@ -225,7 +218,7 @@ def update_multiple_preferences(self, notification_preferences, **kwargs): 'users/self/communication_channels/{}/notification_preferences'.format( self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json()['notification_preferences'] return False @@ -242,8 +235,7 @@ def delete(self): """ response = self._requester.request( - 'DELETE', - 'users/{}/communication_channels/{}'.format(self.user_id, self.id) + 'DELETE', 'users/{}/communication_channels/{}'.format(self.user_id, self.id) ) return response.json().get('workflow_state') == 'deleted' diff --git a/canvasapi/content_migration.py b/canvasapi/content_migration.py index 126d4020..e1f276ef 100644 --- a/canvasapi/content_migration.py +++ b/canvasapi/content_migration.py @@ -30,7 +30,8 @@ def _parent_id(self): return self.user_id else: raise ValueError( - "Content Migration does not have an account_id, course_id, group_id or user_id") + "Content Migration does not have an account_id, course_id, group_id or user_id" + ) @property def _parent_type(self): @@ -49,7 +50,8 @@ def _parent_type(self): return 'user' else: raise ValueError( - "Content Migration does not have an account_id, course_id, group_id or user_id") + "Content Migration does not have an account_id, course_id, group_id or user_id" + ) def get_migration_issue(self, migration_issue, **kwargs): """ @@ -78,23 +80,26 @@ def get_migration_issue(self, migration_issue, **kwargs): """ from canvasapi.content_migration import MigrationIssue - migration_issue_id = obj_or_id(migration_issue, "migration_issue", (MigrationIssue,)) + migration_issue_id = obj_or_id( + migration_issue, "migration_issue", (MigrationIssue,) + ) response = self._requester.request( 'GET', '{}s/{}/content_migrations/{}/migration_issues/{}'.format( - self._parent_type, - self._parent_id, - self.id, - migration_issue_id), - _kwargs=combine_kwargs(**kwargs) + self._parent_type, self._parent_id, self.id, migration_issue_id + ), + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({ - 'context_type': self._parent_type, - 'context_id': self._parent_id, - 'content_migration_id': self.id}) + response_json.update( + { + 'context_type': self._parent_type, + 'context_id': self._parent_id, + 'content_migration_id': self.id, + } + ) return MigrationIssue(self._requester, response_json) @@ -128,12 +133,14 @@ def get_migration_issues(self, **kwargs): self._requester, 'GET', '{}s/{}/content_migrations/{}/migration_issues/'.format( - self._parent_type, - self._parent_id, self.id), - {'context_type': self._parent_type, - 'context_id': self._parent_id, - 'content_migration_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + self._parent_type, self._parent_id, self.id + ), + { + 'context_type': self._parent_type, + 'context_id': self._parent_id, + 'content_migration_id': self.id, + }, + _kwargs=combine_kwargs(**kwargs), ) def get_parent(self, **kwargs): @@ -153,7 +160,7 @@ def get_parent(self, **kwargs): response = self._requester.request( 'GET', '{}s/{}'.format(self._parent_type, self._parent_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if self._parent_type == 'group': @@ -180,9 +187,7 @@ def get_progress(self, **kwargs): progress_id = self.progress_url.split("/")[-1] response = self._requester.request( - 'GET', - 'progress/{}'.format(progress_id), - _kwargs=combine_kwargs(**kwargs) + 'GET', 'progress/{}'.format(progress_id), _kwargs=combine_kwargs(**kwargs) ) return Progress(self._requester, response.json()) @@ -207,8 +212,10 @@ def update(self, **kwargs): """ response = self._requester.request( 'PUT', - '{}s/{}/content_migrations/{}'.format(self._parent_type, self._parent_id, self.id), - _kwargs=combine_kwargs(**kwargs) + '{}s/{}/content_migrations/{}'.format( + self._parent_type, self._parent_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) if 'migration_type' in response.json(): @@ -246,11 +253,9 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', '{}s/{}/content_migrations/{}/migration_issues/{}'.format( - self.context_type, - self.context_id, - self.content_migration_id, - self.id), - _kwargs=combine_kwargs(**kwargs) + self.context_type, self.context_id, self.content_migration_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) if 'workflow_state' in response.json(): diff --git a/canvasapi/conversation.py b/canvasapi/conversation.py index 8a63fcc7..a4edba2f 100644 --- a/canvasapi/conversation.py +++ b/canvasapi/conversation.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class Conversation(CanvasObject): - def __str__(self): return "{} ({})".format(self.subject, self.id) @@ -22,9 +21,7 @@ def edit(self, **kwargs): :rtype: `bool` """ response = self._requester.request( - 'PUT', - 'conversations/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'conversations/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) if response.json().get('id'): @@ -42,10 +39,7 @@ def delete(self): :rtype: `bool` """ - response = self._requester.request( - 'DELETE', - 'conversations/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'conversations/{}'.format(self.id)) if response.json().get('id'): super(Conversation, self).set_attributes(response.json()) @@ -70,7 +64,7 @@ def add_recipients(self, recipients): response = self._requester.request( 'POST', 'conversations/{}/add_recipients'.format(self.id), - recipients=recipients + recipients=recipients, ) return Conversation(self._requester, response.json()) @@ -90,7 +84,7 @@ def add_message(self, body, **kwargs): 'POST', 'conversations/{}/add_message'.format(self.id), body=body, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Conversation(self._requester, response.json()) @@ -109,8 +103,6 @@ def delete_messages(self, remove): :rtype: `dict` """ response = self._requester.request( - 'POST', - 'conversations/{}/remove_messages'.format(self.id), - remove=remove + 'POST', 'conversations/{}/remove_messages'.format(self.id), remove=remove ) return response.json() diff --git a/canvasapi/course.py b/canvasapi/course.py index ec1996f6..f63394d8 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -21,7 +21,11 @@ from canvasapi.submission import GroupedSubmission, Submission from canvasapi.upload import Uploader from canvasapi.util import ( - combine_kwargs, is_multivalued, file_or_path, obj_or_id, normalize_bool + combine_kwargs, + is_multivalued, + file_or_path, + obj_or_id, + normalize_bool, ) from canvasapi.rubric import Rubric @@ -31,7 +35,6 @@ @python_2_unicode_compatible class Course(CanvasObject): - def __str__(self): return '{} {} ({})'.format(self.course_code, self.name, self.id) @@ -46,9 +49,7 @@ def conclude(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'courses/{}'.format(self.id), - event="conclude" + 'DELETE', 'courses/{}'.format(self.id), event="conclude" ) return response.json().get('conclude') @@ -76,7 +77,7 @@ def create_assignment_overrides(self, assignment_overrides, **kwargs): 'POST', 'courses/{}/assignments/overrides'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def delete(self): @@ -90,9 +91,7 @@ def delete(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'courses/{}'.format(self.id), - event="delete" + 'DELETE', 'courses/{}'.format(self.id), event="delete" ) return response.json().get('delete') @@ -107,9 +106,7 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - 'courses/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'courses/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) if response.json().get('name'): @@ -142,7 +139,7 @@ def update_assignment_overrides(self, assignment_overrides, **kwargs): 'PUT', 'courses/{}/assignments/overrides'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_user(self, user, user_id_type=None): @@ -168,10 +165,7 @@ def get_user(self, user, user_id_type=None): user_id = obj_or_id(user, "user", (User,)) uri = 'courses/{}/users/{}'.format(self.id, user_id) - response = self._requester.request( - 'GET', - uri - ) + response = self._requester.request('GET', uri) return User(self._requester, response.json()) def get_users(self, **kwargs): @@ -191,7 +185,7 @@ def get_users(self, **kwargs): self._requester, 'GET', 'courses/{}/search_users'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def enroll_user(self, user, enrollment_type, **kwargs): @@ -216,7 +210,7 @@ def enroll_user(self, user, enrollment_type, **kwargs): response = self._requester.request( 'POST', 'courses/{}/enrollments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Enrollment(self._requester, response.json()) @@ -235,10 +229,7 @@ def get_recent_students(self): from canvasapi.user import User return PaginatedList( - User, - self._requester, - 'GET', - 'courses/{}/recent_students'.format(self.id) + User, self._requester, 'GET', 'courses/{}/recent_students'.format(self.id) ) def preview_html(self, html): @@ -253,9 +244,7 @@ def preview_html(self, html): :rtype: str """ response = self._requester.request( - 'POST', - 'courses/{}/preview_html'.format(self.id), - html=html + 'POST', 'courses/{}/preview_html'.format(self.id), html=html ) return response.json().get('html', '') @@ -268,10 +257,7 @@ def get_settings(self): :rtype: dict """ - response = self._requester.request( - 'GET', - 'courses/{}/settings'.format(self.id) - ) + response = self._requester.request('GET', 'courses/{}/settings'.format(self.id)) return response.json() def update_settings(self, **kwargs): @@ -284,9 +270,7 @@ def update_settings(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'PUT', - 'courses/{}/settings'.format(self.id), - **kwargs + 'PUT', 'courses/{}/settings'.format(self.id), **kwargs ) return response.json() @@ -304,10 +288,7 @@ def upload(self, file, **kwargs): :rtype: tuple """ return Uploader( - self._requester, - 'courses/{}/files'.format(self.id), - file, - **kwargs + self._requester, 'courses/{}/files'.format(self.id), file, **kwargs ).start() def reset(self): @@ -321,8 +302,7 @@ def reset(self): :rtype: :class:`canvasapi.course.Course` """ response = self._requester.request( - 'POST', - 'courses/{}/reset_content'.format(self.id), + 'POST', 'courses/{}/reset_content'.format(self.id) ) return Course(self._requester, response.json()) @@ -337,12 +317,13 @@ def get_enrollments(self, **kwargs): :class:`canvasapi.enrollment.Enrollment` """ from canvasapi.enrollment import Enrollment + return PaginatedList( Enrollment, self._requester, 'GET', 'courses/{}/enrollments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_assignment(self, assignment, **kwargs): @@ -364,7 +345,7 @@ def get_assignment(self, assignment, **kwargs): response = self._requester.request( 'GET', 'courses/{}/assignments/{}'.format(self.id, assignment_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Assignment(self._requester, response.json()) @@ -389,7 +370,7 @@ def get_assignment_overrides(self, assignment_overrides, **kwargs): 'GET', 'courses/{}/assignments/overrides'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_assignments(self, **kwargs): @@ -409,7 +390,7 @@ def get_assignments(self, **kwargs): self._requester, 'GET', 'courses/{}/assignments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_assignment(self, assignment, **kwargs): @@ -435,7 +416,7 @@ def create_assignment(self, assignment, **kwargs): response = self._requester.request( 'POST', 'courses/{}/assignments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Assignment(self._requester, response.json()) @@ -451,13 +432,14 @@ def get_quizzes(self, **kwargs): :class:`canvasapi.quiz.Quiz` """ from canvasapi.quiz import Quiz + return PaginatedList( Quiz, self._requester, 'GET', 'courses/{}/quizzes'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_quiz(self, quiz): @@ -477,8 +459,7 @@ def get_quiz(self, quiz): quiz_id = obj_or_id(quiz, "quiz", (Quiz,)) response = self._requester.request( - 'GET', - 'courses/{}/quizzes/{}'.format(self.id, quiz_id) + 'GET', 'courses/{}/quizzes/{}'.format(self.id, quiz_id) ) quiz_json = response.json() quiz_json.update({'course_id': self.id}) @@ -506,7 +487,7 @@ def create_quiz(self, quiz, **kwargs): response = self._requester.request( 'POST', 'courses/{}/quizzes'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) quiz_json = response.json() quiz_json.update({'course_id': self.id}) @@ -531,7 +512,7 @@ def get_modules(self, **kwargs): 'GET', 'courses/{}/modules'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_module(self, module, **kwargs): @@ -551,8 +532,7 @@ def get_module(self, module, **kwargs): module_id = obj_or_id(module, "module", (Module,)) response = self._requester.request( - 'GET', - 'courses/{}/modules/{}'.format(self.id, module_id), + 'GET', 'courses/{}/modules/{}'.format(self.id, module_id) ) module_json = response.json() module_json.update({'course_id': self.id}) @@ -581,7 +561,7 @@ def create_module(self, module, **kwargs): response = self._requester.request( 'POST', 'courses/{}/modules'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) module_json = response.json() module_json.update({'course_id': self.id}) @@ -603,8 +583,7 @@ def get_external_tool(self, tool): tool_id = obj_or_id(tool, "tool", (ExternalTool,)) response = self._requester.request( - 'GET', - 'courses/{}/external_tools/{}'.format(self.id, tool_id), + 'GET', 'courses/{}/external_tools/{}'.format(self.id, tool_id) ) tool_json = response.json() tool_json.update({'course_id': self.id}) @@ -627,7 +606,7 @@ def get_external_tools(self, **kwargs): 'GET', 'courses/{}/external_tools'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_sections(self, **kwargs): @@ -647,7 +626,7 @@ def get_sections(self, **kwargs): self._requester, 'GET', 'courses/{}/sections'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_section(self, section, **kwargs): @@ -669,7 +648,7 @@ def get_section(self, section, **kwargs): response = self._requester.request( 'GET', 'courses/{}/sections/{}'.format(self.id, section_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Section(self._requester, response.json()) @@ -683,8 +662,7 @@ def show_front_page(self): :rtype: :class:`canvasapi.course.Course` """ response = self._requester.request( - 'GET', - 'courses/{}/front_page'.format(self.id) + 'GET', 'courses/{}/front_page'.format(self.id) ) page_json = response.json() page_json.update({'course_id': self.id}) @@ -703,7 +681,7 @@ def edit_front_page(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/front_page'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) page_json = response.json() page_json.update({'course_id': self.id}) @@ -726,7 +704,7 @@ def get_pages(self, **kwargs): 'GET', 'courses/{}/pages'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_page(self, wiki_page, **kwargs): @@ -748,9 +726,7 @@ def create_page(self, wiki_page, **kwargs): raise RequiredFieldMissing("Dictionary with key 'title' is required.") response = self._requester.request( - 'POST', - 'courses/{}/pages'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'POST', 'courses/{}/pages'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) page_json = response.json() @@ -772,8 +748,7 @@ def get_page(self, url): """ response = self._requester.request( - 'GET', - 'courses/{}/pages/{}'.format(self.id, url) + 'GET', 'courses/{}/pages/{}'.format(self.id, url) ) page_json = response.json() page_json.update({'course_id': self.id}) @@ -797,7 +772,7 @@ def list_sections(self, **kwargs): warnings.warn( "`list_sections` is being deprecated and will be removed in a future version." " Use `get_sections` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_sections(**kwargs) @@ -812,10 +787,11 @@ def create_course_section(self, **kwargs): """ from canvasapi.section import Section + response = self._requester.request( 'POST', 'courses/{}/sections'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Section(self._requester, response.json()) @@ -837,7 +813,7 @@ def list_groups(self, **kwargs): warnings.warn( "`list_groups` is being deprecated and will be removed in a future version." " Use `get_groups` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_groups(**kwargs) @@ -853,12 +829,13 @@ def get_groups(self, **kwargs): :class:`canvasapi.course.Course` """ from canvasapi.group import Group + return PaginatedList( Group, self._requester, 'GET', 'courses/{}/groups'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_group_category(self, name, **kwargs): @@ -878,7 +855,7 @@ def create_group_category(self, name, **kwargs): 'POST', 'courses/{}/group_categories'.format(self.id), name=name, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GroupCategory(self._requester, response.json()) @@ -899,7 +876,7 @@ def list_group_categories(self, **kwargs): warnings.warn( "`list_group_categories` is being deprecated and will be removed in a future version." " Use `get_group_categories` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_group_categories(**kwargs) @@ -921,7 +898,7 @@ def get_group_categories(self, **kwargs): self._requester, 'GET', 'courses/{}/group_categories'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_file(self, file, **kwargs): @@ -943,7 +920,7 @@ def get_file(self, file, **kwargs): response = self._requester.request( 'GET', 'courses/{}/files/{}'.format(self.id, file_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) @@ -962,8 +939,7 @@ def get_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', - 'courses/{}/discussion_topics/{}'.format(self.id, topic_id) + 'GET', 'courses/{}/discussion_topics/{}'.format(self.id, topic_id) ) response_json = response.json() @@ -986,8 +962,7 @@ def get_full_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', - 'courses/{}/discussion_topics/{}/view'.format(self.id, topic_id), + 'GET', 'courses/{}/discussion_topics/{}/view'.format(self.id, topic_id) ) return response.json() @@ -1007,7 +982,7 @@ def get_discussion_topics(self, **kwargs): 'GET', 'courses/{}/discussion_topics'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_assignment_group(self, assignment_group, **kwargs): @@ -1024,12 +999,14 @@ def get_assignment_group(self, assignment_group, **kwargs): """ from canvasapi.assignment import AssignmentGroup - assignment_group_id = obj_or_id(assignment_group, "assignment_group", (AssignmentGroup,)) + assignment_group_id = obj_or_id( + assignment_group, "assignment_group", (AssignmentGroup,) + ) response = self._requester.request( 'GET', 'courses/{}/assignment_groups/{}'.format(self.id, assignment_group_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.id}) @@ -1053,7 +1030,7 @@ def list_assignment_groups(self, **kwargs): warnings.warn( "`list_assignment_groups` is being deprecated and will be removed " "in a future version. Use `get_assignment_groups` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_assignment_groups(**kwargs) @@ -1076,7 +1053,7 @@ def get_assignment_groups(self, **kwargs): 'GET', 'courses/{}/assignment_groups'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_discussion_topic(self, **kwargs): @@ -1091,7 +1068,7 @@ def create_discussion_topic(self, **kwargs): response = self._requester.request( 'POST', 'courses/{}/discussion_topics'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -1123,9 +1100,7 @@ def reorder_pinned_topics(self, order): raise ValueError("Param `order` must be a list, tuple, or string.") response = self._requester.request( - 'POST', - 'courses/{}/discussion_topics/reorder'.format(self.id), - order=order + 'POST', 'courses/{}/discussion_topics/reorder'.format(self.id), order=order ) return response.json().get('reorder') @@ -1144,14 +1119,16 @@ def create_assignment_group(self, **kwargs): response = self._requester.request( 'POST', 'courses/{}/assignment_groups'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.id}) return AssignmentGroup(self._requester, response_json) - def create_external_tool(self, name, privacy_level, consumer_key, shared_secret, **kwargs): + def create_external_tool( + self, name, privacy_level, consumer_key, shared_secret, **kwargs + ): """ Create an external tool in the current course. @@ -1178,7 +1155,7 @@ def create_external_tool(self, name, privacy_level, consumer_key, shared_secret, privacy_level=privacy_level, consumer_key=consumer_key, shared_secret=shared_secret, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.id}) @@ -1196,8 +1173,7 @@ def get_course_level_participation_data(self): """ response = self._requester.request( - 'GET', - 'courses/{}/analytics/activity'.format(self.id) + 'GET', 'courses/{}/analytics/activity'.format(self.id) ) return response.json() @@ -1215,7 +1191,7 @@ def get_course_level_assignment_data(self, **kwargs): response = self._requester.request( 'GET', 'courses/{}/analytics/assignments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json() @@ -1233,7 +1209,7 @@ def get_course_level_student_summary_data(self, **kwargs): response = self._requester.request( 'GET', 'courses/{}/analytics/student_summaries'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json() @@ -1255,8 +1231,7 @@ def get_user_in_a_course_level_participation_data(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', - 'courses/{}/analytics/users/{}/activity'.format(self.id, user_id) + 'GET', 'courses/{}/analytics/users/{}/activity'.format(self.id, user_id) ) return response.json() @@ -1278,8 +1253,7 @@ def get_user_in_a_course_level_assignment_data(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', - 'courses/{}/analytics/users/{}/assignments'.format(self.id, user_id) + 'GET', 'courses/{}/analytics/users/{}/assignments'.format(self.id, user_id) ) return response.json() @@ -1302,7 +1276,7 @@ def get_user_in_a_course_level_messaging_data(self, user): response = self._requester.request( 'GET', - 'courses/{}/analytics/users/{}/communication'.format(self.id, user_id) + 'courses/{}/analytics/users/{}/communication'.format(self.id, user_id), ) return response.json() @@ -1331,14 +1305,13 @@ def submit_assignment(self, assignment, submission, **kwargs): warnings.warn( 'Course.submit_assignment() is deprecated and will be removed in ' 'the future. Use Assignment.submit() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, - {'course_id': self.id, 'id': assignment_id} + self._requester, {'course_id': self.id, 'id': assignment_id} ) return assignment.submit(submission, **kwargs) @@ -1365,14 +1338,13 @@ def list_submissions(self, assignment, **kwargs): warnings.warn( 'Course.list_submissions() is deprecated and will be removed in ' 'the future. Use Assignment.get_submissions() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, - {'course_id': self.id, 'id': assignment_id} + self._requester, {'course_id': self.id, 'id': assignment_id} ) return assignment.get_submissions(**kwargs) @@ -1396,7 +1368,7 @@ def list_multiple_submissions(self, **kwargs): "`list_multiple_submissions`" " is being deprecated and will be removed in a future version." " Use `get_multiple_submissions` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_multiple_submissions(**kwargs) @@ -1452,14 +1424,13 @@ def get_submission(self, assignment, user, **kwargs): warnings.warn( '`Course.get_submission()` is deprecated and will be removed in a ' 'future version. Use `Assignment.get_submission()` instead', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, 'assignment', (Assignment,)) assignment = Assignment( - self._requester, - {'course_id': self.id, 'id': assignment_id} + self._requester, {'course_id': self.id, 'id': assignment_id} ) return assignment.get_submission(user, **kwargs) @@ -1488,17 +1459,16 @@ def update_submission(self, assignment, user, **kwargs): warnings.warn( '`Course.update_submission()` is deprecated and will be removed in a ' 'future version. Use `Submission.edit()` instead', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) user_id = obj_or_id(user, "user", (User,)) - submission = Submission(self._requester, { - 'course_id': self.id, - 'assignment_id': assignment_id, - 'user_id': user_id, - }) + submission = Submission( + self._requester, + {'course_id': self.id, 'assignment_id': assignment_id, 'user_id': user_id}, + ) return submission.edit(**kwargs) @@ -1525,13 +1495,12 @@ def list_gradeable_students(self, assignment, **kwargs): '`Course.list_gradeable_students()` is deprecated and will be ' 'removed in a future version. Use ' '`Assignment.get_gradeable_students()` instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, - {'id': assignment_id, 'course_id': self.id} + self._requester, {'id': assignment_id, 'course_id': self.id} ) return assignment.get_gradeable_students(**kwargs) @@ -1561,17 +1530,16 @@ def mark_submission_as_read(self, assignment, user, **kwargs): warnings.warn( '`Course.mark_submission_as_read()` is deprecated and will be ' 'removed in a future version. Use `Submission.mark_read()` instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) user_id = obj_or_id(user, "user", (User,)) - submission = Submission(self._requester, { - 'course_id': self.id, - 'assignment_id': assignment_id, - 'user_id': user_id - }) + submission = Submission( + self._requester, + {'course_id': self.id, 'assignment_id': assignment_id, 'user_id': user_id}, + ) return submission.mark_read(**kwargs) def mark_submission_as_unread(self, assignment, user, **kwargs): @@ -1599,17 +1567,16 @@ def mark_submission_as_unread(self, assignment, user, **kwargs): warnings.warn( '`Course.mark_submission_as_unread()` is deprecated and will be ' 'removed in a future version. Use `Submission.mark_unread()` instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) user_id = obj_or_id(user, "user", (User,)) - submission = Submission(self._requester, { - 'course_id': self.id, - 'assignment_id': assignment_id, - 'user_id': user_id - }) + submission = Submission( + self._requester, + {'course_id': self.id, 'assignment_id': assignment_id, 'user_id': user_id}, + ) return submission.mark_unread(**kwargs) def list_external_feeds(self, **kwargs): @@ -1629,7 +1596,7 @@ def list_external_feeds(self, **kwargs): warnings.warn( "`list_external_feeds` is being deprecated and will be removed in " "a future version. Use `get_external_feeds` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_external_feeds(**kwargs) @@ -1645,12 +1612,13 @@ def get_external_feeds(self, **kwargs): :class:`canvasapi.external_feed.ExternalFeed` """ from canvasapi.external_feed import ExternalFeed + return PaginatedList( ExternalFeed, self._requester, 'GET', 'courses/{}/external_feeds'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_external_feed(self, url, **kwargs): @@ -1665,11 +1633,12 @@ def create_external_feed(self, url, **kwargs): :rtype: :class:`canvasapi.external_feed.ExternalFeed` """ from canvasapi.external_feed import ExternalFeed + response = self._requester.request( 'POST', 'courses/{}/external_feeds'.format(self.id), url=url, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return ExternalFeed(self._requester, response.json()) @@ -1690,8 +1659,7 @@ def delete_external_feed(self, feed): feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) response = self._requester.request( - 'DELETE', - 'courses/{}/external_feeds/{}'.format(self.id, feed_id) + 'DELETE', 'courses/{}/external_feeds/{}'.format(self.id, feed_id) ) return ExternalFeed(self._requester, response.json()) @@ -1712,7 +1680,7 @@ def list_files(self, **kwargs): warnings.warn( "`list_files` is being deprecated and will be removed in a future " "version. Use `get_files` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_files(**kwargs) @@ -1734,7 +1702,7 @@ def get_files(self, **kwargs): self._requester, 'GET', 'courses/{}/files'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_folder(self, folder): @@ -1752,8 +1720,7 @@ def get_folder(self, folder): folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - 'GET', - 'courses/{}/folders/{}'.format(self.id, folder_id) + 'GET', 'courses/{}/folders/{}'.format(self.id, folder_id) ) return Folder(self._requester, response.json()) @@ -1775,7 +1742,7 @@ def list_folders(self, **kwargs): warnings.warn( "`list_folders` is being deprecated and will be removed in a " "future version. Use `get_folders` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_folders(**kwargs) @@ -1796,7 +1763,7 @@ def get_folders(self, **kwargs): self._requester, 'GET', 'courses/{}/folders'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_folder(self, name, **kwargs): @@ -1814,7 +1781,7 @@ def create_folder(self, name, **kwargs): 'POST', 'courses/{}/folders'.format(self.id), name=name, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Folder(self._requester, response.json()) @@ -1836,7 +1803,7 @@ def list_tabs(self, **kwargs): warnings.warn( "`list_tabs` is being deprecated and will be removed in a future " "version. Use `get_tabs` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_tabs(**kwargs) @@ -1858,7 +1825,7 @@ def get_tabs(self, **kwargs): 'GET', 'courses/{}/tabs'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def update_tab(self, tab_id, **kwargs): @@ -1880,13 +1847,10 @@ def update_tab(self, tab_id, **kwargs): warnings.warn( "`Course.update_tab()` is being deprecated and will be removed in " "a future version. Use `Tab.update()` instead", - DeprecationWarning + DeprecationWarning, ) - tab = Tab(self._requester, { - 'course_id': self.id, - 'id': tab_id - }) + tab = Tab(self._requester, {'course_id': self.id, 'id': tab_id}) return tab.update(**kwargs) def get_rubric(self, rubric_id, **kwargs): @@ -1903,7 +1867,7 @@ def get_rubric(self, rubric_id, **kwargs): response = self._requester.request( 'GET', 'courses/%s/rubrics/%s' % (self.id, rubric_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Rubric(self._requester, response.json()) @@ -1925,7 +1889,7 @@ def list_rubrics(self, **kwargs): warnings.warn( "`list_rubrics` is being deprecated and will be removed in a " "future version. Use `get_rubrics` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_rubrics(**kwargs) @@ -1945,7 +1909,7 @@ def get_rubrics(self, **kwargs): self._requester, 'GET', 'courses/%s/rubrics' % (self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_root_outcome_group(self): @@ -1961,8 +1925,7 @@ def get_root_outcome_group(self): from canvasapi.outcome import OutcomeGroup response = self._requester.request( - 'GET', - 'courses/{}/root_outcome_group'.format(self.id) + 'GET', 'courses/{}/root_outcome_group'.format(self.id) ) return OutcomeGroup(self._requester, response.json()) @@ -1984,8 +1947,7 @@ def get_outcome_group(self, group): outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,)) response = self._requester.request( - 'GET', - 'courses/{}/outcome_groups/{}'.format(self.id, outcome_group_id) + 'GET', 'courses/{}/outcome_groups/{}'.format(self.id, outcome_group_id) ) return OutcomeGroup(self._requester, response.json()) @@ -2007,7 +1969,7 @@ def get_outcome_groups_in_context(self): OutcomeGroup, self._requester, 'GET', - 'courses/{}/outcome_groups'.format(self.id) + 'courses/{}/outcome_groups'.format(self.id), ) def get_all_outcome_links_in_context(self): @@ -2027,7 +1989,7 @@ def get_all_outcome_links_in_context(self): OutcomeLink, self._requester, 'GET', - 'courses/{}/outcome_group_links'.format(self.id) + 'courses/{}/outcome_group_links'.format(self.id), ) def get_outcome_results(self, **kwargs): @@ -2043,7 +2005,7 @@ def get_outcome_results(self, **kwargs): response = self._requester.request( 'GET', 'courses/{}/outcome_results'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json() @@ -2061,7 +2023,7 @@ def get_outcome_result_rollups(self, **kwargs): response = self._requester.request( 'GET', 'courses/{}/outcome_rollups'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json() @@ -2086,14 +2048,16 @@ def add_grading_standards(self, title, grading_scheme_entry, **kwargs): if not isinstance(entry, dict): raise ValueError("grading_scheme_entry must consist of dictionaries.") if "name" not in entry or "value" not in entry: - raise ValueError("Dictionaries with keys 'name' and 'value' are required.") + raise ValueError( + "Dictionaries with keys 'name' and 'value' are required." + ) kwargs["grading_scheme_entry"] = grading_scheme_entry response = self._requester.request( 'POST', 'courses/%s/grading_standards' % (self.id), title=title, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GradingStandard(self._requester, response.json()) @@ -2112,7 +2076,7 @@ def get_grading_standards(self, **kwargs): self._requester, 'GET', 'courses/%s/grading_standards' % (self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_single_grading_standard(self, grading_standard_id, **kwargs): @@ -2130,7 +2094,7 @@ def get_single_grading_standard(self, grading_standard_id, **kwargs): response = self._requester.request( 'GET', 'courses/%s/grading_standards/%d' % (self.id, grading_standard_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GradingStandard(self._requester, response.json()) @@ -2158,7 +2122,7 @@ def create_content_migration(self, migration_type, **kwargs): response = self._requester.request( 'POST', 'courses/{}/content_migrations'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -2180,12 +2144,14 @@ def get_content_migration(self, content_migration, **kwargs): """ from canvasapi.content_migration import ContentMigration - migration_id = obj_or_id(content_migration, "content_migration", (ContentMigration,)) + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) + ) response = self._requester.request( 'GET', 'courses/{}/content_migrations/{}'.format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -2211,7 +2177,7 @@ def get_content_migrations(self, **kwargs): 'GET', 'courses/{}/content_migrations'.format(self.id), {'course_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_migration_systems(self, **kwargs): @@ -2231,7 +2197,7 @@ def get_migration_systems(self, **kwargs): self._requester, 'GET', 'courses/{}/content_migrations/migrators'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def set_quiz_extensions(self, quiz_extensions, **kwargs): @@ -2281,10 +2247,12 @@ def set_quiz_extensions(self, quiz_extensions, **kwargs): response = self._requester.request( 'POST', 'courses/{}/quiz_extensions'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) extension_list = response.json()['quiz_extensions'] - return [QuizExtension(self._requester, extension) for extension in extension_list] + return [ + QuizExtension(self._requester, extension) for extension in extension_list + ] def submissions_bulk_update(self, **kwargs): """ @@ -2298,10 +2266,8 @@ def submissions_bulk_update(self, **kwargs): """ response = self._requester.request( 'POST', - 'courses/{}/submissions/update_grades'.format( - self.id - ), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/submissions/update_grades'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) @@ -2326,11 +2292,8 @@ def get_blueprint(self, template='default', **kwargs): response = self._requester.request( 'GET', - 'courses/{}/blueprint_templates/{}'.format( - self.id, - template_id - ), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/blueprint_templates/{}'.format(self.id, template_id), + _kwargs=combine_kwargs(**kwargs), ) return BlueprintTemplate(self._requester, response.json()) @@ -2350,11 +2313,9 @@ def list_blueprint_subscriptions(self, **kwargs): BlueprintSubscription, self._requester, 'GET', - 'courses/{}/blueprint_subscriptions'.format( - self.id - ), + 'courses/{}/blueprint_subscriptions'.format(self.id), {'course_id': self.id}, - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) def import_outcome(self, attachment, **kwargs): @@ -2476,12 +2437,10 @@ def get_grading_periods(self, **kwargs): GradingPeriod, self._requester, 'GET', - 'courses/{}/grading_periods'.format( - self.id - ), + 'courses/{}/grading_periods'.format(self.id), {'course_id': self.id}, _root="grading_periods", - kwargs=combine_kwargs(**kwargs) + kwargs=combine_kwargs(**kwargs), ) def get_grading_period(self, grading_period, **kwargs): @@ -2498,10 +2457,8 @@ def get_grading_period(self, grading_period, **kwargs): response = self._requester.request( 'GET', - 'courses/{}/grading_periods/{}'.format( - self.id, grading_period - ), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/grading_periods/{}'.format(self.id, grading_period), + _kwargs=combine_kwargs(**kwargs), ) response_grading_period = response.json()['grading_periods'][0] @@ -2525,10 +2482,8 @@ def get_content_exports(self, **kwargs): ContentExport, self._requester, 'GET', - 'courses/{}/content_exports'.format( - self.id - ), - kwargs=combine_kwargs(**kwargs) + 'courses/{}/content_exports'.format(self.id), + kwargs=combine_kwargs(**kwargs), ) def get_content_export(self, content_export, **kwargs): @@ -2549,11 +2504,8 @@ def get_content_export(self, content_export, **kwargs): response = self._requester.request( 'GET', - 'courses/{}/content_exports/{}'.format( - self.id, - export_id - ), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/content_exports/{}'.format(self.id, export_id), + _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -2576,17 +2528,14 @@ def export_content(self, export_type, **kwargs): response = self._requester.request( 'POST', - 'courses/{}/content_exports'.format( - self.id, - ), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/content_exports'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @python_2_unicode_compatible class CourseNickname(CanvasObject): - def __str__(self): return "{} ({})".format(self.nickname, self.course_id) @@ -2601,7 +2550,6 @@ def remove(self): :rtype: :class:`canvasapi.course.CourseNickname` """ response = self._requester.request( - 'DELETE', - 'users/self/course_nicknames/{}'.format(self.course_id) + 'DELETE', 'users/self/course_nicknames/{}'.format(self.course_id) ) return CourseNickname(self._requester, response.json()) diff --git a/canvasapi/current_user.py b/canvasapi/current_user.py index 643c7eb1..4e305e34 100644 --- a/canvasapi/current_user.py +++ b/canvasapi/current_user.py @@ -18,10 +18,7 @@ class CurrentUser(User): def __init__(self, _requester): self._requester = _requester - response = self._requester.request( - 'GET', - 'users/self' - ) + response = self._requester.request('GET', 'users/self') super(CurrentUser, self).__init__(self._requester, response.json()) @@ -44,7 +41,7 @@ def list_groups(self, **kwargs): warnings.warn( "`list_groups` is being deprecated and will be removed in a " "future version. Use `get_groups` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_groups(**kwargs) @@ -65,7 +62,7 @@ def get_groups(self, **kwargs): self._requester, 'GET', 'users/self/groups', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def list_bookmarks(self, **kwargs): @@ -85,7 +82,7 @@ def list_bookmarks(self, **kwargs): warnings.warn( "`list_bookmarks` is being deprecated and will be removed in a " "future version. Use `get_bookmarks` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_bookmarks(**kwargs) @@ -100,12 +97,7 @@ def get_bookmarks(self, **kwargs): :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.bookmark.Bookmark` """ - return PaginatedList( - Bookmark, - self._requester, - 'GET', - 'users/self/bookmarks' - ) + return PaginatedList(Bookmark, self._requester, 'GET', 'users/self/bookmarks') def create_bookmark(self, name, url, **kwargs): """ @@ -127,7 +119,7 @@ def create_bookmark(self, name, url, **kwargs): 'users/self/bookmarks', name=name, url=url, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Bookmark(self._requester, response.json()) @@ -149,8 +141,7 @@ def get_bookmark(self, bookmark): bookmark_id = obj_or_id(bookmark, "bookmark", (Bookmark,)) response = self._requester.request( - 'GET', - 'users/self/bookmarks/{}'.format(bookmark_id) + 'GET', 'users/self/bookmarks/{}'.format(bookmark_id) ) return Bookmark(self._requester, response.json()) @@ -172,7 +163,7 @@ def get_favorite_courses(self, **kwargs): self._requester, 'GET', 'users/self/favorites/courses', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_favorite_groups(self, **kwargs): @@ -193,7 +184,7 @@ def get_favorite_groups(self, **kwargs): self._requester, 'GET', 'users/self/favorites/groups', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def add_favorite_course(self, course, use_sis_id=False, **kwargs): @@ -213,7 +204,7 @@ def add_favorite_course(self, course, use_sis_id=False, **kwargs): :rtype: :class:`canvasapi.favorite.Favorite` """ - if(use_sis_id): + if use_sis_id: course_id = course uri_str = 'users/self/favorites/courses/sis_course_id:{}' else: @@ -221,9 +212,7 @@ def add_favorite_course(self, course, use_sis_id=False, **kwargs): uri_str = 'users/self/favorites/courses/{}' response = self._requester.request( - 'POST', - uri_str.format(course_id), - _kwargs=combine_kwargs(**kwargs) + 'POST', uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) ) return Favorite(self._requester, response.json()) @@ -244,7 +233,7 @@ def add_favorite_group(self, group, use_sis_id=False, **kwargs): :rtype: :class:`canvasapi.favorite.Favorite` """ - if(use_sis_id): + if use_sis_id: group_id = group uri_str = 'users/self/favorites/groups/sis_group_id:{}' else: @@ -252,9 +241,7 @@ def add_favorite_group(self, group, use_sis_id=False, **kwargs): uri_str = 'users/self/favorites/groups/{}' response = self._requester.request( - 'POST', - uri_str.format(group_id), - _kwargs=combine_kwargs(**kwargs) + 'POST', uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) ) return Favorite(self._requester, response.json()) @@ -271,9 +258,7 @@ def reset_favorite_courses(self, **kwargs): """ response = self._requester.request( - 'DELETE', - 'users/self/favorites/courses', - _kwargs=combine_kwargs(**kwargs) + 'DELETE', 'users/self/favorites/courses', _kwargs=combine_kwargs(**kwargs) ) return response.json().get('message') == 'OK' @@ -290,8 +275,6 @@ def reset_favorite_groups(self, **kwargs): """ response = self._requester.request( - 'DELETE', - 'users/self/favorites/groups', - _kwargs=combine_kwargs(**kwargs) + 'DELETE', 'users/self/favorites/groups', _kwargs=combine_kwargs(**kwargs) ) return response.json().get('message') == 'OK' diff --git a/canvasapi/discussion_topic.py b/canvasapi/discussion_topic.py index e20a8f7e..f338cc08 100644 --- a/canvasapi/discussion_topic.py +++ b/canvasapi/discussion_topic.py @@ -52,8 +52,7 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', - '{}s/{}'.format(self._parent_type, self._parent_id) + 'GET', '{}s/{}'.format(self._parent_type, self._parent_id) ) if self._parent_type == 'group': @@ -77,10 +76,8 @@ def delete(self): response = self._requester.request( 'DELETE', '{}s/{}/discussion_topics/{}'.format( - self._parent_type, - self._parent_id, - self.id - ) + self._parent_type, self._parent_id, self.id + ), ) return 'deleted_at' in response.json() @@ -99,11 +96,9 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', '{}s/{}/discussion_topics/{}'.format( - self._parent_type, - self._parent_id, - self.id + self._parent_type, self._parent_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return DiscussionTopic(self._requester, response.json()) @@ -122,17 +117,17 @@ def post_entry(self, **kwargs): response = self._requester.request( 'POST', '{}s/{}/discussion_topics/{}/entries'.format( - self._parent_type, - self._parent_id, - self.id + self._parent_type, self._parent_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({ - 'discussion_id': self.id, - '{}_id'.format(self._parent_type): self._parent_id - }) + response_json.update( + { + 'discussion_id': self.id, + '{}_id'.format(self._parent_type): self._parent_id, + } + ) return DiscussionEntry(self._requester, response_json) def list_topic_entries(self, **kwargs): @@ -155,7 +150,7 @@ def list_topic_entries(self, **kwargs): warnings.warn( "`list_topic_entries` is being deprecated and will be removed in " "a future version. Use `get_topic_entries` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_topic_entries(**kwargs) @@ -178,15 +173,13 @@ def get_topic_entries(self, **kwargs): self._requester, 'GET', '{}s/{}/discussion_topics/{}/entries'.format( - self._parent_type, - self._parent_id, - self.id + self._parent_type, self._parent_id, self.id ), { 'discussion_id': self.id, - '{}_id'.format(self._parent_type): self._parent_id + '{}_id'.format(self._parent_type): self._parent_id, }, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def list_entries(self, ids, **kwargs): @@ -213,7 +206,7 @@ def list_entries(self, ids, **kwargs): warnings.warn( "`list_entries` is being deprecated and will be removed in a " "future version. Use `get_entries` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_entries(ids, **kwargs) @@ -236,7 +229,7 @@ def get_entries(self, ids, **kwargs): :class:`canvasapi.discussion_topic.DiscussionEntry` """ - entry_ids = [obj_or_id(item, "ids", (DiscussionEntry, )) for item in ids] + entry_ids = [obj_or_id(item, "ids", (DiscussionEntry,)) for item in ids] kwargs.update(ids=entry_ids) return PaginatedList( @@ -244,13 +237,11 @@ def get_entries(self, ids, **kwargs): self._requester, 'GET', '{}s/{}/discussion_topics/{}/entry_list'.format( - self._parent_type, - self._parent_id, - self.id + self._parent_type, self._parent_id, self.id ), { 'discussion_id': self.id, - '{}_id'.format(self._parent_type): self._parent_id + '{}_id'.format(self._parent_type): self._parent_id, }, _kwargs=combine_kwargs(**kwargs), ) @@ -270,10 +261,8 @@ def mark_as_read(self): response = self._requester.request( 'PUT', '{}s/{}/discussion_topics/{}/read'.format( - self._parent_type, - self._parent_id, - self.id - ) + self._parent_type, self._parent_id, self.id + ), ) return response.status_code == 204 @@ -292,10 +281,8 @@ def mark_as_unread(self): response = self._requester.request( 'DELETE', '{}s/{}/discussion_topics/{}/read'.format( - self._parent_type, - self._parent_id, - self.id - ) + self._parent_type, self._parent_id, self.id + ), ) return response.status_code == 204 @@ -314,11 +301,9 @@ def mark_entries_as_read(self, **kwargs): response = self._requester.request( 'PUT', '{}s/{}/discussion_topics/{}/read_all'.format( - self._parent_type, - self._parent_id, - self.id + self._parent_type, self._parent_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 @@ -337,11 +322,9 @@ def mark_entries_as_unread(self, **kwargs): response = self._requester.request( 'DELETE', '{}s/{}/discussion_topics/{}/read_all'.format( - self._parent_type, - self._parent_id, - self.id + self._parent_type, self._parent_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 @@ -360,10 +343,8 @@ def subscribe(self): response = self._requester.request( 'PUT', '{}s/{}/discussion_topics/{}/subscribed'.format( - self._parent_type, - self._parent_id, - self.id - ) + self._parent_type, self._parent_id, self.id + ), ) return response.status_code == 204 @@ -382,10 +363,8 @@ def unsubscribe(self): response = self._requester.request( 'DELETE', '{}s/{}/discussion_topics/{}/subscribed'.format( - self._parent_type, - self._parent_id, - self.id - ) + self._parent_type, self._parent_id, self.id + ), ) return response.status_code == 204 @@ -435,8 +414,8 @@ def get_discussion(self): '{}s/{}/discussion_topics/{}'.format( self._discussion_parent_type, self._discussion_parent_id, - self.discussion_id - ) + self.discussion_id, + ), ) response_json = response.json() @@ -464,9 +443,9 @@ def update(self, **kwargs): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id + self.id, ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if response.json().get('updated_at'): @@ -492,9 +471,9 @@ def delete(self, **kwargs): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id + self.id, ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return 'deleted_at' in response.json() @@ -517,9 +496,9 @@ def post_reply(self, **kwargs): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id + self.id, ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update(discussion_id=self.discussion_id) @@ -547,7 +526,7 @@ def list_replies(self, **kwargs): warnings.warn( "`list_replies` is being deprecated and will be removed in a " "future version. Use `get_replies` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_replies(**kwargs) @@ -575,13 +554,15 @@ def get_replies(self, **kwargs): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id + self.id, ), { 'discussion_id': self.discussion_id, - '{}_id'.format(self._discussion_parent_type): self._discussion_parent_id + '{}_id'.format( + self._discussion_parent_type + ): self._discussion_parent_id, }, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) # TODO: update to use correct class @@ -603,8 +584,8 @@ def mark_as_read(self): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id - ) + self.id, + ), ) return response.status_code == 204 @@ -629,8 +610,8 @@ def mark_as_unread(self): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id - ) + self.id, + ), ) return response.status_code == 204 @@ -659,9 +640,9 @@ def rate(self, rating, **kwargs): self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id + self.id, ), rating=rating, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 diff --git a/canvasapi/enrollment.py b/canvasapi/enrollment.py index a4355a36..8f7daf42 100644 --- a/canvasapi/enrollment.py +++ b/canvasapi/enrollment.py @@ -7,7 +7,6 @@ @python_2_unicode_compatible class Enrollment(CanvasObject): - def __str__(self): return "{} ({})".format(self.type, self.id) @@ -28,15 +27,16 @@ def deactivate(self, task): ALLOWED_TASKS = ['conclude', 'delete', 'inactivate', 'deactivate'] if task not in ALLOWED_TASKS: - raise ValueError('{} is not a valid task. Please use one of the following: {}'.format( - task, - ','.join(ALLOWED_TASKS) - )) + raise ValueError( + '{} is not a valid task. Please use one of the following: {}'.format( + task, ','.join(ALLOWED_TASKS) + ) + ) response = self._requester.request( 'DELETE', 'courses/{}/enrollments/{}'.format(self.course_id, self.id), - task=task + task=task, ) return Enrollment(self._requester, response.json()) @@ -51,6 +51,6 @@ def reactivate(self): """ response = self._requester.request( 'PUT', - 'courses/{}/enrollments/{}/reactivate'.format(self.course_id, self.id) + 'courses/{}/enrollments/{}/reactivate'.format(self.course_id, self.id), ) return Enrollment(self._requester, response.json()) diff --git a/canvasapi/enrollment_term.py b/canvasapi/enrollment_term.py index 0ee68d2e..dcebcf4b 100644 --- a/canvasapi/enrollment_term.py +++ b/canvasapi/enrollment_term.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class EnrollmentTerm(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -22,8 +21,7 @@ def delete(self): :rtype: :class:`canvasapi.enrollment_term.EnrollmentTerm` """ response = self._requester.request( - 'DELETE', - 'accounts/{}/terms/{}'.format(self.account_id, self.id) + 'DELETE', 'accounts/{}/terms/{}'.format(self.account_id, self.id) ) return EnrollmentTerm(self._requester, response.json()) @@ -39,7 +37,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'accounts/{}/terms/{}'.format(self.account_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return EnrollmentTerm(self._requester, response.json()) diff --git a/canvasapi/exceptions.py b/canvasapi/exceptions.py index 85b0fa1d..f3278a6f 100644 --- a/canvasapi/exceptions.py +++ b/canvasapi/exceptions.py @@ -8,6 +8,7 @@ class CanvasException(Exception): # pragma: no cover """ Base class for all errors returned by the Canvas API. """ + def __init__(self, message): if isinstance(message, dict): self.error_report_id = message.get('error_report_id', None) @@ -26,34 +27,41 @@ def __str__(self): class BadRequest(CanvasException): """Canvas was unable to understand the request. More information may be needed.""" + pass class InvalidAccessToken(CanvasException): """CanvasAPI was unable to make an API connection.""" + pass class Unauthorized(CanvasException): """CanvasAPI's key is valid, but is unauthorized to access the requested resource.""" + pass class ResourceDoesNotExist(CanvasException): """Canvas could not locate the requested resource.""" + pass class RequiredFieldMissing(CanvasException): """A required field is missing.""" + pass class Forbidden(CanvasException): """Canvas has denied access to the resource for this user.""" + pass class Conflict(CanvasException): """Canvas had a conflict with an existing resource.""" + pass diff --git a/canvasapi/external_feed.py b/canvasapi/external_feed.py index c46a049b..aa8fa15b 100644 --- a/canvasapi/external_feed.py +++ b/canvasapi/external_feed.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class ExternalFeed(CanvasObject): - def __str__(self): return "{}".format(self.display_name) diff --git a/canvasapi/external_tool.py b/canvasapi/external_tool.py index b7995a23..e6216869 100644 --- a/canvasapi/external_tool.py +++ b/canvasapi/external_tool.py @@ -9,7 +9,6 @@ @python_2_unicode_compatible class ExternalTool(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -51,8 +50,7 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', - '{}s/{}'.format(self.parent_type, self.parent_id) + 'GET', '{}s/{}'.format(self.parent_type, self.parent_id) ) if self.parent_type == 'account': @@ -73,7 +71,9 @@ def delete(self): """ response = self._requester.request( 'DELETE', - '{}s/{}/external_tools/{}'.format(self.parent_type, self.parent_id, self.id) + '{}s/{}/external_tools/{}'.format( + self.parent_type, self.parent_id, self.id + ), ) return ExternalTool(self._requester, response.json()) @@ -91,8 +91,10 @@ def edit(self, **kwargs): """ response = self._requester.request( 'PUT', - '{}s/{}/external_tools/{}'.format(self.parent_type, self.parent_id, self.id), - _kwargs=combine_kwargs(**kwargs) + '{}s/{}/external_tools/{}'.format( + self.parent_type, self.parent_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -115,8 +117,10 @@ def get_sessionless_launch_url(self, **kwargs): kwargs['id'] = self.id response = self._requester.request( 'GET', - '{}s/{}/external_tools/sessionless_launch'.format(self.parent_type, self.parent_id), - _kwargs=combine_kwargs(**kwargs) + '{}s/{}/external_tools/sessionless_launch'.format( + self.parent_type, self.parent_id + ), + _kwargs=combine_kwargs(**kwargs), ) try: return response.json()['url'] diff --git a/canvasapi/favorite.py b/canvasapi/favorite.py index ac28c90c..ffd19278 100644 --- a/canvasapi/favorite.py +++ b/canvasapi/favorite.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class Favorite(CanvasObject): - def __str__(self): return "{} ({})".format(self.context_type, self.context_id) @@ -23,17 +22,15 @@ def remove(self, **kwargs): :rtype: :class:`canvasapi.favorite.Favorite` """ - if(self.context_type == "course"): + if self.context_type == "course": id = self.context_id uri_str = 'users/self/favorites/courses/{}' - elif(self.context_type == "group"): + elif self.context_type == "group": id = self.context_id uri_str = 'users/self/favorites/groups/{}' response = self._requester.request( - 'DELETE', - uri_str.format(id), - _kwargs=combine_kwargs(**kwargs) + 'DELETE', uri_str.format(id), _kwargs=combine_kwargs(**kwargs) ) return Favorite(self._requester, response.json()) diff --git a/canvasapi/file.py b/canvasapi/file.py index f9129e26..63597168 100644 --- a/canvasapi/file.py +++ b/canvasapi/file.py @@ -7,7 +7,6 @@ @python_2_unicode_compatible class File(CanvasObject): - def __str__(self): return "{}".format(self.display_name) @@ -20,10 +19,7 @@ def delete(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request( - 'DELETE', - 'files/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'files/{}'.format(self.id)) return File(self._requester, response.json()) def get_contents(self): @@ -32,10 +28,7 @@ def get_contents(self): :rtype: str """ - response = self._requester.request( - 'GET', - _url=self.url - ) + response = self._requester.request('GET', _url=self.url) return response.text def download(self, location): @@ -45,10 +38,7 @@ def download(self, location): :param location: The path to download to. :type location: str """ - response = self._requester.request( - 'GET', - _url=self.url - ) + response = self._requester.request('GET', _url=self.url) with open(location, 'wb') as file_out: file_out.write(response.content) diff --git a/canvasapi/folder.py b/canvasapi/folder.py index 22ae2f7b..614a1ab5 100644 --- a/canvasapi/folder.py +++ b/canvasapi/folder.py @@ -12,7 +12,6 @@ @python_2_unicode_compatible class Folder(CanvasObject): - def __str__(self): return "{}".format(self.full_name) @@ -33,7 +32,7 @@ def list_files(self, **kwargs): warnings.warn( "`list_files` is being deprecated and will be removed in a future " "version. Use `get_files` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_files(**kwargs) @@ -55,7 +54,7 @@ def get_files(self, **kwargs): self._requester, 'GET', 'folders/{}/files'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def delete(self, **kwargs): @@ -69,9 +68,7 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'DELETE', - 'folders/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'DELETE', 'folders/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) return Folder(self._requester, response.json()) @@ -92,7 +89,7 @@ def list_folders(self, **kwargs): warnings.warn( "`list_folders` is being deprecated and will be removed in a " "future version. Use `get_folders` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_folders(**kwargs) @@ -108,10 +105,7 @@ def get_folders(self, **kwargs): :class:`canvasapi.folder.Folder` """ return PaginatedList( - Folder, - self._requester, - 'GET', - 'folders/{}/folders'.format(self.id) + Folder, self._requester, 'GET', 'folders/{}/folders'.format(self.id) ) def create_folder(self, name, **kwargs): @@ -129,7 +123,7 @@ def create_folder(self, name, **kwargs): 'POST', 'folders/{}/folders'.format(self.id), name=name, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Folder(self._requester, response.json()) @@ -147,12 +141,7 @@ def upload(self, file, **kwargs): :rtype: tuple """ my_path = 'folders/{}/files'.format(self.id) - return Uploader( - self._requester, - my_path, - file, - **kwargs - ).start() + return Uploader(self._requester, my_path, file, **kwargs).start() def update(self, **kwargs): """ @@ -164,9 +153,7 @@ def update(self, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'PUT', - 'folders/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'folders/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) if 'name' in response.json(): @@ -194,7 +181,7 @@ def copy_file(self, source_file, **kwargs): response = self._requester.request( 'POST', 'folders/{}/copy_file'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) diff --git a/canvasapi/grading_period.py b/canvasapi/grading_period.py index bf91b9c3..9108aa99 100644 --- a/canvasapi/grading_period.py +++ b/canvasapi/grading_period.py @@ -9,7 +9,6 @@ @python_2_unicode_compatible class GradingPeriod(CanvasObject): - def __str__(self): return '{} ({})'.format(self.title, self.id) @@ -39,7 +38,7 @@ def update(self, grading_period, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/grading_periods/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -61,7 +60,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/grading_periods/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code diff --git a/canvasapi/grading_standard.py b/canvasapi/grading_standard.py index 32a9f97c..31f5d0d2 100644 --- a/canvasapi/grading_standard.py +++ b/canvasapi/grading_standard.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class GradingStandard(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) diff --git a/canvasapi/group.py b/canvasapi/group.py index a9775aff..99dc880e 100644 --- a/canvasapi/group.py +++ b/canvasapi/group.py @@ -15,7 +15,6 @@ @python_2_unicode_compatible class Group(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -39,9 +38,7 @@ def create_page(self, wiki_page, **kwargs): raise RequiredFieldMissing("Dictionary with key 'title' is required.") response = self._requester.request( - 'POST', - 'groups/{}/pages'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'POST', 'groups/{}/pages'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) page_json = response.json() @@ -63,7 +60,7 @@ def edit_front_page(self, **kwargs): response = self._requester.request( 'PUT', 'groups/{}/front_page'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) page_json = response.json() page_json.update({'group_id': self.id}) @@ -82,8 +79,7 @@ def show_front_page(self): from canvasapi.course import Page response = self._requester.request( - 'GET', - 'groups/{}/front_page'.format(self.id) + 'GET', 'groups/{}/front_page'.format(self.id) ) page_json = response.json() page_json.update({'group_id': self.id}) @@ -105,8 +101,7 @@ def get_page(self, url): from canvasapi.course import Page response = self._requester.request( - 'GET', - 'groups/{}/pages/{}'.format(self.id, url) + 'GET', 'groups/{}/pages/{}'.format(self.id, url) ) page_json = response.json() page_json.update({'group_id': self.id}) @@ -124,13 +119,14 @@ def get_pages(self, **kwargs): :class:`canvasapi.page.Page` """ from canvasapi.course import Page + return PaginatedList( Page, self._requester, 'GET', 'groups/{}/pages'.format(self.id), {'group_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def edit(self, **kwargs): @@ -143,9 +139,7 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.group.Group` """ response = self._requester.request( - 'PUT', - 'groups/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'groups/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) return Group(self._requester, response.json()) @@ -158,10 +152,7 @@ def delete(self): :rtype: :class:`canvasapi.group.Group` """ - response = self._requester.request( - 'DELETE', - 'groups/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'groups/{}'.format(self.id)) return Group(self._requester, response.json()) def invite(self, invitees): @@ -182,7 +173,7 @@ def invite(self, invitees): self._requester, 'POST', 'groups/{}/invite'.format(self.id), - invitees=invitees + invitees=invitees, ) def list_users(self, **kwargs): @@ -202,7 +193,7 @@ def list_users(self, **kwargs): warnings.warn( "`list_users` is being deprecated and will be removed in a future " "version. Use `get_users` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_users(**kwargs) @@ -218,12 +209,13 @@ def get_users(self, **kwargs): :class:`canvasapi.user.User` """ from canvasapi.user import User + return PaginatedList( User, self._requester, 'GET', 'groups/{}/users'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def remove_user(self, user): @@ -243,8 +235,7 @@ def remove_user(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'DELETE', - 'groups/{}/users/{}'.format(self.id, user_id), + 'DELETE', 'groups/{}/users/{}'.format(self.id, user_id) ) return User(self._requester, response.json()) @@ -268,10 +259,7 @@ def upload(self, file, **kwargs): from canvasapi.upload import Uploader return Uploader( - self._requester, - 'groups/{}/files'.format(self.id), - file, - **kwargs + self._requester, 'groups/{}/files'.format(self.id), file, **kwargs ).start() def preview_html(self, html): @@ -286,9 +274,7 @@ def preview_html(self, html): :rtype: str """ response = self._requester.request( - 'POST', - 'groups/{}/preview_html'.format(self.id), - html=html + 'POST', 'groups/{}/preview_html'.format(self.id), html=html ) return response.json().get('html', '') @@ -302,8 +288,7 @@ def get_activity_stream_summary(self): :rtype: dict """ response = self._requester.request( - 'GET', - 'groups/{}/activity_stream/summary'.format(self.id) + 'GET', 'groups/{}/activity_stream/summary'.format(self.id) ) return response.json() @@ -324,7 +309,7 @@ def list_memberships(self, **kwargs): warnings.warn( "`list_memberships` is being deprecated and will be removed in a " "future version. Use `get_memberships` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_memberships(**kwargs) @@ -344,7 +329,7 @@ def get_memberships(self, **kwargs): self._requester, 'GET', 'groups/{}/memberships'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_membership(self, user, membership_type): @@ -367,8 +352,7 @@ def get_membership(self, user, membership_type): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', - 'groups/{}/{}/{}'.format(self.id, membership_type, user_id) + 'GET', 'groups/{}/{}/{}'.format(self.id, membership_type, user_id) ) return GroupMembership(self._requester, response.json()) @@ -393,7 +377,7 @@ def create_membership(self, user, **kwargs): 'POST', 'groups/{}/memberships'.format(self.id), user_id=user_id, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GroupMembership(self._requester, response.json()) @@ -416,7 +400,7 @@ def update_membership(self, user, **kwargs): response = self._requester.request( 'PUT', 'groups/{}/users/{}'.format(self.id, user_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GroupMembership(self._requester, response.json()) @@ -435,8 +419,7 @@ def get_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', - 'groups/{}/discussion_topics/{}'.format(self.id, topic_id) + 'GET', 'groups/{}/discussion_topics/{}'.format(self.id, topic_id) ) response_json = response.json() @@ -457,12 +440,13 @@ def get_file(self, file, **kwargs): :rtype: :class:`canvasapi.file.File` """ from canvasapi.file import File + file_id = obj_or_id(file, "file", (File,)) response = self._requester.request( 'GET', 'groups/{}/files/{}'.format(self.id, file_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) @@ -481,8 +465,7 @@ def get_full_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', - 'groups/{}/discussion_topics/{}/view'.format(self.id, topic_id), + 'GET', 'groups/{}/discussion_topics/{}/view'.format(self.id, topic_id) ) return response.json() @@ -503,7 +486,7 @@ def get_discussion_topics(self, **kwargs): 'GET', 'groups/{}/discussion_topics'.format(self.id), {'group_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_discussion_topic(self, **kwargs): @@ -518,7 +501,7 @@ def create_discussion_topic(self, **kwargs): response = self._requester.request( 'POST', 'groups/{}/discussion_topics'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -550,9 +533,7 @@ def reorder_pinned_topics(self, order): raise ValueError("Param `order` must be a list, tuple, or string.") response = self._requester.request( - 'POST', - 'groups/{}/discussion_topics/reorder'.format(self.id), - order=order + 'POST', 'groups/{}/discussion_topics/reorder'.format(self.id), order=order ) return response.json().get('reorder') @@ -574,7 +555,7 @@ def list_external_feeds(self, **kwargs): warnings.warn( "`list_external_feeds` is being deprecated and will be removed in " "a future version. Use `get_external_feeds` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_external_feeds(**kwargs) @@ -590,11 +571,12 @@ def get_external_feeds(self, **kwargs): :class:`canvasapi.external_feed.ExternalFeed` """ from canvasapi.external_feed import ExternalFeed + return PaginatedList( ExternalFeed, self._requester, 'GET', - 'groups/{}/external_feeds'.format(self.id) + 'groups/{}/external_feeds'.format(self.id), ) def create_external_feed(self, url, **kwargs): @@ -609,11 +591,12 @@ def create_external_feed(self, url, **kwargs): :rtype: :class:`canvasapi.external_feed.ExternalFeed` """ from canvasapi.external_feed import ExternalFeed + response = self._requester.request( 'POST', 'groups/{}/external_feeds'.format(self.id), url=url, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return ExternalFeed(self._requester, response.json()) @@ -634,8 +617,7 @@ def delete_external_feed(self, feed): feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) response = self._requester.request( - 'DELETE', - 'groups/{}/external_feeds/{}'.format(self.id, feed_id) + 'DELETE', 'groups/{}/external_feeds/{}'.format(self.id, feed_id) ) return ExternalFeed(self._requester, response.json()) @@ -656,7 +638,7 @@ def list_files(self, **kwargs): warnings.warn( "`list_files` is being deprecated and will be removed in a future " "version. Use `get_files` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_files(**kwargs) @@ -678,7 +660,7 @@ def get_files(self, **kwargs): self._requester, 'GET', 'groups/{}/files'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_folder(self, folder): @@ -696,8 +678,7 @@ def get_folder(self, folder): folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - 'GET', - 'groups/{}/folders/{}'.format(self.id, folder_id) + 'GET', 'groups/{}/folders/{}'.format(self.id, folder_id) ) return Folder(self._requester, response.json()) @@ -719,7 +700,7 @@ def list_folders(self, **kwargs): warnings.warn( "`list_folders` is being deprecated and will be removed in a " "future version. Use `get_folders` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_folders(**kwargs) @@ -736,10 +717,7 @@ def get_folders(self, **kwargs): :class:`canvasapi.folder.Folder` """ return PaginatedList( - Folder, - self._requester, - 'GET', - 'groups/{}/folders'.format(self.id) + Folder, self._requester, 'GET', 'groups/{}/folders'.format(self.id) ) def create_folder(self, name, **kwargs): @@ -757,7 +735,7 @@ def create_folder(self, name, **kwargs): 'POST', 'groups/{}/folders'.format(self.id), name=name, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Folder(self._requester, response.json()) @@ -779,7 +757,7 @@ def list_tabs(self, **kwargs): warnings.warn( "`list_tabs` is being deprecated and will be removed in a future " "version. Use `get_tabs` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_tabs(**kwargs) @@ -801,7 +779,7 @@ def get_tabs(self, **kwargs): 'GET', 'groups/{}/tabs'.format(self.id), {'group_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_content_migration(self, migration_type, **kwargs): @@ -828,7 +806,7 @@ def create_content_migration(self, migration_type, **kwargs): response = self._requester.request( 'POST', 'groups/{}/content_migrations'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -850,12 +828,14 @@ def get_content_migration(self, content_migration, **kwargs): """ from canvasapi.content_migration import ContentMigration - migration_id = obj_or_id(content_migration, "content_migration", (ContentMigration,)) + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) + ) response = self._requester.request( 'GET', 'groups/{}/content_migrations/{}'.format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -881,7 +861,7 @@ def get_content_migrations(self, **kwargs): 'GET', 'groups/{}/content_migrations'.format(self.id), {'group_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_migration_systems(self, **kwargs): @@ -901,7 +881,7 @@ def get_migration_systems(self, **kwargs): self._requester, 'GET', 'groups/{}/content_migrations/migrators'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_assignment_override(self, assignment, **kwargs): @@ -921,8 +901,7 @@ def get_assignment_override(self, assignment, **kwargs): assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) response = self._requester.request( - 'GET', - 'groups/{}/assignments/{}/override'.format(self.id, assignment_id) + 'GET', 'groups/{}/assignments/{}/override'.format(self.id, assignment_id) ) response_json = response.json() response_json.update({'course_id': self.course_id}) @@ -945,10 +924,8 @@ def get_content_exports(self, **kwargs): ContentExport, self._requester, 'GET', - 'groups/{}/content_exports'.format( - self.id - ), - kwargs=combine_kwargs(**kwargs) + 'groups/{}/content_exports'.format(self.id), + kwargs=combine_kwargs(**kwargs), ) def get_content_export(self, content_export, **kwargs): @@ -969,11 +946,8 @@ def get_content_export(self, content_export, **kwargs): response = self._requester.request( 'GET', - 'groups/{}/content_exports/{}'.format( - self.id, - export_id - ), - _kwargs=combine_kwargs(**kwargs) + 'groups/{}/content_exports/{}'.format(self.id, export_id), + _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -996,17 +970,14 @@ def export_content(self, export_type, **kwargs): response = self._requester.request( 'POST', - 'groups/{}/content_exports'.format( - self.id, - ), - _kwargs=combine_kwargs(**kwargs) + 'groups/{}/content_exports'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @python_2_unicode_compatible class GroupMembership(CanvasObject): - def __str__(self): return "{} - {} ({})".format(self.user_id, self.group_id, self.id) @@ -1023,7 +994,7 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', 'groups/{}/memberships/{}'.format(self.group_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GroupMembership(self._requester, response.json()) @@ -1045,8 +1016,7 @@ def remove_user(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'DELETE', - 'groups/{}/users/{}'.format(self.id, user_id), + 'DELETE', 'groups/{}/users/{}'.format(self.id, user_id) ) return response.json() @@ -1061,15 +1031,13 @@ def remove_self(self): :rtype: dict """ response = self._requester.request( - 'DELETE', - 'groups/{}/memberships/self'.format(self.id), + 'DELETE', 'groups/{}/memberships/self'.format(self.id) ) return response.json() @python_2_unicode_compatible class GroupCategory(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -1085,7 +1053,7 @@ def create_group(self, **kwargs): response = self._requester.request( 'POST', 'group_categories/{}/groups'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Group(self._requester, response.json()) @@ -1101,7 +1069,7 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', 'group_categories/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return GroupCategory(self._requester, response.json()) @@ -1115,8 +1083,7 @@ def delete(self): :rtype: empty dict """ response = self._requester.request( - 'DELETE', - 'group_categories/{}'.format(self.id) + 'DELETE', 'group_categories/{}'.format(self.id) ) return response.json() @@ -1137,7 +1104,7 @@ def list_groups(self, **kwargs): warnings.warn( "`list_groups` is being deprecated and will be removed in a " "future version. Use `get_groups` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_groups(**kwargs) @@ -1153,10 +1120,7 @@ def get_groups(self, **kwargs): :class:`canvasapi.group.Group` """ return PaginatedList( - Group, - self._requester, - 'GET', - 'group_categories/{}/groups'.format(self.id) + Group, self._requester, 'GET', 'group_categories/{}/groups'.format(self.id) ) def list_users(self, **kwargs): @@ -1176,7 +1140,7 @@ def list_users(self, **kwargs): warnings.warn( "`list_users` is being deprecated and will be removed in a future version." " Use `get_users` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_users(**kwargs) @@ -1192,12 +1156,13 @@ def get_users(self, **kwargs): :class:`canvasapi.user.User` """ from canvasapi.user import User + return PaginatedList( User, self._requester, 'GET', 'group_categories/{}/users'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def assign_members(self, sync=False): @@ -1212,16 +1177,16 @@ def assign_members(self, sync=False): """ from canvasapi.user import User from canvasapi.progress import Progress + if sync: return PaginatedList( User, self._requester, 'POST', - 'group_categories/{}/assign_unassigned_members'.format(self.id) + 'group_categories/{}/assign_unassigned_members'.format(self.id), ) else: response = self._requester.request( - 'POST', - 'group_categories/{}/assign_unassigned_members'.format(self.id) + 'POST', 'group_categories/{}/assign_unassigned_members'.format(self.id) ) return Progress(self._requester, response.json()) diff --git a/canvasapi/login.py b/canvasapi/login.py index 48988963..d1948208 100644 --- a/canvasapi/login.py +++ b/canvasapi/login.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class Login(CanvasObject): - def __str__(self): return "{} ({})".format(self.id, self.unique_id) @@ -22,8 +21,7 @@ def delete(self): :rtype: :class:`canvasapi.login.Login` """ response = self._requester.request( - 'DELETE', - 'users/{}/logins/{}'.format(self.user_id, self.id) + 'DELETE', 'users/{}/logins/{}'.format(self.user_id, self.id) ) return Login(self._requester, response.json()) @@ -39,6 +37,6 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'accounts/{}/logins/{}'.format(self.account_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Login(self._requester, response.json()) diff --git a/canvasapi/module.py b/canvasapi/module.py index cc494f1c..6d526ce6 100644 --- a/canvasapi/module.py +++ b/canvasapi/module.py @@ -11,7 +11,6 @@ @python_2_unicode_compatible class Module(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -27,7 +26,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/modules/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) module_json = response.json() module_json.update({'course_id': self.course_id}) @@ -44,8 +43,7 @@ def delete(self): :rtype: :class:`canvasapi.module.Module` """ response = self._requester.request( - 'DELETE', - 'courses/{}/modules/{}'.format(self.course_id, self.id), + 'DELETE', 'courses/{}/modules/{}'.format(self.course_id, self.id) ) module_json = response.json() module_json.update({'course_id': self.course_id}) @@ -66,8 +64,7 @@ def relock(self): :rtype: :class:`canvasapi.module.Module` """ response = self._requester.request( - 'PUT', - 'courses/{}/modules/{}/relock'.format(self.course_id, self.id), + 'PUT', 'courses/{}/modules/{}/relock'.format(self.course_id, self.id) ) module_json = response.json() module_json.update({'course_id': self.course_id}) @@ -91,7 +88,7 @@ def list_module_items(self, **kwargs): warnings.warn( "`list_module_items` is being deprecated and will be removed in a " "future version. Use `get_module_items` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_module_items(**kwargs) @@ -112,7 +109,7 @@ def get_module_items(self, **kwargs): 'GET', 'courses/{}/modules/{}/items'.format(self.course_id, self.id), {'course_id': self.course_id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_module_item(self, module_item, **kwargs): @@ -131,8 +128,10 @@ def get_module_item(self, module_item, **kwargs): response = self._requester.request( 'GET', - 'courses/{}/modules/{}/items/{}'.format(self.course_id, self.id, module_item_id), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/modules/{}/items/{}'.format( + self.course_id, self.id, module_item_id + ), + _kwargs=combine_kwargs(**kwargs), ) module_item_json = response.json() module_item_json.update({'course_id': self.course_id}) @@ -155,14 +154,16 @@ def create_module_item(self, module_item, **kwargs): if 'content_id' in module_item: kwargs['module_item'] = module_item else: - raise RequiredFieldMissing("Dictionary with key 'content_id' is required.") + raise RequiredFieldMissing( + "Dictionary with key 'content_id' is required." + ) else: raise RequiredFieldMissing("Dictionary with key 'type' is required.") response = self._requester.request( 'POST', 'courses/{}/modules/{}/items'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) module_item_json = response.json() module_item_json.update({'course_id': self.course_id}) @@ -172,7 +173,6 @@ def create_module_item(self, module_item, **kwargs): @python_2_unicode_compatible class ModuleItem(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) @@ -188,8 +188,10 @@ def edit(self, **kwargs): """ response = self._requester.request( 'PUT', - 'courses/{}/modules/{}/items/{}'.format(self.course_id, self.module_id, self.id), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/modules/{}/items/{}'.format( + self.course_id, self.module_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) module_item_json = response.json() module_item_json.update({'course_id': self.course_id}) @@ -207,7 +209,9 @@ def delete(self): """ response = self._requester.request( 'DELETE', - 'courses/{}/modules/{}/items/{}'.format(self.course_id, self.module_id, self.id), + 'courses/{}/modules/{}/items/{}'.format( + self.course_id, self.module_id, self.id + ), ) module_item_json = response.json() module_item_json.update({'course_id': self.course_id}) @@ -225,7 +229,9 @@ def complete(self): """ response = self._requester.request( 'PUT', - 'courses/{}/modules/{}/items/{}/done'.format(self.course_id, self.module_id, self.id), + 'courses/{}/modules/{}/items/{}/done'.format( + self.course_id, self.module_id, self.id + ), ) module_item_json = response.json() module_item_json.update({'course_id': self.course_id}) @@ -243,7 +249,9 @@ def uncomplete(self): """ response = self._requester.request( 'DELETE', - 'courses/{}/modules/{}/items/{}/done'.format(self.course_id, self.module_id, self.id), + 'courses/{}/modules/{}/items/{}/done'.format( + self.course_id, self.module_id, self.id + ), ) module_item_json = response.json() module_item_json.update({'course_id': self.course_id}) diff --git a/canvasapi/notification_preference.py b/canvasapi/notification_preference.py index 177e4ff7..90a64330 100644 --- a/canvasapi/notification_preference.py +++ b/canvasapi/notification_preference.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class NotificationPreference(CanvasObject): - def __str__(self): return "{} ({})".format(self.notification, self.frequency) diff --git a/canvasapi/outcome.py b/canvasapi/outcome.py index f1dd8c48..b766efb0 100644 --- a/canvasapi/outcome.py +++ b/canvasapi/outcome.py @@ -10,7 +10,6 @@ @python_2_unicode_compatible class Outcome(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.url) @@ -25,9 +24,7 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - 'outcomes/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'outcomes/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) if 'id' in response.json(): @@ -38,12 +35,9 @@ def update(self, **kwargs): @python_2_unicode_compatible class OutcomeLink(CanvasObject): - def __str__(self): return "Group {} with Outcome {} ({})".format( - self.outcome_group, - self.outcome, - self.url + self.outcome_group, self.outcome, self.url ) def context_ref(self): @@ -63,10 +57,7 @@ def get_outcome(self): :rtype: :class:`canvasapi.outcome.Outcome` """ oid = self.outcome['id'] - response = self._requester.request( - 'GET', - 'outcomes/{}'.format(oid) - ) + response = self._requester.request('GET', 'outcomes/{}'.format(oid)) return Outcome(self._requester, response.json()) @@ -86,8 +77,7 @@ def get_outcome_group(self): """ ogid = self.outcome_group['id'] response = self._requester.request( - 'GET', - '{}/outcome_groups/{}'.format(self.context_ref(), ogid) + 'GET', '{}/outcome_groups/{}'.format(self.context_ref(), ogid) ) return OutcomeGroup(self._requester, response.json()) @@ -95,7 +85,6 @@ def get_outcome_group(self): @python_2_unicode_compatible class OutcomeGroup(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.url) @@ -124,7 +113,7 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', '{}/outcome_groups/{}'.format(self.context_ref(), self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) if 'id' in response.json(): @@ -147,8 +136,7 @@ def delete(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}/outcome_groups/{}'.format(self.context_ref(), self.id) + 'DELETE', '{}/outcome_groups/{}'.format(self.context_ref(), self.id) ) if 'id' in response.json(): @@ -178,7 +166,7 @@ def list_linked_outcomes(self, **kwargs): warnings.warn( "`list_linked_outcomes` is being deprecated and will be removed " "in a future version. Use `get_linked_outcomes` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_linked_outcomes(**kwargs) @@ -203,7 +191,7 @@ def get_linked_outcomes(self, **kwargs): self._requester, 'GET', '{}/outcome_groups/{}/outcomes'.format(self.context_ref(), self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def link_existing(self, outcome): @@ -228,10 +216,8 @@ def link_existing(self, outcome): response = self._requester.request( 'PUT', '{}/outcome_groups/{}/outcomes/{}'.format( - self.context_ref(), - self.id, - outcome_id - ) + self.context_ref(), self.id, outcome_id + ), ) return OutcomeLink(self._requester, response.json()) @@ -257,7 +243,7 @@ def link_new(self, title, **kwargs): 'POST', '{}/outcome_groups/{}/outcomes'.format(self.context_ref(), self.id), title=title, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return OutcomeLink(self._requester, response.json()) @@ -284,10 +270,8 @@ def unlink_outcome(self, outcome): response = self._requester.request( 'DELETE', '{}/outcome_groups/{}/outcomes/{}'.format( - self.context_ref(), - self.id, - outcome_id - ) + self.context_ref(), self.id, outcome_id + ), ) if 'context_id' in response.json(): @@ -317,7 +301,7 @@ def list_subgroups(self, **kwargs): warnings.warn( "`list_subgroups` is being deprecated and will be removed in a " "future version. Use `get_subgroups` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_subgroups(**kwargs) @@ -343,7 +327,7 @@ def get_subgroups(self, **kwargs): 'GET', '{}/outcome_groups/{}/subgroups'.format(self.context_ref(), self.id), {'context_type': self.context_type, 'context_id': self.context_id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_subgroup(self, title, **kwargs): @@ -367,7 +351,7 @@ def create_subgroup(self, title, **kwargs): 'POST', '{}/outcome_groups/{}/subgroups'.format(self.context_ref(), self.id), title=title, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return OutcomeGroup(self._requester, response.json()) @@ -389,12 +373,14 @@ def import_outcome_group(self, outcome_group): :returns: Itself as an OutcomeGroup object. :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ - source_outcome_group_id = obj_or_id(outcome_group, "outcome_group", (OutcomeGroup,)) + source_outcome_group_id = obj_or_id( + outcome_group, "outcome_group", (OutcomeGroup,) + ) response = self._requester.request( 'POST', '{}/outcome_groups/{}/import'.format(self.context_ref(), self.id), - source_outcome_group_id=source_outcome_group_id + source_outcome_group_id=source_outcome_group_id, ) return OutcomeGroup(self._requester, response.json()) diff --git a/canvasapi/page.py b/canvasapi/page.py index 83606145..1b0b7424 100644 --- a/canvasapi/page.py +++ b/canvasapi/page.py @@ -10,7 +10,6 @@ @python_2_unicode_compatible class Page(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.url) @@ -27,7 +26,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', '{}s/{}/pages/{}'.format(self.parent_type, self.parent_id, self.url), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) page_json = response.json() @@ -46,8 +45,7 @@ def delete(self): :rtype: :class:`canvasapi.page.Page` """ response = self._requester.request( - 'DELETE', - 'courses/{}/pages/{}'.format(self.course_id, self.url) + 'DELETE', 'courses/{}/pages/{}'.format(self.course_id, self.url) ) return Page(self._requester, response.json()) @@ -94,8 +92,7 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', - '{}s/{}'.format(self.parent_type, self.parent_id) + 'GET', '{}s/{}'.format(self.parent_type, self.parent_id) ) if self.parent_type == 'group': @@ -114,8 +111,10 @@ def show_latest_revision(self, **kwargs): """ response = self._requester.request( 'GET', - '{}s/{}/pages/{}/revisions/latest'.format(self.parent_type, self.parent_id, self.url), - _kwargs=combine_kwargs(**kwargs) + '{}s/{}/pages/{}/revisions/latest'.format( + self.parent_type, self.parent_id, self.url + ), + _kwargs=combine_kwargs(**kwargs), ) return PageRevision(self._requester, response.json()) @@ -137,12 +136,9 @@ def get_revision_by_id(self, revision, **kwargs): response = self._requester.request( 'GET', '{}s/{}/pages/{}/revisions/{}'.format( - self.parent_type, - self.parent_id, - self.url, - revision_id + self.parent_type, self.parent_id, self.url, revision_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) pagerev_json = response.json() if self.parent_type == "group": @@ -169,7 +165,7 @@ def list_revisions(self, **kwargs): warnings.warn( "`list_revisions` is being deprecated and will be removed in a " "future version. Use `get_revisions` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_revisions(**kwargs) @@ -188,8 +184,10 @@ def get_revisions(self, **kwargs): PageRevision, self._requester, 'GET', - '{}s/{}/pages/{}/revisions'.format(self.parent_type, self.parent_id, self.url), - _kwargs=combine_kwargs(**kwargs) + '{}s/{}/pages/{}/revisions'.format( + self.parent_type, self.parent_id, self.url + ), + _kwargs=combine_kwargs(**kwargs), ) def revert_to_revision(self, revision): @@ -209,10 +207,7 @@ def revert_to_revision(self, revision): response = self._requester.request( 'POST', '{}s/{}/pages/{}/revisions/{}'.format( - self.parent_type, - self.parent_id, - self.url, - revision_id + self.parent_type, self.parent_id, self.url, revision_id ), ) pagerev_json = response.json() @@ -226,7 +221,6 @@ def revert_to_revision(self, revision): @python_2_unicode_compatible class PageRevision(CanvasObject): - def __str__(self): return "{} ({})".format(self.updated_at, self.revision_id) @@ -273,8 +267,7 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', - '{}s/{}'.format(self.parent_type, self.parent_id) + 'GET', '{}s/{}'.format(self.parent_type, self.parent_id) ) if self.parent_type == 'group': diff --git a/canvasapi/page_view.py b/canvasapi/page_view.py index 6ee8e437..42891ce0 100644 --- a/canvasapi/page_view.py +++ b/canvasapi/page_view.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class PageView(CanvasObject): - def __str__(self): return "{} ({})".format(self.context_type, self.id) diff --git a/canvasapi/paginated_list.py b/canvasapi/paginated_list.py index 0e9c4094..58ab6782 100644 --- a/canvasapi/paginated_list.py +++ b/canvasapi/paginated_list.py @@ -9,8 +9,15 @@ class PaginatedList(object): """ def __init__( - self, content_class, requester, request_method, first_url, extra_attribs=None, - _root=None, **kwargs): + self, + content_class, + requester, + request_method, + first_url, + extra_attribs=None, + _root=None, + **kwargs + ): self._elements = list() @@ -61,9 +68,7 @@ def _has_next(self): def _get_next_page(self): response = self._requester.request( - self._request_method, - self._next_url, - **self._next_params + self._request_method, self._next_url, **self._next_params ) data = response.json() self._next_url = None @@ -71,7 +76,9 @@ def _get_next_page(self): next_link = response.links.get('next') regex = r'{}(.*)'.format(re.escape(self._requester.base_url)) - self._next_url = re.search(regex, next_link['url']).group(1) if next_link else None + self._next_url = ( + re.search(regex, next_link['url']).group(1) if next_link else None + ) self._next_params = {} diff --git a/canvasapi/peer_review.py b/canvasapi/peer_review.py index 740ea646..74e91dd1 100644 --- a/canvasapi/peer_review.py +++ b/canvasapi/peer_review.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class PeerReview(CanvasObject): - def __str__(self): return "{} {} ({})".format(self.asset_id, self.user_id, self.id) diff --git a/canvasapi/planner.py b/canvasapi/planner.py index 6c535d27..e8689d53 100644 --- a/canvasapi/planner.py +++ b/canvasapi/planner.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class PlannerNote(CanvasObject): - def __str__(self): return "{} {} ({})".format(self.title, self.todo_date, self.id) @@ -23,9 +22,7 @@ def update(self, **kwargs): """ response = self._requester.request( - 'PUT', - 'planner_notes/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'planner_notes/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) return PlannerNote(self._requester, response.json()) @@ -41,7 +38,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'planner_notes/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PlannerNote(self._requester, response.json()) @@ -49,7 +46,6 @@ def delete(self, **kwargs): @python_2_unicode_compatible class PlannerOverride(CanvasObject): - def __str__(self): return "{} {} ({})".format(self.plannable_id, self.marked_complete, self.id) @@ -66,7 +62,7 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', 'planner/overrides/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PlannerOverride(self._requester, response.json()) @@ -82,7 +78,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'planner/overrides/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PlannerOverride(self._requester, response.json()) diff --git a/canvasapi/poll.py b/canvasapi/poll.py index 85826f12..d2370d08 100644 --- a/canvasapi/poll.py +++ b/canvasapi/poll.py @@ -12,7 +12,6 @@ @python_2_unicode_compatible class Poll(CanvasObject): - def __str__(self): return "{} ({})".format(self.question, self.id) @@ -27,17 +26,17 @@ def update(self, poll, **kwargs): :type poll: list :rtype: :class:`canvasapi.poll.Poll` """ - if isinstance(poll, list) and isinstance(poll[0], dict) and 'question' in poll[0]: + if ( + isinstance(poll, list) + and isinstance(poll[0], dict) + and 'question' in poll[0] + ): kwargs['poll'] = poll else: - raise RequiredFieldMissing( - "Dictionary with key 'question' is required." - ) + raise RequiredFieldMissing("Dictionary with key 'question' is required.") response = self._requester.request( - 'PUT', - 'polls/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'polls/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) return Poll(self._requester, response.json()['polls'][0]) @@ -53,9 +52,7 @@ def delete(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'polls/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'DELETE', 'polls/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) return response.status_code == 204 @@ -75,7 +72,7 @@ def get_choices(self, **kwargs): 'GET', 'polls/{}/poll_choices'.format(self.id), _root='poll_choices', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_choice(self, poll_choice, **kwargs): @@ -92,7 +89,7 @@ def get_choice(self, poll_choice, **kwargs): response = self._requester.request( 'GET', 'polls/{}/poll_choices/{}'.format(self.id, poll_choice_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollChoice(self._requester, response.json()['poll_choices'][0]) @@ -114,14 +111,12 @@ def create_choice(self, poll_choice, **kwargs): ): kwargs['poll_choice'] = poll_choice else: - raise RequiredFieldMissing( - "Dictionary with key 'text' is required." - ) + raise RequiredFieldMissing("Dictionary with key 'text' is required.") response = self._requester.request( 'POST', 'polls/{}/poll_choices'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollChoice(self._requester, response.json()['poll_choices'][0]) @@ -141,7 +136,7 @@ def get_sessions(self, **kwargs): 'GET', 'polls/{}/poll_sessions'.format(self.id), _root='poll_sessions', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_session(self, poll_session, **kwargs): @@ -161,7 +156,7 @@ def get_session(self, poll_session, **kwargs): response = self._requester.request( 'GET', 'polls/{}/poll_sessions/{}'.format(self.id, poll_session_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSession(self._requester, response.json()['poll_sessions'][0]) @@ -186,13 +181,11 @@ def create_session(self, poll_session, **kwargs): ): kwargs['poll_session'] = poll_session else: - raise RequiredFieldMissing( - "Dictionary with key 'course_id' is required." - ) + raise RequiredFieldMissing("Dictionary with key 'course_id' is required.") response = self._requester.request( 'POST', 'polls/{}/poll_sessions'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSession(self._requester, response.json()['poll_sessions'][0]) diff --git a/canvasapi/poll_choice.py b/canvasapi/poll_choice.py index 3d2b1ffb..d934b043 100644 --- a/canvasapi/poll_choice.py +++ b/canvasapi/poll_choice.py @@ -9,7 +9,6 @@ @python_2_unicode_compatible class PollChoice(CanvasObject): - def __str__(self): return "{} ({})".format(self.text, self.id) @@ -25,18 +24,19 @@ def update(self, poll_choice, **kwargs): :type poll_choice: list :rtype: :class:`canvasapi.poll_choice.PollChoice` """ - if (isinstance(poll_choice, list) and isinstance(poll_choice[0], dict) - and 'text' in poll_choice[0]): + if ( + isinstance(poll_choice, list) + and isinstance(poll_choice[0], dict) + and 'text' in poll_choice[0] + ): kwargs['poll_choice'] = poll_choice else: - raise RequiredFieldMissing( - "Dictionary with key 'text' is required." - ) + raise RequiredFieldMissing("Dictionary with key 'text' is required.") response = self._requester.request( 'PUT', 'polls/{}/poll_choices/{}'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollChoice(self._requester, response.json()['poll_choices'][0]) @@ -54,6 +54,6 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'polls/{}/poll_choices/{}'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 diff --git a/canvasapi/poll_session.py b/canvasapi/poll_session.py index 88d620bf..3ece0d63 100644 --- a/canvasapi/poll_session.py +++ b/canvasapi/poll_session.py @@ -10,7 +10,6 @@ @python_2_unicode_compatible class PollSession(CanvasObject): - def __str__(self): return "{} ({})".format(self.poll_id, self.id) @@ -35,14 +34,12 @@ def update(self, poll_session, **kwargs): ): kwargs['poll_session'] = poll_session else: - raise RequiredFieldMissing( - "Dictionary with key 'course_id' is required." - ) + raise RequiredFieldMissing("Dictionary with key 'course_id' is required.") response = self._requester.request( 'PUT', 'polls/{}/poll_sessions/{}'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSession(self._requester, response.json()['poll_sessions'][0]) @@ -60,7 +57,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'polls/{}/poll_sessions/{}'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 @@ -76,7 +73,7 @@ def open(self, **kwargs): response = self._requester.request( 'GET', 'polls/{}/poll_sessions/{}/open'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSession(self._requester, response.json()['poll_sessions'][0]) @@ -92,7 +89,7 @@ def close(self, **kwargs): response = self._requester.request( 'GET', 'polls/{}/poll_sessions/{}/close'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSession(self._requester, response.json()['poll_sessions'][0]) @@ -108,16 +105,16 @@ def get_submission(self, poll_submission, **kwargs): :rtype: :class:`canvasapi.poll_submission.PollSubmission` """ - poll_submission_id = obj_or_id(poll_submission, "poll_submission", (PollSubmission,)) + poll_submission_id = obj_or_id( + poll_submission, "poll_submission", (PollSubmission,) + ) response = self._requester.request( 'GET', 'polls/{}/poll_sessions/{}/poll_submissions/{}'.format( - self.poll_id, - self.id, - poll_submission_id + self.poll_id, self.id, poll_submission_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSubmission(self._requester, response.json()['poll_submissions'][0]) @@ -148,6 +145,6 @@ def create_submission(self, poll_submissions, **kwargs): response = self._requester.request( 'POST', 'polls/{}/poll_sessions/{}/poll_submissions'.format(self.poll_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return PollSubmission(self._requester, response.json()['poll_submissions'][0]) diff --git a/canvasapi/poll_submission.py b/canvasapi/poll_submission.py index e69f53f8..1e1098e1 100644 --- a/canvasapi/poll_submission.py +++ b/canvasapi/poll_submission.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class PollSubmission(CanvasObject): - def __str__(self): return "{} ({})".format(self.poll_choice_id, self.id) diff --git a/canvasapi/progress.py b/canvasapi/progress.py index bb9e6b18..e4d07873 100644 --- a/canvasapi/progress.py +++ b/canvasapi/progress.py @@ -7,7 +7,6 @@ @python_2_unicode_compatible class Progress(CanvasObject): - def __str__(self): return "{} - {} ({})".format(self.tag, self.workflow_state, self.id) @@ -20,10 +19,7 @@ def query(self): :rtype: :class:`canvasapi.progress.Progress` """ - response = self._requester.request( - 'GET', - 'progress/{}'.format(self.id) - ) + response = self._requester.request('GET', 'progress/{}'.format(self.id)) response_json = response.json() super(Progress, self).set_attributes(response_json) diff --git a/canvasapi/quiz.py b/canvasapi/quiz.py index 3f48df04..512e28b8 100644 --- a/canvasapi/quiz.py +++ b/canvasapi/quiz.py @@ -13,7 +13,6 @@ @python_2_unicode_compatible class Quiz(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) @@ -30,7 +29,7 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/quizzes/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) quiz_json = response.json() quiz_json.update({'course_id': self.course_id}) @@ -49,7 +48,7 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/quizzes/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) quiz_json = response.json() quiz_json.update({'course_id': self.course_id}) @@ -72,7 +71,7 @@ def get_quiz_group(self, id, **kwargs): response = self._requester.request( 'GET', 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.id, id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -104,7 +103,12 @@ def create_question_group(self, quiz_groups, **kwargs): if not isinstance(quiz_groups[0], dict): raise ValueError("Param `quiz_groups must contain a dictionary") - param_list = ['name', 'pick_count', 'question_points', 'assessment_question_bank_id'] + param_list = [ + 'name', + 'pick_count', + 'question_points', + 'assessment_question_bank_id', + ] if not any(param in quiz_groups[0] for param in param_list): raise RequiredFieldMissing("quiz_groups must contain at least 1 parameter.") @@ -113,7 +117,7 @@ def create_question_group(self, quiz_groups, **kwargs): response = self._requester.request( 'POST', 'courses/{}/quizzes/{}/groups'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -134,7 +138,7 @@ def create_question(self, **kwargs): response = self._requester.request( 'POST', 'courses/{}/quizzes/{}/questions'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) @@ -158,11 +162,9 @@ def get_question(self, question, **kwargs): response = self._requester.request( 'GET', 'courses/{}/quizzes/{}/questions/{}'.format( - self.course_id, - self.id, - question_id + self.course_id, self.id, question_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) @@ -185,7 +187,7 @@ def get_questions(self, **kwargs): 'GET', 'courses/{}/quizzes/{}/questions'.format(self.course_id, self.id), {'course_id': self.course_id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def set_extensions(self, quiz_extensions, **kwargs): @@ -235,10 +237,12 @@ def set_extensions(self, quiz_extensions, **kwargs): response = self._requester.request( 'POST', 'courses/{}/quizzes/{}/extensions'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) extension_list = response.json()['quiz_extensions'] - return [QuizExtension(self._requester, extension) for extension in extension_list] + return [ + QuizExtension(self._requester, extension) for extension in extension_list + ] def get_all_quiz_submissions(self, **kwargs): """ @@ -256,7 +260,7 @@ def get_all_quiz_submissions(self, **kwargs): warnings.warn( "`get_all_quiz_submissions` is being deprecated and will be removed in a " "future version. Use `get_submissions` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_submissions(**kwargs) @@ -275,12 +279,9 @@ def get_submissions(self, **kwargs): QuizSubmission, self._requester, 'GET', - 'courses/{}/quizzes/{}/submissions'.format( - self.course_id, - self.id - ), + 'courses/{}/quizzes/{}/submissions'.format(self.course_id, self.id), _root='quiz_submissions', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_quiz_submission(self, quiz_submission, **kwargs): @@ -295,16 +296,16 @@ def get_quiz_submission(self, quiz_submission, **kwargs): :rtype: :class:`canvasapi.quiz.QuizSubmission` """ - quiz_submission_id = obj_or_id(quiz_submission, "quiz_submission", (QuizSubmission,)) + quiz_submission_id = obj_or_id( + quiz_submission, "quiz_submission", (QuizSubmission,) + ) response = self._requester.request( 'GET', 'courses/{}/quizzes/{}/submissions/{}'.format( - self.course_id, - self.id, - quiz_submission_id + self.course_id, self.id, quiz_submission_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json()["quiz_submissions"][0] @@ -324,11 +325,8 @@ def create_submission(self, **kwargs): """ response = self._requester.request( 'POST', - 'courses/{}/quizzes/{}/submissions'.format( - self.course_id, - self.id - ), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/quizzes/{}/submissions'.format(self.course_id, self.id), + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json()["quiz_submissions"][0] @@ -339,7 +337,6 @@ def create_submission(self, **kwargs): @python_2_unicode_compatible class QuizSubmission(CanvasObject): - def __str__(self): return "Quiz {} - User {} ({})".format(self.quiz_id, self.user_id, self.id) @@ -373,11 +370,9 @@ def complete(self, validation_token=None, **kwargs): response = self._requester.request( 'POST', 'courses/{}/quizzes/{}/submissions/{}/complete'.format( - self.course_id, - self.quiz_id, - self.id + self.course_id, self.quiz_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json()["quiz_submissions"][0] @@ -396,11 +391,9 @@ def get_times(self, **kwargs): response = self._requester.request( 'GET', 'courses/{}/quizzes/{}/submissions/{}/time'.format( - self.course_id, - self.quiz_id, - self.id + self.course_id, self.quiz_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json() @@ -420,11 +413,9 @@ def update_score_and_comments(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/quizzes/{}/submissions/{}'.format( - self.course_id, - self.quiz_id, - self.id + self.course_id, self.quiz_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json()["quiz_submissions"][0] @@ -448,10 +439,7 @@ def get_submission_questions(self, **kwargs): questions = list() for question in response.json().get("quiz_submission_questions", []): - question.update({ - 'quiz_submission_id': self.id, - 'attempt': self.attempt - }) + question.update({'quiz_submission_id': self.id, 'attempt': self.attempt}) questions.append(QuizSubmissionQuestion(self._requester, question)) return questions @@ -485,16 +473,18 @@ def answer_submission_questions(self, validation_token=None, **kwargs): response = self._requester.request( 'POST', 'quiz_submissions/{}/questions'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) questions = list() for question in response.json().get('quiz_submission_questions', []): - question.update({ - 'quiz_submission_id': self.id, - 'validation_token': kwargs['validation_token'], - 'attempt': self.attempt - }) + question.update( + { + 'quiz_submission_id': self.id, + 'validation_token': kwargs['validation_token'], + 'attempt': self.attempt, + } + ) questions.append(QuizSubmissionQuestion(self._requester, question)) return questions @@ -502,14 +492,12 @@ def answer_submission_questions(self, validation_token=None, **kwargs): @python_2_unicode_compatible class QuizExtension(CanvasObject): - def __str__(self): return "{}-{}".format(self.quiz_id, self.user_id) @python_2_unicode_compatible class QuizQuestion(CanvasObject): - def __str__(self): return "{} ({})".format(self.question_name, self.id) @@ -526,11 +514,9 @@ def delete(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/quizzes/{}/questions/{}'.format( - self.course_id, - self.quiz_id, - self.id + self.course_id, self.quiz_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 @@ -547,11 +533,9 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/quizzes/{}/questions/{}'.format( - self.course_id, - self.quiz_id, - self.id + self.course_id, self.quiz_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) @@ -562,7 +546,6 @@ def edit(self, **kwargs): @python_2_unicode_compatible class QuizSubmissionQuestion(CanvasObject): - def __str__(self): return "QuizSubmissionQuestion #{}".format(self.id) @@ -594,15 +577,19 @@ def flag(self, validation_token=None, **kwargs): response = self._requester.request( 'PUT', - 'quiz_submissions/{}/questions/{}/flag'.format(self.quiz_submission_id, self.id), - _kwargs=combine_kwargs(**kwargs) + 'quiz_submissions/{}/questions/{}/flag'.format( + self.quiz_submission_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) question = response.json()['quiz_submission_questions'][0] - question.update({ - 'validation_token': kwargs['validation_token'], - 'quiz_submission_id': self.quiz_submission_id - }) + question.update( + { + 'validation_token': kwargs['validation_token'], + 'quiz_submission_id': self.quiz_submission_id, + } + ) super(QuizSubmissionQuestion, self).set_attributes(question) return True @@ -635,15 +622,19 @@ def unflag(self, validation_token=None, **kwargs): response = self._requester.request( 'PUT', - 'quiz_submissions/{}/questions/{}/unflag'.format(self.quiz_submission_id, self.id), - _kwargs=combine_kwargs(**kwargs) + 'quiz_submissions/{}/questions/{}/unflag'.format( + self.quiz_submission_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) question = response.json()['quiz_submission_questions'][0] - question.update({ - 'validation_token': kwargs['validation_token'], - 'quiz_submission_id': self.quiz_submission_id - }) + question.update( + { + 'validation_token': kwargs['validation_token'], + 'quiz_submission_id': self.quiz_submission_id, + } + ) super(QuizSubmissionQuestion, self).set_attributes(question) return True diff --git a/canvasapi/quiz_group.py b/canvasapi/quiz_group.py index b4772a28..9a4fb15d 100644 --- a/canvasapi/quiz_group.py +++ b/canvasapi/quiz_group.py @@ -9,7 +9,6 @@ @python_2_unicode_compatible class QuizGroup(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -46,7 +45,7 @@ def update(self, id, quiz_groups, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.quiz_id, id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) successful = 'name' in response.json().get('quiz_groups')[0] @@ -70,9 +69,9 @@ def delete(self, id): """ response = self._requester.request( 'DELETE', - 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.quiz_id, id) + 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.quiz_id, id), ) - return (response.status_code == 204) + return response.status_code == 204 def reorder_question_group(self, id, order, **kwargs): """ @@ -107,8 +106,10 @@ def reorder_question_group(self, id, order, **kwargs): response = self._requester.request( 'POST', - 'courses/{}/quizzes/{}/groups/{}/reorder'.format(self.course_id, self.quiz_id, id), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/quizzes/{}/groups/{}/reorder'.format( + self.course_id, self.quiz_id, id + ), + _kwargs=combine_kwargs(**kwargs), ) - return (response.status_code == 204) + return response.status_code == 204 diff --git a/canvasapi/rubric.py b/canvasapi/rubric.py index e877995e..4ff44abf 100644 --- a/canvasapi/rubric.py +++ b/canvasapi/rubric.py @@ -7,6 +7,5 @@ @python_2_unicode_compatible class Rubric(CanvasObject): - def __str__(self): return "{} ({})".format(self.title, self.id) diff --git a/canvasapi/section.py b/canvasapi/section.py index 54869372..5b2ca655 100644 --- a/canvasapi/section.py +++ b/canvasapi/section.py @@ -14,13 +14,8 @@ @python_2_unicode_compatible class Section(CanvasObject): - def __str__(self): - return '{} - {} ({})'.format( - self.name, - self.course_id, - self.id, - ) + return '{} - {} ({})'.format(self.name, self.course_id, self.id) def get_assignment_override(self, assignment, **kwargs): """ @@ -39,8 +34,7 @@ def get_assignment_override(self, assignment, **kwargs): assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) response = self._requester.request( - 'GET', - 'sections/{}/assignments/{}/override'.format(self.id, assignment_id) + 'GET', 'sections/{}/assignments/{}/override'.format(self.id, assignment_id) ) response_json = response.json() response_json.update({'course_id': self.course_id}) @@ -64,7 +58,7 @@ def get_enrollments(self, **kwargs): self._requester, 'GET', 'sections/{}/enrollments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def cross_list_section(self, new_course): @@ -84,8 +78,7 @@ def cross_list_section(self, new_course): new_course_id = obj_or_id(new_course, "new_course", (Course,)) response = self._requester.request( - 'POST', - 'sections/{}/crosslist/{}'.format(self.id, new_course_id) + 'POST', 'sections/{}/crosslist/{}'.format(self.id, new_course_id) ) return Section(self._requester, response.json()) @@ -99,8 +92,7 @@ def decross_list_section(self): :rtype: :class:`canvasapi.section.Section` """ response = self._requester.request( - 'DELETE', - 'sections/{}/crosslist'.format(self.id) + 'DELETE', 'sections/{}/crosslist'.format(self.id) ) return Section(self._requester, response.json()) @@ -114,9 +106,7 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.section.Section` """ response = self._requester.request( - 'PUT', - 'sections/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'sections/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) if 'name' in response.json(): @@ -133,10 +123,7 @@ def delete(self): :rtype: :class:`canvasapi.section.Section` """ - response = self._requester.request( - 'DELETE', - 'sections/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'sections/{}'.format(self.id)) return Section(self._requester, response.json()) def submit_assignment(self, assignment, submission, **kwargs): @@ -162,15 +149,14 @@ def submit_assignment(self, assignment, submission, **kwargs): warnings.warn( 'Section.submit_assignment() is deprecated and will be removed ' 'in the future. Use Assignment.submit() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - assignment = Assignment(self._requester, { - 'course_id': self.course_id, - 'section_id': self.id, - 'id': assignment_id - }) + assignment = Assignment( + self._requester, + {'course_id': self.course_id, 'section_id': self.id, 'id': assignment_id}, + ) return assignment.submit(submission, **kwargs) def list_submissions(self, assignment, **kwargs): @@ -195,15 +181,14 @@ def list_submissions(self, assignment, **kwargs): warnings.warn( 'Section.list_submissions() is deprecated and will be removed ' 'in the future. Use Assignment.get_submissions() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - assignment = Assignment(self._requester, { - 'course_id': self.course_id, - 'section_id': self.id, - 'id': assignment_id - }) + assignment = Assignment( + self._requester, + {'course_id': self.course_id, 'section_id': self.id, 'id': assignment_id}, + ) return assignment.get_submissions(**kwargs) @@ -226,7 +211,7 @@ def list_multiple_submissions(self, **kwargs): "`list_multiple_submissions`" " is being deprecated and will be removed in a future version." " Use `get_multiple_submissions` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_multiple_submissions(**kwargs) @@ -281,16 +266,15 @@ def get_submission(self, assignment, user, **kwargs): warnings.warn( 'Section.get_submission() is deprecated and will be removed ' 'in the future. Use Assignment.get_submission() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - assignment = Assignment(self._requester, { - 'course_id': self.course_id, - 'section_id': self.id, - 'id': assignment_id - }) + assignment = Assignment( + self._requester, + {'course_id': self.course_id, 'section_id': self.id, 'id': assignment_id}, + ) return assignment.get_submission(user, **kwargs) @@ -318,17 +302,20 @@ def update_submission(self, assignment, user, **kwargs): warnings.warn( 'Section.update_submission() is deprecated and will be removed ' 'in the future. Use Submission.edit() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) user_id = obj_or_id(user, "user", (User,)) - submission = Submission(self._requester, { - 'course_id': self.course_id, - 'assignment_id': assignment_id, - 'user_id': user_id - }) + submission = Submission( + self._requester, + { + 'course_id': self.course_id, + 'assignment_id': assignment_id, + 'user_id': user_id, + }, + ) return submission.edit(**kwargs) @@ -357,17 +344,20 @@ def mark_submission_as_read(self, assignment, user, **kwargs): warnings.warn( 'Section.mark_submission_as_read() is deprecated and will be ' 'removed in the future. Use Submission.mark_read() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) user_id = obj_or_id(user, "user", (User,)) - submission = Submission(self._requester, { - 'course_id': self.course_id, - 'assignment_id': assignment_id, - 'user_id': user_id - }) + submission = Submission( + self._requester, + { + 'course_id': self.course_id, + 'assignment_id': assignment_id, + 'user_id': user_id, + }, + ) return submission.mark_read(**kwargs) def mark_submission_as_unread(self, assignment, user, **kwargs): @@ -395,17 +385,20 @@ def mark_submission_as_unread(self, assignment, user, **kwargs): warnings.warn( 'Section.mark_submission_as_unread() is deprecated and will be ' 'removed in the future. Use Submission.mark_unread() instead.', - DeprecationWarning + DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) user_id = obj_or_id(user, "user", (User,)) - submission = Submission(self._requester, { - 'course_id': self.course_id, - 'assignment_id': assignment_id, - 'user_id': user_id - }) + submission = Submission( + self._requester, + { + 'course_id': self.course_id, + 'assignment_id': assignment_id, + 'user_id': user_id, + }, + ) return submission.mark_unread(**kwargs) def submissions_bulk_update(self, **kwargs): @@ -420,9 +413,7 @@ def submissions_bulk_update(self, **kwargs): """ response = self._requester.request( 'POST', - 'sections/{}/submissions/update_grades'.format( - self.id - ), - _kwargs=combine_kwargs(**kwargs) + 'sections/{}/submissions/update_grades'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) diff --git a/canvasapi/sis_import.py b/canvasapi/sis_import.py index 4adbdf8b..2bb4e6e5 100644 --- a/canvasapi/sis_import.py +++ b/canvasapi/sis_import.py @@ -9,7 +9,6 @@ @python_2_unicode_compatible class SisImport(CanvasObject): - def __str__(self): # pragma: no cover return "{} ({})".format(self.workflow_state, self.id) @@ -25,7 +24,7 @@ def abort(self, **kwargs): response = self._requester.request( 'PUT', 'accounts/{}/sis_imports/{}/abort'.format(self.account_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return SisImport(self._requester, response.json()) @@ -40,7 +39,9 @@ def restore_states(self, **kwargs): """ response = self._requester.request( 'PUT', - 'accounts/{}/sis_imports/{}/restore_states'.format(self.account_id, self.id), - _kwargs=combine_kwargs(**kwargs) + 'accounts/{}/sis_imports/{}/restore_states'.format( + self.account_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) diff --git a/canvasapi/submission.py b/canvasapi/submission.py index d36be907..7fa5c2b6 100644 --- a/canvasapi/submission.py +++ b/canvasapi/submission.py @@ -11,7 +11,6 @@ @python_2_unicode_compatible class Submission(CanvasObject): - def __str__(self): return '{}-{}'.format(self.assignment_id, self.user_id) @@ -35,10 +34,9 @@ def create_submission_peer_review(self, user, **kwargs): response = self._requester.request( 'POST', 'courses/{}/assignments/{}/submissions/{}/peer_reviews'.format( - self.course_id, - self.assignment_id, - self.id), - _kwargs=combine_kwargs(**kwargs) + self.course_id, self.assignment_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) return PeerReview(self._requester, response.json()) @@ -63,10 +61,9 @@ def delete_submission_peer_review(self, user, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/assignments/{}/submissions/{}/peer_reviews'.format( - self.course_id, - self.assignment_id, - self.id), - _kwargs=combine_kwargs(**kwargs) + self.course_id, self.assignment_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) return PeerReview(self._requester, response.json()) @@ -82,11 +79,9 @@ def edit(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/assignments/{}/submissions/{}'.format( - self.course_id, - self.assignment_id, - self.user_id + self.course_id, self.assignment_id, self.user_id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update(course_id=self.course_id) @@ -108,10 +103,8 @@ def mark_read(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/assignments/{}/submissions/{}/read'.format( - self.course_id, - self.assignment_id, - self.user_id - ) + self.course_id, self.assignment_id, self.user_id + ), ) return response.status_code == 204 @@ -129,10 +122,8 @@ def mark_unread(self, **kwargs): response = self._requester.request( 'DELETE', 'courses/{}/assignments/{}/submissions/{}/read'.format( - self.course_id, - self.assignment_id, - self.user_id - ) + self.course_id, self.assignment_id, self.user_id + ), ) return response.status_code == 204 @@ -151,9 +142,10 @@ def get_submission_peer_reviews(self, **kwargs): PeerReview, self._requester, 'GET', - 'courses/{}/assignments/{}/submissions/{}/peer_reviews' - .format(self.course_id, self.assignment_id, self.id), - _kwargs=combine_kwargs(**kwargs) + 'courses/{}/assignments/{}/submissions/{}/peer_reviews'.format( + self.course_id, self.assignment_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), ) def upload_comment(self, file, **kwargs): @@ -173,20 +165,14 @@ def upload_comment(self, file, **kwargs): response = Uploader( self._requester, 'courses/{}/assignments/{}/submissions/{}/comments/files'.format( - self.course_id, - self.assignment_id, - self.user_id + self.course_id, self.assignment_id, self.user_id ), file, **kwargs ).start() if response[0]: - self.edit( - comment={ - 'file_ids': [response[1]['id']] - } - ) + self.edit(comment={'file_ids': [response[1]['id']]}) return response diff --git a/canvasapi/tab.py b/canvasapi/tab.py index 7f0c7ebf..a9e321f9 100644 --- a/canvasapi/tab.py +++ b/canvasapi/tab.py @@ -8,7 +8,6 @@ @python_2_unicode_compatible class Tab(CanvasObject): - def __str__(self): return "{} ({})".format(self.label, self.id) @@ -30,7 +29,7 @@ def update(self, **kwargs): response = self._requester.request( 'PUT', 'courses/{}/tabs/{}'.format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() response_json.update({'course_id': self.course_id}) diff --git a/canvasapi/upload.py b/canvasapi/upload.py index d7957648..de685701 100644 --- a/canvasapi/upload.py +++ b/canvasapi/upload.py @@ -62,9 +62,7 @@ def request_upload_token(self, file): self.kwargs['size'] = os.fstat(file.fileno()).st_size response = self._requester.request( - 'POST', - self.url, - _kwargs=combine_kwargs(**self.kwargs) + 'POST', self.url, _kwargs=combine_kwargs(**self.kwargs) ) return self.upload(response, file) @@ -94,7 +92,7 @@ def upload(self, response, file): use_auth=False, _url=response.get('upload_url'), file=file, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) # remove `while(1);` that may appear at the top of a response diff --git a/canvasapi/user.py b/canvasapi/user.py index 4e11cd8e..87a9817e 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -14,7 +14,6 @@ @python_2_unicode_compatible class User(CanvasObject): - def __str__(self): return "{} ({})".format(self.name, self.id) @@ -27,10 +26,7 @@ def get_profile(self, **kwargs): :rtype: dict """ - response = self._requester.request( - 'GET', - 'users/{}/profile'.format(self.id) - ) + response = self._requester.request('GET', 'users/{}/profile'.format(self.id)) return response.json() def get_page_views(self, **kwargs): @@ -50,7 +46,7 @@ def get_page_views(self, **kwargs): self._requester, 'GET', 'users/{}/page_views'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_courses(self, **kwargs): @@ -70,7 +66,7 @@ def get_courses(self, **kwargs): self._requester, 'GET', 'users/{}/courses'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_missing_submissions(self): @@ -90,7 +86,7 @@ def get_missing_submissions(self): Assignment, self._requester, 'GET', - 'users/{}/missing_submissions'.format(self.id) + 'users/{}/missing_submissions'.format(self.id), ) def update_settings(self, **kwargs): @@ -103,9 +99,7 @@ def update_settings(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'PUT', - 'users/{}/settings'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'users/{}/settings'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -123,8 +117,7 @@ def get_color(self, asset_string): :rtype: dict """ response = self._requester.request( - 'GET', - 'users/{}/colors/{}'.format(self.id, asset_string) + 'GET', 'users/{}/colors/{}'.format(self.id, asset_string) ) return response.json() @@ -137,10 +130,7 @@ def get_colors(self): :rtype: dict """ - response = self._requester.request( - 'GET', - 'users/{}/colors'.format(self.id) - ) + response = self._requester.request('GET', 'users/{}/colors'.format(self.id)) return response.json() def update_color(self, asset_string, hexcode): @@ -162,9 +152,7 @@ def update_color(self, asset_string, hexcode): :rtype: dict """ response = self._requester.request( - 'PUT', - 'users/{}/colors/{}'.format(self.id, asset_string), - hexcode=hexcode + 'PUT', 'users/{}/colors/{}'.format(self.id, asset_string), hexcode=hexcode ) return response.json() @@ -178,9 +166,7 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.user.User` """ response = self._requester.request( - 'PUT', - 'users/{}'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + 'PUT', 'users/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) ) super(User, self).set_attributes(response.json()) return self @@ -197,11 +183,10 @@ def merge_into(self, destination_user): :rtype: :class:`canvasapi.user.User` """ - dest_user_id = obj_or_id(destination_user, 'destination_user', (User, )) + dest_user_id = obj_or_id(destination_user, 'destination_user', (User,)) response = self._requester.request( - 'PUT', - 'users/{}/merge_into/{}'.format(self.id, dest_user_id), + 'PUT', 'users/{}/merge_into/{}'.format(self.id, dest_user_id) ) super(User, self).set_attributes(response.json()) return self @@ -219,10 +204,7 @@ def get_avatars(self): from canvasapi.avatar import Avatar return PaginatedList( - Avatar, - self._requester, - 'GET', - 'users/{}/avatars'.format(self.id) + Avatar, self._requester, 'GET', 'users/{}/avatars'.format(self.id) ) def get_assignments(self, course, **kwargs): @@ -249,7 +231,7 @@ def get_assignments(self, course, **kwargs): self._requester, 'GET', 'users/{}/courses/{}/assignments'.format(self.id, course_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_enrollments(self, **kwargs): @@ -269,7 +251,7 @@ def get_enrollments(self, **kwargs): self._requester, 'GET', 'users/{}/enrollments'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def upload(self, file, **kwargs): @@ -290,10 +272,7 @@ def upload(self, file, **kwargs): :rtype: tuple """ return Uploader( - self._requester, - 'users/{}/files'.format(self.id), - file, - **kwargs + self._requester, 'users/{}/files'.format(self.id), file, **kwargs ).start() def list_calendar_events_for_user(self, **kwargs): @@ -314,7 +293,7 @@ def list_calendar_events_for_user(self, **kwargs): "`list_calendar_events_for_user`" " is being deprecated and will be removed in a future version." " Use `get_calendar_events_for_user` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_calendar_events_for_user(**kwargs) @@ -334,7 +313,7 @@ def get_calendar_events_for_user(self, **kwargs): self._requester, 'GET', 'users/{}/calendar_events'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def list_communication_channels(self, **kwargs): @@ -356,7 +335,7 @@ def list_communication_channels(self, **kwargs): "`list_communication_channels`" " is being deprecated and will be removed in a future version." " Use `get_communication_channels` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_communication_channels(**kwargs) @@ -377,7 +356,7 @@ def get_communication_channels(self, **kwargs): self._requester, 'GET', 'users/{}/communication_channels'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_communication_channel(self, **kwargs): @@ -392,7 +371,7 @@ def create_communication_channel(self, **kwargs): response = self._requester.request( 'POST', 'users/{}/communication_channels'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return CommunicationChannel(self._requester, response.json()) @@ -414,7 +393,7 @@ def list_files(self, **kwargs): warnings.warn( "`list_files` is being deprecated and will be removed in a future " "version. Use `get_files` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_files(**kwargs) @@ -436,7 +415,7 @@ def get_files(self, **kwargs): self._requester, 'GET', 'users/{}/files'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_file(self, file, **kwargs): @@ -458,7 +437,7 @@ def get_file(self, file, **kwargs): response = self._requester.request( 'GET', 'users/{}/files/{}'.format(self.id, file_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) @@ -479,8 +458,7 @@ def get_folder(self, folder): folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - 'GET', - 'users/{}/folders/{}'.format(self.id, folder_id) + 'GET', 'users/{}/folders/{}'.format(self.id, folder_id) ) return Folder(self._requester, response.json()) @@ -502,7 +480,7 @@ def list_folders(self, **kwargs): warnings.warn( "`list_folders` is being deprecated and will be removed in a " "future version. Use `get_folders` instead.", - DeprecationWarning + DeprecationWarning, ) return self.get_folders(**kwargs) @@ -523,7 +501,7 @@ def get_folders(self, **kwargs): self._requester, 'GET', 'users/{}/folders'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def create_folder(self, name, **kwargs): @@ -541,7 +519,7 @@ def create_folder(self, name, **kwargs): 'POST', 'users/{}/folders'.format(self.id), name=name, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return Folder(self._requester, response.json()) @@ -562,10 +540,10 @@ def list_user_logins(self, **kwargs): warnings.warn( "`list_user_logins` is being deprecated and will be removed in a future version." " Use `get_user_logins` instead", - DeprecationWarning + DeprecationWarning, ) - return self. get_user_logins(**kwargs) + return self.get_user_logins(**kwargs) def get_user_logins(self, **kwargs): """ @@ -584,7 +562,7 @@ def get_user_logins(self, **kwargs): self._requester, 'GET', 'users/{}/logins'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def list_observees(self, **kwargs): @@ -604,7 +582,7 @@ def list_observees(self, **kwargs): warnings.warn( "`list_observees` is being deprecated and will be removed in a " "future version. Use `get_observees` instead", - DeprecationWarning + DeprecationWarning, ) return self.get_observees(**kwargs) @@ -625,7 +603,7 @@ def get_observees(self, **kwargs): self._requester, 'GET', 'users/{}/observees'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def add_observee_with_credentials(self, **kwargs): @@ -641,7 +619,7 @@ def add_observee_with_credentials(self, **kwargs): response = self._requester.request( 'POST', 'users/{}/observees'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return User(self._requester, response.json()) @@ -658,8 +636,7 @@ def show_observee(self, observee_id): """ response = self._requester.request( - 'GET', - 'users/{}/observees/{}'.format(self.id, observee_id) + 'GET', 'users/{}/observees/{}'.format(self.id, observee_id) ) return User(self._requester, response.json()) @@ -676,8 +653,7 @@ def add_observee(self, observee_id): """ response = self._requester.request( - 'PUT', - 'users/{}/observees/{}'.format(self.id, observee_id) + 'PUT', 'users/{}/observees/{}'.format(self.id, observee_id) ) return User(self._requester, response.json()) @@ -694,8 +670,7 @@ def remove_observee(self, observee_id): """ response = self._requester.request( - 'DELETE', - 'users/{}/observees/{}'.format(self.id, observee_id) + 'DELETE', 'users/{}/observees/{}'.format(self.id, observee_id) ) return User(self._requester, response.json()) @@ -723,7 +698,7 @@ def create_content_migration(self, migration_type, **kwargs): response = self._requester.request( 'POST', 'users/{}/content_migrations'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -745,12 +720,14 @@ def get_content_migration(self, content_migration, **kwargs): """ from canvasapi.content_migration import ContentMigration - migration_id = obj_or_id(content_migration, "content_migration", (ContentMigration,)) + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) + ) response = self._requester.request( 'GET', 'users/{}/content_migrations/{}'.format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -776,7 +753,7 @@ def get_content_migrations(self, **kwargs): 'GET', 'users/{}/content_migrations'.format(self.id), {'user_id': self.id}, - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_migration_systems(self, **kwargs): @@ -796,7 +773,7 @@ def get_migration_systems(self, **kwargs): self._requester, 'GET', 'users/{}/content_migrations/migrators'.format(self.id), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_content_exports(self, **kwargs): @@ -815,10 +792,8 @@ def get_content_exports(self, **kwargs): ContentExport, self._requester, 'GET', - 'users/{}/content_exports'.format( - self.id - ), - kwargs=combine_kwargs(**kwargs) + 'users/{}/content_exports'.format(self.id), + kwargs=combine_kwargs(**kwargs), ) def get_content_export(self, content_export, **kwargs): @@ -839,11 +814,8 @@ def get_content_export(self, content_export, **kwargs): response = self._requester.request( 'GET', - 'users/{}/content_exports/{}'.format( - self.id, - export_id - ), - _kwargs=combine_kwargs(**kwargs) + 'users/{}/content_exports/{}'.format(self.id, export_id), + _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -866,10 +838,8 @@ def export_content(self, export_type, **kwargs): response = self._requester.request( 'POST', - 'users/{}/content_exports'.format( - self.id, - ), - _kwargs=combine_kwargs(**kwargs) + 'users/{}/content_exports'.format(self.id), + _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -891,7 +861,7 @@ def get_open_poll_sessions(self, **kwargs): 'GET', 'poll_sessions/opened', _root='poll_sessions', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) def get_closed_poll_sessions(self, **kwargs): @@ -912,12 +882,11 @@ def get_closed_poll_sessions(self, **kwargs): 'GET', 'poll_sessions/closed', _root='poll_sessions', - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) @python_2_unicode_compatible class UserDisplay(CanvasObject): - def __str__(self): return "{}".format(self.display_name) diff --git a/tests/test_account.py b/tests/test_account.py index 29ee3570..8db73ef9 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -7,7 +7,14 @@ import requests_mock from canvasapi import Canvas -from canvasapi.account import Account, AccountNotification, AccountReport, Admin, Role, SSOSettings +from canvasapi.account import ( + Account, + AccountNotification, + AccountReport, + Admin, + Role, + SSOSettings, +) from canvasapi.authentication_provider import AuthenticationProvider from canvasapi.course import Course from canvasapi.enrollment import Enrollment @@ -31,7 +38,6 @@ @requests_mock.Mocker() class TestAccount(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -124,7 +130,7 @@ def test_create_notification(self, m): 'subject': subject, 'message': 'Message', 'start_at': '2015-04-01T00:00:00Z', - 'end_at': '2018-04-01T00:00:00Z' + 'end_at': '2018-04-01T00:00:00Z', } notif = self.account.create_notification(notif_dict) @@ -461,7 +467,7 @@ def test_create_external_tool(self, m): name="External Tool - Account", privacy_level="public", consumer_key="key", - shared_secret="secret" + shared_secret="secret", ) self.assertIsInstance(response, ExternalTool) @@ -472,10 +478,7 @@ def test_create_external_tool(self, m): def test_create_enrollment_term(self, m): register_uris({'enrollment_term': ['create_enrollment_term']}, m) - evnt = self.account.create_enrollment_term( - name="Test Enrollment Term", - id=45 - ) + evnt = self.account.create_enrollment_term(name="Test Enrollment Term", id=45) self.assertIsInstance(evnt, EnrollmentTerm) self.assertEqual(evnt.name, "Test Enrollment Term") @@ -536,8 +539,7 @@ def test_create_user_login(self, m): unique_id = 'belieber@example.com' response = self.account.create_user_login( - user={'id': 1}, - login={'unique_id': unique_id} + user={'id': 1}, login={'unique_id': unique_id} ) self.assertIsInstance(response, Login) @@ -556,15 +558,21 @@ def test_create_user_login_fail_on_login_unique_id(self, m): # get_department_level_participation_data_with_given_term() def test_get_department_level_participation_data_with_given_term(self, m): - register_uris({'account': ['get_department_level_participation_data_with_given_term']}, m) + register_uris( + {'account': ['get_department_level_participation_data_with_given_term']}, m + ) - response = self.account.get_department_level_participation_data_with_given_term(1) + response = self.account.get_department_level_participation_data_with_given_term( + 1 + ) self.assertIsInstance(response, list) # get_department_level_participation_data_current() def test_get_department_level_participation_data_current(self, m): - register_uris({'account': ['get_department_level_participation_data_current']}, m) + register_uris( + {'account': ['get_department_level_participation_data_current']}, m + ) response = self.account.get_department_level_participation_data_current() @@ -572,7 +580,9 @@ def test_get_department_level_participation_data_current(self, m): # get_department_level_participation_data_completed() def test_get_department_level_participation_data_completed(self, m): - register_uris({'account': ['get_department_level_participation_data_completed']}, m) + register_uris( + {'account': ['get_department_level_participation_data_completed']}, m + ) response = self.account.get_department_level_participation_data_completed() @@ -580,7 +590,9 @@ def test_get_department_level_participation_data_completed(self, m): # get_department_level_grade_data_with_given_term() def test_get_department_level_grade_data_with_given_term(self, m): - register_uris({'account': ['get_department_level_grade_data_with_given_term']}, m) + register_uris( + {'account': ['get_department_level_grade_data_with_given_term']}, m + ) response = self.account.get_department_level_grade_data_with_given_term(1) @@ -604,7 +616,9 @@ def test_get_department_level_grade_data_completed(self, m): # get_department_level_statistics_with_given_term() def test_get_department_level_statistics_with_given_term(self, m): - register_uris({'account': ['get_department_level_statistics_with_given_term']}, m) + register_uris( + {'account': ['get_department_level_statistics_with_given_term']}, m + ) response = self.account.get_department_level_statistics_with_given_term(1) @@ -628,18 +642,25 @@ def test_get_department_level_statistics_completed(self, m): # list_authentication_providers() def test_list_authentication_providers(self, m): - requires = {'account': ['list_authentication_providers', - 'list_authentication_providers_2']} + requires = { + 'account': [ + 'list_authentication_providers', + 'list_authentication_providers_2', + ] + } register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: authentication_providers = self.account.list_authentication_providers() authentication_providers_list = [ - authentication_provider for authentication_provider in authentication_providers + authentication_provider + for authentication_provider in authentication_providers ] self.assertEqual(len(authentication_providers_list), 4) - self.assertIsInstance(authentication_providers_list[0], AuthenticationProvider) + self.assertIsInstance( + authentication_providers_list[0], AuthenticationProvider + ) self.assertTrue(hasattr(authentication_providers_list[0], 'auth_type')) self.assertTrue(hasattr(authentication_providers_list[0], 'position')) @@ -648,13 +669,18 @@ def test_list_authentication_providers(self, m): # get_authentication_providers() def test_get_authentication_providers(self, m): - requires = {'account': ['list_authentication_providers', - 'list_authentication_providers_2']} + requires = { + 'account': [ + 'list_authentication_providers', + 'list_authentication_providers_2', + ] + } register_uris(requires, m) authentication_providers = self.account.get_authentication_providers() authentication_providers_list = [ - authentication_provider for authentication_provider in authentication_providers + authentication_provider + for authentication_provider in authentication_providers ] self.assertEqual(len(authentication_providers_list), 4) @@ -864,8 +890,10 @@ def test_create_content_migration(self, m): self.assertTrue(hasattr(content_migration, 'migration_type')) def test_create_content_migration_migrator(self, m): - register_uris({'account': ['create_content_migration', - 'get_migration_systems_multiple']}, m) + register_uris( + {'account': ['create_content_migration', 'get_migration_systems_multiple']}, + m, + ) migrators = self.account.get_migration_systems() content_migration = self.account.create_content_migration(migrators[0]) @@ -947,8 +975,7 @@ def test_create_sis_import(self, m): register_uris({'account': ['create_sis_import']}, m) - filepath = os.path.join('tests', 'fixtures', - 'test_create_sis_import.csv') + filepath = os.path.join('tests', 'fixtures', 'test_create_sis_import.csv') sis_import = self.account.create_sis_import(filepath) @@ -963,8 +990,7 @@ def test_create_sis_import_binary(self, m): register_uris({'account': ['create_sis_import']}, m) - filepath = os.path.join('tests', 'fixtures', - 'test_create_sis_import.csv') + filepath = os.path.join('tests', 'fixtures', 'test_create_sis_import.csv') with open(filepath, 'rb') as f: sis_import = self.account.create_sis_import(f) @@ -1146,7 +1172,7 @@ def test_delete_grading_periods(self, m): self.grading_period = GradingPeriod( self.canvas._Canvas__requester, - {"title": "grading period 1", "id": 1, "course_id": 1} + {"title": "grading period 1", "id": 1, "course_id": 1}, ) self.assertTrue(self.account.delete_grading_period(1)) self.assertTrue(self.account.delete_grading_period(self.grading_period)) diff --git a/tests/test_appointment_group.py b/tests/test_appointment_group.py index cb64556e..336b228e 100644 --- a/tests/test_appointment_group.py +++ b/tests/test_appointment_group.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestAppointmentGroup(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) diff --git a/tests/test_assignment.py b/tests/test_assignment.py index 6b4e0025..67e0d0c7 100644 --- a/tests/test_assignment.py +++ b/tests/test_assignment.py @@ -17,7 +17,6 @@ @requests_mock.Mocker() class TestAssignment(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -34,7 +33,7 @@ def test_create_override(self, m): override = self.assignment.create_override( assignment_override={ 'student_ids': [1, 2, 3], - 'title': 'New Assignment Override' + 'title': 'New Assignment Override', } ) @@ -80,10 +79,15 @@ def test_get_override(self, m): # get_overrides() def test_get_overrides(self, m): - register_uris({'assignment': [ - 'list_assignment_overrides', - 'list_assignment_overrides_p2' - ]}, m) + register_uris( + { + 'assignment': [ + 'list_assignment_overrides', + 'list_assignment_overrides_p2', + ] + }, + m, + ) overrides = self.assignment.get_overrides() override_list = [override for override in overrides] @@ -104,10 +108,7 @@ def test_get_peer_reviews(self, m): # get_submission() def test_get_submission(self, m): - register_uris({ - 'submission': ['get_by_id_course'], - 'user': ['get_by_id'] - }, m) + register_uris({'submission': ['get_by_id_course'], 'user': ['get_by_id']}, m) user_id = 1 submission_by_id = self.assignment.get_submission(user_id) @@ -194,14 +195,9 @@ def test__str__(self, m): def test_submissions_bulk_update(self, m): register_uris({'assignment': ['update_submissions']}, m) register_uris({'progress': ['course_progress']}, m) - progress = self.assignment.submissions_bulk_update(grade_data={ - '1': { - 'posted_grade': 97 - }, - '2': { - 'posted_grade': 98 - } - }) + progress = self.assignment.submissions_bulk_update( + grade_data={'1': {'posted_grade': 97}, '2': {'posted_grade': 98}} + ) self.assertIsInstance(progress, Progress) self.assertTrue(progress.context_type == "Course") progress = progress.query() @@ -243,15 +239,13 @@ def test_upload_to_submission_user(self, m): @requests_mock.Mocker() class TestAssignmentGroup(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id'], - 'assignment': ['get_assignment_group'] - }, m) + register_uris( + {'course': ['get_by_id'], 'assignment': ['get_assignment_group']}, m + ) self.course = self.canvas.get_course(1) self.assignment_group = self.course.get_assignment_group(5) @@ -287,15 +281,17 @@ def test__str__(self, m): @requests_mock.Mocker() class TestAssignmentOverride(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id', 'get_assignment_by_id'], - 'assignment': ['get_assignment_override'], - }, m) + register_uris( + { + 'course': ['get_by_id', 'get_assignment_by_id'], + 'assignment': ['get_assignment_override'], + }, + m, + ) self.course = self.canvas.get_course(1) self.assignment = self.course.get_assignment(1) @@ -319,10 +315,12 @@ def test_delete(self, m): def test_edit(self, m): register_uris({'assignment': ['edit_override']}, m) - edited = self.assignment_override.edit(assignment_override={ - 'title': 'New Title', - 'student_ids': self.assignment_override.student_ids - }) + edited = self.assignment_override.edit( + assignment_override={ + 'title': 'New Title', + 'student_ids': self.assignment_override.student_ids, + } + ) self.assertEqual(edited, self.assignment_override) self.assertIsInstance(self.assignment_override, AssignmentOverride) diff --git a/tests/test_authentication_providers.py b/tests/test_authentication_providers.py index f16bfef5..02962707 100644 --- a/tests/test_authentication_providers.py +++ b/tests/test_authentication_providers.py @@ -11,40 +11,43 @@ @requests_mock.Mocker() class TestAuthenticationProvider(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'account': ['get_by_id', 'add_authentication_providers'] - }, m) + register_uris({'account': ['get_by_id', 'add_authentication_providers']}, m) self.account = self.canvas.get_account(1) self.authentication_providers = self.account.add_authentication_providers( - authentication_providers={ - "auth_type": "Authentication Providers" - } + authentication_providers={"auth_type": "Authentication Providers"} ) # update() def test_update_authentication_providers(self, m): - register_uris({'authentication_providers': ['update_authentication_providers']}, m) + register_uris( + {'authentication_providers': ['update_authentication_providers']}, m + ) new_auth_type = 'New Authentication Providers' - self.authentication_providers.update(authentication_providers={"auth_type": new_auth_type}) + self.authentication_providers.update( + authentication_providers={"auth_type": new_auth_type} + ) self.assertEqual(self.authentication_providers.auth_type, new_auth_type) # delete() def test_delete_authentication_providers(self, m): - register_uris({'authentication_providers': ['delete_authentication_providers']}, m) + register_uris( + {'authentication_providers': ['delete_authentication_providers']}, m + ) deleted_authentication_providers = self.authentication_providers.delete() self.assertIsInstance(deleted_authentication_providers, AuthenticationProvider) self.assertTrue(hasattr(deleted_authentication_providers, 'auth_type')) - self.assertEqual(deleted_authentication_providers.auth_type, 'Authentication Providers') + self.assertEqual( + deleted_authentication_providers.auth_type, 'Authentication Providers' + ) # __str__() def test_str__(self, m): diff --git a/tests/test_blueprint.py b/tests/test_blueprint.py index 654bd003..5b518d65 100644 --- a/tests/test_blueprint.py +++ b/tests/test_blueprint.py @@ -13,14 +13,17 @@ @requests_mock.Mocker() class TestBlueprint(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { - 'course': ['get_blueprint', 'get_by_id', 'list_blueprint_subscriptions'], - 'blueprint': ['show_blueprint_migration'] + 'course': [ + 'get_blueprint', + 'get_by_id', + 'list_blueprint_subscriptions', + ], + 'blueprint': ['show_blueprint_migration'], } register_uris(requires, m) @@ -57,7 +60,9 @@ def test_associated_course_migration(self, m): # change_blueprint_restrictions() def test_change_blueprint_restrictions(self, m): register_uris({'blueprint': ['change_blueprint_restrictions']}, m) - blueprint_restriction = self.blueprint.change_blueprint_restrictions("quiz", 1, True) + blueprint_restriction = self.blueprint.change_blueprint_restrictions( + "quiz", 1, True + ) self.assertIsInstance(blueprint_restriction, bool) # get_unsynced_changes() @@ -94,14 +99,17 @@ def test_show_blueprint_migration(self, m): @requests_mock.Mocker() class TestBlueprintSubscription(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { - 'course': ['get_blueprint', 'get_by_id', 'list_blueprint_subscriptions'], - 'blueprint': ['show_blueprint_migration'] + 'course': [ + 'get_blueprint', + 'get_by_id', + 'list_blueprint_subscriptions', + ], + 'blueprint': ['show_blueprint_migration'], } register_uris(requires, m) @@ -116,6 +124,7 @@ def test__str__(self, m): self.assertIsInstance(string, str) # list_blueprint_imports() + def test_list_blueprint_imports(self, m): register_uris({'blueprint': ['list_blueprint_imports']}, m) blueprint_imports = self.blueprint_subscription.list_blueprint_imports() @@ -125,6 +134,7 @@ def test_list_blueprint_imports(self, m): self.assertEqual(blueprint_imports[0].subscription_id, 10) # show_blueprint_import + def test_show_blueprint_import(self, m): register_uris({'blueprint': ['show_blueprint_import']}, m) blueprint_import = self.blueprint_subscription.show_blueprint_import(3) @@ -133,17 +143,21 @@ def test_show_blueprint_import(self, m): @requests_mock.Mocker() class TestBlueprintMigration(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { - 'course': ['get_blueprint', 'get_by_id', 'list_blueprint_subscriptions'], + 'course': [ + 'get_blueprint', + 'get_by_id', + 'list_blueprint_subscriptions', + ], 'blueprint': [ - 'show_blueprint_migration', 'list_blueprint_imports', - 'show_blueprint_import' - ] + 'show_blueprint_migration', + 'list_blueprint_imports', + 'show_blueprint_import', + ], } register_uris(requires, m) @@ -151,7 +165,9 @@ def setUp(self): self.blueprint = self.course.get_blueprint(1) self.blueprint_migration = self.blueprint.show_blueprint_migration(1) self.blueprint_subscription = self.course.list_blueprint_subscriptions()[0] - self.blueprint_imports = self.blueprint_subscription.list_blueprint_imports()[0] + self.blueprint_imports = self.blueprint_subscription.list_blueprint_imports()[ + 0 + ] self.b_import = self.blueprint_subscription.show_blueprint_import(3) # __str__() diff --git a/tests/test_bookmark.py b/tests/test_bookmark.py index b4f57594..1fbf35b7 100644 --- a/tests/test_bookmark.py +++ b/tests/test_bookmark.py @@ -11,15 +11,13 @@ @requests_mock.Mocker() class TestBookmark(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'bookmark': ['get_bookmark'], - 'current_user': ['get_by_id'] - }, m) + register_uris( + {'bookmark': ['get_bookmark'], 'current_user': ['get_by_id']}, m + ) self.user = self.canvas.get_current_user() self.bookmark = self.user.get_bookmark(45) diff --git a/tests/test_calendar_event.py b/tests/test_calendar_event.py index 5c5ce8a8..5edac143 100644 --- a/tests/test_calendar_event.py +++ b/tests/test_calendar_event.py @@ -11,7 +11,6 @@ @requests_mock.Mocker() class TestCalendarEvent(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) diff --git a/tests/test_canvas.py b/tests/test_canvas.py index fbc6cf22..95d9589d 100644 --- a/tests/test_canvas.py +++ b/tests/test_canvas.py @@ -31,7 +31,6 @@ @requests_mock.Mocker() class TestCanvas(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -46,8 +45,10 @@ def test_init_warns_when_url_is_http(self, m): Canvas(settings.BASE_URL_AS_HTTP, settings.API_KEY) self.assertRaises( UserWarning, - msg=('Canvas may respond unexpectedly when making requests to HTTP' - 'URLs. If possible, please use HTTPS.') + msg=( + 'Canvas may respond unexpectedly when making requests to HTTP' + 'URLs. If possible, please use HTTPS.' + ), ) def test_init_warns_when_url_is_blank(self, m): @@ -55,7 +56,7 @@ def test_init_warns_when_url_is_blank(self, m): Canvas(settings.BASE_URL_AS_BLANK, settings.API_KEY) self.assertRaises( UserWarning, - msg='Canvas needs a valid URL, please provide a non-blank `base_url`.' + msg='Canvas needs a valid URL, please provide a non-blank `base_url`.', ) def test_init_warns_when_url_is_invalid(self, m): @@ -63,8 +64,10 @@ def test_init_warns_when_url_is_invalid(self, m): Canvas(settings.BASE_URL_AS_INVALID, settings.API_KEY) self.assertRaises( UserWarning, - msg=('An invalid `base_url` for the Canvas API Instance was used.' - 'Please provide a valid HTTP or HTTPS URL if possible.') + msg=( + 'An invalid `base_url` for the Canvas API Instance was used.' + 'Please provide a valid HTTP or HTTPS URL if possible.' + ), ) # create_account() @@ -73,9 +76,7 @@ def test_create_account(self, m): name = 'Newly Created Account' - account_dict = { - 'name': name - } + account_dict = {'name': name} account = self.canvas.create_account(account=account_dict) self.assertIsInstance(account, Account) @@ -364,8 +365,7 @@ def test_create_conversation(self, m): body = 'Hello, World!' conversations = self.canvas.create_conversation( - recipients=recipients, - body=body + recipients=recipients, body=body ) self.assertIsInstance(conversations, list) self.assertEqual(len(conversations), 1) @@ -380,8 +380,7 @@ def test_create_conversation_multiple_people(self, m): body = 'Hey guys!' conversations = self.canvas.create_conversation( - recipients=recipients, - body=body + recipients=recipients, body=body ) self.assertIsInstance(conversations, list) self.assertEqual(len(conversations), 2) @@ -408,9 +407,7 @@ def test_get_conversation(self, m): # get_conversations() def test_get_conversations(self, m): - requires = { - 'conversation': ['get_conversations', 'get_conversations_2'] - } + requires = {'conversation': ['get_conversations', 'get_conversations_2']} register_uris(requires, m) convos = self.canvas.get_conversations() @@ -449,8 +446,7 @@ def test_conversations_batch_update(self, m): conversation_ids = [1, 2] this_event = "mark_as_read" result = self.canvas.conversations_batch_update( - event=this_event, - conversation_ids=conversation_ids + event=this_event, conversation_ids=conversation_ids ) self.assertIsInstance(result, Progress) @@ -458,8 +454,7 @@ def test_conversations_batch_updated_fail_on_event(self, m): conversation_ids = [1, 2] this_event = "this doesn't work" result = self.canvas.conversations_batch_update( - event=this_event, - conversation_ids=conversation_ids + event=this_event, conversation_ids=conversation_ids ) self.assertIsInstance(result, ValueError) @@ -467,8 +462,7 @@ def test_conversations_batch_updated_fail_on_ids(self, m): conversation_ids = [None] * 501 this_event = "mark_as_read" result = self.canvas.conversations_batch_update( - event=this_event, - conversation_ids=conversation_ids + event=this_event, conversation_ids=conversation_ids ) self.assertIsInstance(result, ValueError) @@ -476,9 +470,7 @@ def test_conversations_batch_updated_fail_on_ids(self, m): def test_create_calendar_event(self, m): register_uris({'calendar_event': ['create_calendar_event']}, m) - cal_event = { - "context_code": "course_123" - } + cal_event = {"context_code": "course_123"} evnt = self.canvas.create_calendar_event(calendar_event=cal_event) self.assertIsInstance(evnt, CalendarEvent) @@ -529,16 +521,18 @@ def test_reserve_time_slot(self, m): self.assertIsInstance(calendar_event_by_id, CalendarEvent) self.assertEqual(calendar_event_by_id.title, "Test Reservation") - calendar_event_by_obj = self.canvas.reserve_time_slot(calendar_event=calendar_event_by_id) + calendar_event_by_obj = self.canvas.reserve_time_slot( + calendar_event=calendar_event_by_id + ) self.assertIsInstance(calendar_event_by_obj, CalendarEvent) self.assertEqual(calendar_event_by_obj.title, "Test Reservation") def test_reserve_time_slot_by_participant_id(self, m): - register_uris({ - 'calendar_event': ['reserve_time_slot_participant_id'] - }, m) + register_uris({'calendar_event': ['reserve_time_slot_participant_id']}, m) - cal_event = self.canvas.reserve_time_slot(calendar_event=567, participant_id=777) + cal_event = self.canvas.reserve_time_slot( + calendar_event=567, participant_id=777 + ) self.assertIsInstance(cal_event, CalendarEvent) self.assertEqual(cal_event.title, "Test Reservation") self.assertEqual(cal_event.user, 777) @@ -571,7 +565,9 @@ def test_get_appointment_group(self, m): self.assertIsInstance(appointment_group_by_id, AppointmentGroup) self.assertEqual(appointment_group_by_id.title, "Test Group 3") - appointment_group_by_obj = self.canvas.get_appointment_group(appointment_group_by_id) + appointment_group_by_obj = self.canvas.get_appointment_group( + appointment_group_by_id + ) self.assertIsInstance(appointment_group_by_obj, AppointmentGroup) self.assertEqual(appointment_group_by_obj.title, "Test Group 3") @@ -579,10 +575,9 @@ def test_get_appointment_group(self, m): def test_create_appointment_group(self, m): register_uris({'appointment_group': ['create_appointment_group']}, m) - evnt = self.canvas.create_appointment_group({ - "context_codes": ["course_123"], - "title": "Test Group" - }) + evnt = self.canvas.create_appointment_group( + {"context_codes": ["course_123"], "title": "Test Group"} + ) self.assertIsInstance(evnt, AppointmentGroup) self.assertEqual(evnt.context_codes[0], "course_123") @@ -590,9 +585,7 @@ def test_create_appointment_group(self, m): def test_create_appointment_group_fail_on_context_codes(self, m): with self.assertRaises(RequiredFieldMissing): - self.canvas.create_appointment_group({ - "title": "Test Group" - }) + self.canvas.create_appointment_group({"title": "Test Group"}) def test_create_appointment_group_fail_on_title(self, m): with self.assertRaises(RequiredFieldMissing): @@ -604,9 +597,11 @@ def test_list_user_participants(self, m): { 'appointment_group': [ 'get_appointment_group_222', - 'list_user_participants' + 'list_user_participants', ] - }, m) + }, + m, + ) with warnings.catch_warnings(record=True) as warning_list: users_by_id = self.canvas.list_user_participants(222) @@ -631,9 +626,11 @@ def test_get_user_participants(self, m): { 'appointment_group': [ 'get_appointment_group_222', - 'list_user_participants' + 'list_user_participants', ] - }, m) + }, + m, + ) users_by_id = self.canvas.get_user_participants(222) users_get_by_id = [user for user in users_by_id] @@ -650,9 +647,11 @@ def test_list_group_participants(self, m): { 'appointment_group': [ 'get_appointment_group_222', - 'list_group_participants' + 'list_group_participants', ] - }, m) + }, + m, + ) with warnings.catch_warnings(record=True) as warning_list: groups_by_id = self.canvas.list_group_participants(222) @@ -664,7 +663,9 @@ def test_list_group_participants(self, m): with warnings.catch_warnings(record=True) as warning_list: appointment_group_for_obj = self.canvas.get_appointment_group(222) - groups_by_obj = self.canvas.list_group_participants(appointment_group_for_obj) + groups_by_obj = self.canvas.list_group_participants( + appointment_group_for_obj + ) groups_list_by_obj = [group for group in groups_by_obj] self.assertEqual(len(groups_list_by_obj), 2) @@ -677,9 +678,11 @@ def test_get_group_participants(self, m): { 'appointment_group': [ 'get_appointment_group_222', - 'list_group_participants' + 'list_group_participants', ] - }, m) + }, + m, + ) groups_by_id = self.canvas.get_group_participants(222) groups_get_by_id = [group for group in groups_by_id] diff --git a/tests/test_communication_channel.py b/tests/test_communication_channel.py index 4c489ce8..7116b284 100644 --- a/tests/test_communication_channel.py +++ b/tests/test_communication_channel.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestCommunicationChannel(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -91,8 +90,7 @@ def test_update_preference(self, m): frequency = 'daily' updated_pref = self.comm_chan.update_preference( - notification=notification, - frequency=frequency + notification=notification, frequency=frequency ) self.assertIsInstance(updated_pref, NotificationPreference) @@ -102,15 +100,12 @@ def test_update_preference(self, m): # update_preferences_by_category() def test_update_preferences_by_category(self, m): - register_uris({ - 'communication_channel': ['update_preferences_by_category'] - }, m) + register_uris({'communication_channel': ['update_preferences_by_category']}, m) category = 'course_content' frequency = 'daily' updated_prefs = self.comm_chan.update_preferences_by_catagory( - category=category, - frequency=frequency + category=category, frequency=frequency ) self.assertEqual(len(updated_prefs), 3) @@ -123,12 +118,8 @@ def test_update_multiple_preferences(self, m): register_uris({'communication_channel': ['update_multiple_preferences']}, m) notification_preferences = { - "assignment_due_date_changed": { - "frequency": "daily" - }, - "assignment_changed": { - "frequency": "daily" - } + "assignment_due_date_changed": {"frequency": "daily"}, + "assignment_changed": {"frequency": "daily"}, } updated_prefs = self.comm_chan.update_multiple_preferences( @@ -161,13 +152,12 @@ def test_update_multiple_preferences(self, m): # delete() def test_delete(self, m): - register_uris({ - 'communication_channel': ['create_comm_channel', 'delete_comm_channel'] - }, m) + register_uris( + {'communication_channel': ['create_comm_channel', 'delete_comm_channel']}, m + ) - channel = { - "type": "email", - "address": "username@example.org" - } - new_channel = self.user.create_communication_channel(communication_channel=channel) + channel = {"type": "email", "address": "username@example.org"} + new_channel = self.user.create_communication_channel( + communication_channel=channel + ) self.assertTrue(new_channel.delete()) diff --git a/tests/test_content_export.py b/tests/test_content_export.py index 5d70e63e..1d57a4de 100644 --- a/tests/test_content_export.py +++ b/tests/test_content_export.py @@ -17,7 +17,7 @@ def setUp(self): requires = { 'course': ['get_by_id', 'single_content_export'], 'group': ['get_by_id', 'single_content_export'], - 'user': ['get_by_id', 'single_content_export'] + 'user': ['get_by_id', 'single_content_export'], } register_uris(requires, m) diff --git a/tests/test_content_migration.py b/tests/test_content_migration.py index 2616dadc..ace2e953 100644 --- a/tests/test_content_migration.py +++ b/tests/test_content_migration.py @@ -24,7 +24,7 @@ def setUp(self): 'course': ['get_by_id', 'get_content_migration_single'], 'group': ['get_by_id', 'get_content_migration_single'], 'account': ['get_by_id', 'get_content_migration_single'], - 'user': ['get_by_id', 'get_content_migration_single'] + 'user': ['get_by_id', 'get_content_migration_single'], } register_uris(requires, m) @@ -163,7 +163,6 @@ def test_update_fail(self, m): @requests_mock.Mocker() class TestMigrationIssue(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -173,10 +172,12 @@ def setUp(self): 'group': ['get_by_id', 'get_content_migration_single'], 'account': ['get_by_id', 'get_content_migration_single'], 'user': ['get_by_id', 'get_content_migration_single'], - 'content_migration': ['get_migration_issue_single', - 'get_migration_issue_single_course', - 'get_migration_issue_single_group', - 'get_migration_issue_single_user'] + 'content_migration': [ + 'get_migration_issue_single', + 'get_migration_issue_single_course', + 'get_migration_issue_single_group', + 'get_migration_issue_single_user', + ], } register_uris(requires, m) @@ -191,9 +192,15 @@ def setUp(self): self.content_migration_user = self.user.get_content_migration(1) self.migration_issue = self.content_migration.get_migration_issue(1) - self.migration_issue_course = self.content_migration_course.get_migration_issue(1) - self.migration_issue_group = self.content_migration_group.get_migration_issue(1) - self.migration_issue_user = self.content_migration_user.get_migration_issue(1) + self.migration_issue_course = self.content_migration_course.get_migration_issue( + 1 + ) + self.migration_issue_group = self.content_migration_group.get_migration_issue( + 1 + ) + self.migration_issue_user = self.content_migration_user.get_migration_issue( + 1 + ) # __str__() def test__str__(self, m): @@ -227,10 +234,12 @@ def setUp(self): 'group': ['get_by_id', 'get_migration_systems_multiple'], 'account': ['get_by_id', 'get_migration_systems_multiple'], 'user': ['get_by_id', 'get_migration_systems_multiple'], - 'content_migration': ['get_migration_issue_single', - 'get_migration_issue_single_course', - 'get_migration_issue_single_group', - 'get_migration_issue_single_user'] + 'content_migration': [ + 'get_migration_issue_single', + 'get_migration_issue_single_course', + 'get_migration_issue_single_group', + 'get_migration_issue_single_user', + ], } register_uris(requires, m) diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 633288ed..9c16a5ef 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -11,7 +11,6 @@ @requests_mock.Mocker() class TestConversation(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -61,7 +60,9 @@ def test_add_recipients(self, m): recipients = {'bob': 1, 'joe': 2} string_bob = "Bob was added to the conversation by Hank TA" string_joe = "Joe was added to the conversation by Hank TA" - result = self.conversation.add_recipients([recipients['bob'], recipients['joe']]) + result = self.conversation.add_recipients( + [recipients['bob'], recipients['joe']] + ) self.assertTrue(hasattr(result, 'messages')) self.assertEqual(len(result.messages), 2) self.assertEqual(result.messages[0]["body"], string_bob) diff --git a/tests/test_course.py b/tests/test_course.py index 6263c3a0..f8d17ae2 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -44,7 +44,6 @@ @requests_mock.Mocker() class TestCourse(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -52,7 +51,7 @@ def setUp(self): requires = { 'course': ['get_assignment_by_id', 'get_by_id', 'get_page'], 'quiz': ['get_by_id'], - 'user': ['get_by_id'] + 'user': ['get_by_id'], } register_uris(requires, m) @@ -82,13 +81,13 @@ def test_create_assignment_overrides(self, m): { 'student_ids': [1, 2, 3], 'title': 'New Assignment Override', - 'assignment_id': 1 + 'assignment_id': 1, }, { 'assignment_id': 2, 'student_ids': [1, 2, 3], - 'title': 'New Assignment Override 2' - } + 'title': 'New Assignment Override 2', + }, ] created_overrides = self.course.create_assignment_overrides(override_list) created_list = [created for created in created_overrides] @@ -120,13 +119,13 @@ def test_update_assignment_overrides(self, m): { 'student_ids': [4, 5, 6], 'title': 'Updated Assignment Override', - 'assignment_id': 1 + 'assignment_id': 1, }, { 'assignment_id': 2, 'student_ids': [6, 7], - 'title': 'Updated Assignment Override 2' - } + 'title': 'Updated Assignment Override 2', + }, ] updated_overrides = self.course.update_assignment_overrides(override_list) updated_list = [updated for updated in updated_overrides] @@ -167,10 +166,7 @@ def test_get_users(self, m): # enroll_user() def test_enroll_user(self, m): - requires = { - 'course': ['enroll_user'], - 'user': ['get_by_id'] - } + requires = {'course': ['enroll_user'], 'user': ['get_by_id']} register_uris(requires, m) enrollment_type = 'TeacherEnrollment' @@ -408,15 +404,17 @@ def test_get_assignment(self, m): # get_assignment_overrides() def test_get_assignment_overrides(self, m): - register_uris({'assignment': [ - 'batch_get_assignment_overrides', - 'batch_get_assignment_overrides_p2' - ]}, m) - - bulk_select = [ - {'id': 1, 'assignment_id': 1}, - {'id': 20, 'assignment_id': 2} - ] + register_uris( + { + 'assignment': [ + 'batch_get_assignment_overrides', + 'batch_get_assignment_overrides_p2', + ] + }, + m, + ) + + bulk_select = [{'id': 1, 'assignment_id': 1}, {'id': 20, 'assignment_id': 2}] overrides = self.course.get_assignment_overrides(bulk_select) override_list = [override for override in overrides] @@ -622,12 +620,8 @@ def test_get_file(self, m): # get_full_discussion_topic() def test_get_full_discussion_topic(self, m): register_uris( - { - 'course': [ - 'get_discussion_topics', - 'get_full_discussion_topic' - ] - }, m) + {'course': ['get_discussion_topics', 'get_full_discussion_topic']}, m + ) topic_id = 1 discussion_by_id = self.course.get_full_discussion_topic(topic_id) @@ -714,7 +708,9 @@ def test_get_assignment_group(self, m): self.assertTrue(hasattr(assignment_group_by_id, 'course_id')) self.assertEqual(assignment_group_by_id.course_id, 1) - assignment_group_by_obj = self.course.get_assignment_group(assignment_group_by_id) + assignment_group_by_obj = self.course.get_assignment_group( + assignment_group_by_id + ) self.assertIsInstance(assignment_group_by_obj, AssignmentGroup) self.assertTrue(hasattr(assignment_group_by_obj, 'id')) @@ -724,9 +720,9 @@ def test_get_assignment_group(self, m): # list_assignment_groups() def test_list_assignment_groups(self, m): - register_uris({ - 'assignment': ['list_assignment_groups', 'get_assignment_group'] - }, m) + register_uris( + {'assignment': ['list_assignment_groups', 'get_assignment_group']}, m + ) with warnings.catch_warnings(record=True) as warning_list: response = self.course.list_assignment_groups() @@ -742,9 +738,9 @@ def test_list_assignment_groups(self, m): # get_assignment_groups() def test_get_assignment_groups(self, m): - register_uris({ - 'assignment': ['list_assignment_groups', 'get_assignment_group'] - }, m) + register_uris( + {'assignment': ['list_assignment_groups', 'get_assignment_group']}, m + ) response = self.course.get_assignment_groups() asnt_group_list = [assignment_group for assignment_group in response] @@ -772,7 +768,7 @@ def test_create_external_tool(self, m): name="External Tool - Course", privacy_level="public", consumer_key="key", - shared_secret="secret" + shared_secret="secret", ) self.assertIsInstance(response, ExternalTool) @@ -943,10 +939,9 @@ def test_get_multiple_submissions_grouped_invalid(self, m): # get_submission() def test_get_submission(self, m): - register_uris({ - 'course': ['get_assignment_by_id'], - 'submission': ['get_by_id_course'] - }, m) + register_uris( + {'course': ['get_assignment_by_id'], 'submission': ['get_by_id_course']}, m + ) assignment_for_id = 1 user_id = 1 @@ -961,7 +956,9 @@ def test_get_submission(self, m): with warnings.catch_warnings(record=True) as warning_list: assignment_for_obj = self.course.get_assignment(1) - submission_by_obj = self.course.get_submission(assignment_for_obj, self.user) + submission_by_obj = self.course.get_submission( + assignment_for_obj, self.user + ) self.assertIsInstance(submission_by_obj, Submission) self.assertTrue(hasattr(submission_by_obj, 'submission_type')) @@ -970,18 +967,19 @@ def test_get_submission(self, m): # update_submission() def test_update_submission(self, m): - register_uris({ - 'course': ['get_assignment_by_id'], - 'submission': ['edit', 'get_by_id_course'] - }, m) + register_uris( + { + 'course': ['get_assignment_by_id'], + 'submission': ['edit', 'get_by_id_course'], + }, + m, + ) assignment_for_id = 1 user_id = 1 with warnings.catch_warnings(record=True) as warning_list: submission = self.course.update_submission( - assignment_for_id, - user_id, - submission={'excuse': True} + assignment_for_id, user_id, submission={'excuse': True} ) self.assertIsInstance(submission, Submission) self.assertTrue(hasattr(submission, 'excused')) @@ -992,9 +990,7 @@ def test_update_submission(self, m): assignment_for_obj = self.course.get_assignment(1) with warnings.catch_warnings(record=True) as warning_list: submission = self.course.update_submission( - assignment_for_obj, - self.user, - submission={'excuse': True} + assignment_for_obj, self.user, submission={'excuse': True} ) self.assertIsInstance(submission, Submission) self.assertTrue(hasattr(submission, 'excused')) @@ -1004,7 +1000,9 @@ def test_update_submission(self, m): # list_gradeable_students() def test_list_gradeable_students(self, m): - register_uris({'course': ['get_assignment_by_id', 'list_gradeable_students']}, m) + register_uris( + {'course': ['get_assignment_by_id', 'list_gradeable_students']}, m + ) assignment_for_id = 1 with warnings.catch_warnings(record=True) as warning_list: @@ -1030,12 +1028,16 @@ def test_list_gradeable_students(self, m): # mark_submission_as_read def test_mark_submission_as_read(self, m): - register_uris({'course': ['get_assignment_by_id', 'mark_submission_as_read']}, m) + register_uris( + {'course': ['get_assignment_by_id', 'mark_submission_as_read']}, m + ) assignment_for_id = 1 user_for_id = 1 with warnings.catch_warnings(record=True) as warning_list: - submission_by_id = self.course.mark_submission_as_read(assignment_for_id, user_for_id) + submission_by_id = self.course.mark_submission_as_read( + assignment_for_id, user_for_id + ) self.assertTrue(submission_by_id) self.assertEqual(len(warning_list), 1) @@ -1043,7 +1045,9 @@ def test_mark_submission_as_read(self, m): assignment_for_obj = self.course.get_assignment(1) with warnings.catch_warnings(record=True) as warning_list: - submission_by_obj = self.course.mark_submission_as_read(assignment_for_obj, self.user) + submission_by_obj = self.course.mark_submission_as_read( + assignment_for_obj, self.user + ) self.assertTrue(submission_by_obj) self.assertEqual(len(warning_list), 1) @@ -1051,15 +1055,16 @@ def test_mark_submission_as_read(self, m): # mark_submission_as_unread def test_mark_submission_as_unread(self, m): - register_uris({'course': ['get_assignment_by_id', 'mark_submission_as_unread']}, m) + register_uris( + {'course': ['get_assignment_by_id', 'mark_submission_as_unread']}, m + ) assignment_for_id = 1 user_for_id = 1 with warnings.catch_warnings(record=True) as warning_list: submission_by_id = self.course.mark_submission_as_unread( - assignment_for_id, - user_for_id + assignment_for_id, user_for_id ) self.assertTrue(submission_by_id) @@ -1069,8 +1074,7 @@ def test_mark_submission_as_unread(self, m): assignment_for_obj = self.course.get_assignment(1) with warnings.catch_warnings(record=True) as warning_list: submission_by_obj = self.course.mark_submission_as_unread( - assignment_for_obj, - self.user + assignment_for_obj, self.user ) self.assertTrue(submission_by_obj) @@ -1408,8 +1412,10 @@ def test_create_content_migration(self, m): self.assertTrue(hasattr(content_migration, 'migration_type')) def test_create_content_migration_migrator(self, m): - register_uris({'course': ['create_content_migration', - 'get_migration_systems_multiple']}, m) + register_uris( + {'course': ['create_content_migration', 'get_migration_systems_multiple']}, + m, + ) migrators = self.course.get_migration_systems() content_migration = self.course.create_content_migration(migrators[0]) @@ -1468,16 +1474,9 @@ def test_get_migration_systems(self, m): def test_set_quiz_extensions(self, m): register_uris({'course': ['set_quiz_extensions']}, m) - extension = self.course.set_quiz_extensions([ - { - 'user_id': 1, - 'extra_time': 60 - }, - { - 'user_id': 2, - 'extra_attempts': 3 - } - ]) + extension = self.course.set_quiz_extensions( + [{'user_id': 1, 'extra_time': 60}, {'user_id': 2, 'extra_attempts': 3}] + ) self.assertIsInstance(extension, list) self.assertEqual(len(extension), 2) @@ -1512,16 +1511,9 @@ def test_set_extensions_missing_key(self, m): def test_submissions_bulk_update(self, m): register_uris({'course': ['update_submissions']}, m) register_uris({'progress': ['course_progress']}, m) - progress = self.course.submissions_bulk_update(grade_data={ - '1': { - '1': { - 'posted_grade': 97 - }, - '2': { - 'posted_grade': 98 - } - } - }) + progress = self.course.submissions_bulk_update( + grade_data={'1': {'1': {'posted_grade': 97}, '2': {'posted_grade': 98}}} + ) self.assertIsInstance(progress, Progress) self.assertTrue(progress.context_type == "Course") progress = progress.query() @@ -1709,7 +1701,6 @@ def test_export_content(self, m): @requests_mock.Mocker() class TestCourseNickname(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) diff --git a/tests/test_current_user.py b/tests/test_current_user.py index 940856e2..3bce7e40 100644 --- a/tests/test_current_user.py +++ b/tests/test_current_user.py @@ -87,8 +87,7 @@ def test_get_bookmark(self, m): def test_create_bookmark(self, m): register_uris({'bookmark': ['create_bookmark']}, m) evnt = self.user.create_bookmark( - name="Test Bookmark", - url="https://www.google.com" + name="Test Bookmark", url="https://www.google.com" ) self.assertIsInstance(evnt, Bookmark) self.assertEqual(evnt.name, "Test Bookmark") @@ -122,7 +121,9 @@ def test_get_favorite_groups(self, m): # add_favorite_course() def test_add_favorite_course(self, m): - register_uris({'current_user': ['add_favorite_course'], 'course': ['get_by_id']}, m) + register_uris( + {'current_user': ['add_favorite_course'], 'course': ['get_by_id']}, m + ) fav_by_id = self.user.add_favorite_course(1) self.assertIsInstance(fav_by_id, Favorite) @@ -146,7 +147,9 @@ def test_add_favorite_course_sis_id(self, m): # add_favorite_group() def test_add_favorite_group(self, m): - register_uris({'current_user': ['add_favorite_group'], 'group': ['get_by_id']}, m) + register_uris( + {'current_user': ['add_favorite_group'], 'group': ['get_by_id']}, m + ) fav_by_id = self.user.add_favorite_group(1) self.assertIsInstance(fav_by_id, Favorite) diff --git a/tests/test_discussion_topic.py b/tests/test_discussion_topic.py index 174deff6..b9031522 100644 --- a/tests/test_discussion_topic.py +++ b/tests/test_discussion_topic.py @@ -15,14 +15,13 @@ @requests_mock.Mocker() class TestDiscussionTopic(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { 'course': ['get_by_id', 'get_discussion_topic'], - 'group': ['get_by_id', 'get_discussion_topic'] + 'group': ['get_by_id', 'get_discussion_topic'], } register_uris(requires, m) @@ -273,15 +272,17 @@ def test_get_parent_group(self, m): @requests_mock.Mocker() class TestDiscussionEntry(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { 'course': ['get_by_id', 'get_discussion_topic'], - 'discussion_topic': ['list_entries_single', 'list_entries_single_group'], - 'group': ['get_by_id', 'get_discussion_topic'] + 'discussion_topic': [ + 'list_entries_single', + 'list_entries_single_group', + ], + 'group': ['get_by_id', 'get_discussion_topic'], } register_uris(requires, m) @@ -290,7 +291,9 @@ def setUp(self): self.discussion_topic = self.course.get_discussion_topic(1) self.discussion_topic_group = self.group.get_discussion_topic(1) self.discussion_entry = self.discussion_topic.get_entries([1])[0] - self.discussion_entry_group = self.discussion_topic_group.get_entries([1])[0] + self.discussion_entry_group = self.discussion_topic_group.get_entries([1])[ + 0 + ] # __str__() def test__str__(self, m): diff --git a/tests/test_enrollment.py b/tests/test_enrollment.py index c2eceb6c..456deb52 100644 --- a/tests/test_enrollment.py +++ b/tests/test_enrollment.py @@ -11,15 +11,11 @@ @requests_mock.Mocker() class TestEnrollment(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = { - 'account': ['get_by_id'], - 'enrollment': ['get_by_id'] - } + requires = {'account': ['get_by_id'], 'enrollment': ['get_by_id']} register_uris(requires, m) self.account = self.canvas.get_account(1) diff --git a/tests/test_enrollment_term.py b/tests/test_enrollment_term.py index fd4fda31..71f6f572 100644 --- a/tests/test_enrollment_term.py +++ b/tests/test_enrollment_term.py @@ -11,19 +11,16 @@ @requests_mock.Mocker() class TestEnrollmentTerm(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'account': ['get_by_id', 'create_enrollment_term'] - }, m) + register_uris({'account': ['get_by_id', 'create_enrollment_term']}, m) self.account = self.canvas.get_account(1) - self.enrollment_term = self.account.create_enrollment_term(enrollment_term={ - "name": "Test Enrollment Term" - }) + self.enrollment_term = self.account.create_enrollment_term( + enrollment_term={"name": "Test Enrollment Term"} + ) # delete() def test_delete_enrollment_term(self, m): @@ -40,9 +37,9 @@ def test_edit_enrollment_term(self, m): register_uris({'enrollment_term': ['edit_enrollment_term']}, m) name = 'New Name' - edited_enrollment_term = self.enrollment_term.edit(enrollment_term={ - "name": name - }) + edited_enrollment_term = self.enrollment_term.edit( + enrollment_term={"name": name} + ) self.assertIsInstance(edited_enrollment_term, EnrollmentTerm) self.assertTrue(hasattr(edited_enrollment_term, 'name')) diff --git a/tests/test_external_feed.py b/tests/test_external_feed.py index 2f64df45..df815c49 100644 --- a/tests/test_external_feed.py +++ b/tests/test_external_feed.py @@ -10,7 +10,6 @@ @requests_mock.Mocker() class TestExternalFeed(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) diff --git a/tests/test_external_tool.py b/tests/test_external_tool.py index a9e9b57e..a6963972 100644 --- a/tests/test_external_tool.py +++ b/tests/test_external_tool.py @@ -15,7 +15,6 @@ @requests_mock.Mocker() class TestExternalTool(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -94,14 +93,14 @@ def test_get_sessionless_launch_url(self, m): requires = {'external_tool': ['get_sessionless_launch_url_course']} register_uris(requires, m) - self.assertIsInstance(self.ext_tool_course.get_sessionless_launch_url(), text_type) + self.assertIsInstance( + self.ext_tool_course.get_sessionless_launch_url(), text_type + ) def test_get_sessionless_launch_url_no_url(self, m): requires = { 'course': ['get_by_id_2'], - 'external_tool': [ - 'get_by_id_course_2', 'sessionless_launch_no_url' - ] + 'external_tool': ['get_by_id_course_2', 'sessionless_launch_no_url'], } register_uris(requires, m) diff --git a/tests/test_favorite.py b/tests/test_favorite.py index 04a992b4..3b5adb7e 100644 --- a/tests/test_favorite.py +++ b/tests/test_favorite.py @@ -11,13 +11,16 @@ @requests_mock.Mocker() class TestFavorite(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { - 'current_user': ['add_favorite_course', 'add_favorite_group', 'get_by_id'] + 'current_user': [ + 'add_favorite_course', + 'add_favorite_group', + 'get_by_id', + ] } register_uris(requires, m) diff --git a/tests/test_file.py b/tests/test_file.py index 483bfdcb..a5bd48d8 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -13,12 +13,13 @@ @requests_mock.Mocker() class TestFile(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'list_course_files', 'list_course_files2']}, m) + register_uris( + {'course': ['get_by_id', 'list_course_files', 'list_course_files2']}, m + ) self.course = self.canvas.get_course(1) self.file = self.course.get_files()[0] diff --git a/tests/test_folder.py b/tests/test_folder.py index f7cae7a8..e6ab2754 100644 --- a/tests/test_folder.py +++ b/tests/test_folder.py @@ -14,7 +14,6 @@ @requests_mock.Mocker() class TestFolder(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) diff --git a/tests/test_grading_period.py b/tests/test_grading_period.py index 357dce65..76e1b126 100644 --- a/tests/test_grading_period.py +++ b/tests/test_grading_period.py @@ -12,13 +12,12 @@ @requests_mock.Mocker() class TestGradingPeriod(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) self.grading_period = GradingPeriod( self.canvas._Canvas__requester, - {"title": "grading period 1", "id": 1, "course_id": 1} + {"title": "grading period 1", "id": 1, "course_id": 1}, ) def test_str(self, m): @@ -31,10 +30,12 @@ def test_update(self, m): register_uris({'grading_period': ['update']}, m) edited_grading_period = self.grading_period.update( - grading_period=[{ - 'start_date': '2019-06-10T06:00:00Z', - 'end_date': '2019-06-15T06:00:00Z' - }] + grading_period=[ + { + 'start_date': '2019-06-10T06:00:00Z', + 'end_date': '2019-06-15T06:00:00Z', + } + ] ) self.assertIsInstance(edited_grading_period, GradingPeriod) @@ -55,7 +56,7 @@ def test_update_without_list(self, m): self.grading_period.update( grading_period={ 'start_date': '2019-06-10T06:00:00Z', - 'end_date': '2019-06-15T06:00:00Z' + 'end_date': '2019-06-15T06:00:00Z', } ) @@ -64,18 +65,18 @@ def test_update_without_start_date(self, m): register_uris({'grading_period': ['update']}, m) with self.assertRaises(RequiredFieldMissing): - self.grading_period.update(grading_period=[{ - 'end_date': '2019-06-15T06:00:00Z' - }]) + self.grading_period.update( + grading_period=[{'end_date': '2019-06-15T06:00:00Z'}] + ) # Check that the appropriate exception is raised when no list is given. def test_update_without_end_date(self, m): register_uris({'grading_period': ['update']}, m) with self.assertRaises(RequiredFieldMissing): - self.grading_period.update(grading_period=[{ - 'start_date': '2019-06-10T06:00:00Z' - }]) + self.grading_period.update( + grading_period=[{'start_date': '2019-06-10T06:00:00Z'}] + ) # delete() def test_delete(self, m): diff --git a/tests/test_grading_standard.py b/tests/test_grading_standard.py index 2a8d3f80..3d7f5d26 100644 --- a/tests/test_grading_standard.py +++ b/tests/test_grading_standard.py @@ -10,14 +10,11 @@ @requests_mock.Mocker() class TestGradingStandard(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id', 'get_single_grading_standard'] - }, m) + register_uris({'course': ['get_by_id', 'get_single_grading_standard']}, m) self.course = self.canvas.get_course(1) self.grading_standard = self.course.get_single_grading_standard(1) diff --git a/tests/test_group.py b/tests/test_group.py index 63b9e69a..c59fea84 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -25,7 +25,6 @@ @requests_mock.Mocker() class TestGroup(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -128,6 +127,7 @@ def test_list_users(self, m): with warnings.catch_warnings(record=True) as warning_list: from canvasapi.user import User + users = self.group.list_users() user_list = [user for user in users] self.assertIsInstance(user_list[0], User) @@ -141,6 +141,7 @@ def test_get_users(self, m): register_uris({'group': ['list_users', 'list_users_p2']}, m) from canvasapi.user import User + users = self.group.get_users() user_list = [user for user in users] self.assertIsInstance(user_list[0], User) @@ -148,16 +149,10 @@ def test_get_users(self, m): # remove_user() def test_remove_user(self, m): - register_uris( - { - 'group': [ - 'list_users', - 'list_users_p2', - 'remove_user' - ] - }, m) + register_uris({'group': ['list_users', 'list_users_p2', 'remove_user']}, m) from canvasapi.user import User + user_by_id = self.group.remove_user(1) self.assertIsInstance(user_by_id, User) @@ -221,14 +216,7 @@ def test_get_memberships(self, m): # get_membership() def test_get_membership(self, m): - register_uris( - { - 'group': [ - 'get_membership', - 'list_users', - 'list_users_p2' - ] - }, m) + register_uris({'group': ['get_membership', 'list_users', 'list_users_p2']}, m) membership_by_id = self.group.get_membership(1, "users") self.assertIsInstance(membership_by_id, GroupMembership) @@ -240,13 +228,8 @@ def test_get_membership(self, m): # create_membership() def test_create_membership(self, m): register_uris( - { - 'group': [ - 'create_membership', - 'list_users', - 'list_users_p2' - ] - }, m) + {'group': ['create_membership', 'list_users', 'list_users_p2']}, m + ) response = self.group.create_membership(1) self.assertIsInstance(response, GroupMembership) @@ -258,13 +241,8 @@ def test_create_membership(self, m): # update_membership() def test_update_membership(self, m): register_uris( - { - 'group': [ - 'list_users', - 'list_users_p2', - 'update_membership_user' - ] - }, m) + {'group': ['list_users', 'list_users_p2', 'update_membership_user']}, m + ) updated_membership_by_id = self.group.update_membership(1) self.assertIsInstance(updated_membership_by_id, GroupMembership) @@ -275,13 +253,7 @@ def test_update_membership(self, m): # get_discussion_topic() def test_get_discussion_topic(self, m): - register_uris( - { - 'group': [ - 'get_discussion_topic', - 'get_discussion_topics' - ] - }, m) + register_uris({'group': ['get_discussion_topic', 'get_discussion_topics']}, m) group_id = 1 discussion_by_id = self.group.get_discussion_topic(group_id) @@ -314,12 +286,8 @@ def test_get_file(self, m): # get_full_discussion_topic def test_get_full_discussion_topic(self, m): register_uris( - { - 'group': [ - 'get_full_discussion_topic', - 'get_discussion_topics' - ] - }, m) + {'group': ['get_full_discussion_topic', 'get_discussion_topics']}, m + ) discussion_by_id = self.group.get_full_discussion_topic(1) self.assertIsInstance(discussion_by_id, dict) @@ -537,8 +505,9 @@ def test_create_content_migration(self, m): self.assertTrue(hasattr(content_migration, 'migration_type')) def test_create_content_migration_migrator(self, m): - register_uris({'group': ['create_content_migration', - 'get_migration_systems_multiple']}, m) + register_uris( + {'group': ['create_content_migration', 'get_migration_systems_multiple']}, m + ) migrators = self.group.get_migration_systems() content_migration = self.group.create_content_migration(migrators[0]) @@ -635,7 +604,6 @@ def test_export_content(self, m): @requests_mock.Mocker() class TestGroupMembership(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -659,11 +627,7 @@ def test_update(self, m): # remove_user() def test_remove_user(self, m): - register_uris( - { - 'group': ['remove_user'], - 'user': ['get_by_id'] - }, m) + register_uris({'group': ['remove_user'], 'user': ['get_by_id']}, m) response_by_id = self.membership.remove_user(1) self.assertIsInstance(response_by_id, dict) @@ -686,7 +650,6 @@ def test_remove_self(self, m): @requests_mock.Mocker() class TestGroupCategory(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: @@ -785,10 +748,7 @@ def test_assign_members(self, m): from canvasapi.paginated_list import PaginatedList requires = { - 'group': [ - 'category_assign_members_true', - 'category_assign_members_false' - ] + 'group': ['category_assign_members_true', 'category_assign_members_false'] } register_uris(requires, m) diff --git a/tests/test_login.py b/tests/test_login.py index 6b910003..1a38489f 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -11,20 +11,15 @@ @requests_mock.Mocker() class TestLogin(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'account': ['get_by_id'], - 'login': ['create_user_login'] - }, m) + register_uris({'account': ['get_by_id'], 'login': ['create_user_login']}, m) self.account = self.canvas.get_account(1) self.login = self.account.create_user_login( - user={'id': 1}, - login={'unique_id': 'belieber@example.com'} + user={'id': 1}, login={'unique_id': 'belieber@example.com'} ) # delete() @@ -43,8 +38,7 @@ def test_edit_user_login(self, m): unique_id = 'newemail@example.com' edited_user_login = self.login.edit( - user={'id': 1}, - login={'unique_id': unique_id}, + user={'id': 1}, login={'unique_id': unique_id} ) self.assertIsInstance(edited_user_login, Login) diff --git a/tests/test_module.py b/tests/test_module.py index df738e34..0a654f60 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -13,7 +13,6 @@ @requests_mock.Mocker() class TestModule(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -105,10 +104,7 @@ def test_create_module_item(self, m): register_uris({'module': ['create_module_item']}, m) module_item = self.module.create_module_item( - module_item={ - 'type': 'Page', - 'content_id': 1 - } + module_item={'type': 'Page', 'content_id': 1} ) self.assertIsInstance(module_item, ModuleItem) self.assertTrue(hasattr(module_item, 'course_id')) @@ -116,15 +112,11 @@ def test_create_module_item(self, m): def test_create_module_item_fail1(self, m): with self.assertRaises(RequiredFieldMissing): - self.module.create_module_item( - module_item={'content_id': 1} - ) + self.module.create_module_item(module_item={'content_id': 1}) def test_create_module_item_fail2(self, m): with self.assertRaises(RequiredFieldMissing): - self.module.create_module_item( - module_item={'type': 'Page'} - ) + self.module.create_module_item(module_item={'type': 'Page'}) # __str__ def test__str__(self, m): @@ -134,14 +126,13 @@ def test__str__(self, m): @requests_mock.Mocker() class TestModuleItem(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { 'course': ['get_by_id', 'get_module_by_id'], - 'module': ['get_module_item_by_id'] + 'module': ['get_module_item_by_id'], } register_uris(requires, m) @@ -154,9 +145,7 @@ def test_edit_module_item(self, m): register_uris({'module': ['edit_module_item']}, m) title = 'New Title' - edited_module_item = self.module_item.edit( - module_item={'title': title} - ) + edited_module_item = self.module_item.edit(module_item={'title': title}) self.assertIsInstance(edited_module_item, ModuleItem) self.assertTrue(hasattr(edited_module_item, 'title')) diff --git a/tests/test_notification_preference.py b/tests/test_notification_preference.py index 41ad6bdd..c834bee6 100644 --- a/tests/test_notification_preference.py +++ b/tests/test_notification_preference.py @@ -10,7 +10,6 @@ @requests_mock.Mocker() class TestNotificationPreference(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -18,8 +17,10 @@ def setUp(self): register_uris( { 'user': ['get_by_id', 'list_comm_channels'], - 'communication_channel': ['get_preference'] - }, m) + 'communication_channel': ['get_preference'], + }, + m, + ) self.user = self.canvas.get_user(1) self.comm_chan = self.user.get_communication_channels()[0] diff --git a/tests/test_outcome.py b/tests/test_outcome.py index 63ce378c..99d99e85 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -24,9 +24,10 @@ def setUp(self): 'canvas_root_outcome_group', 'course_root_outcome_group', 'course_outcome_links_in_context', - 'outcome_example' - ] - }, m + 'outcome_example', + ], + }, + m, ) self.course = self.canvas.get_course(1) @@ -60,9 +61,10 @@ def setUp(self): 'course': ['get_by_id'], 'outcome': [ 'account_outcome_links_in_context', - 'course_outcome_links_in_context' - ] - }, m + 'course_outcome_links_in_context', + ], + }, + m, ) self.account = self.canvas.get_account(1) @@ -78,7 +80,9 @@ def test__str__(self, m): # get_outcome() def test_get_outcome(self, m): - register_uris({'outcome': ['outcome_example', 'course_outcome_links_in_context']}, m) + register_uris( + {'outcome': ['outcome_example', 'course_outcome_links_in_context']}, m + ) result = self.course_outcome_links[0].get_outcome() self.assertIsInstance(result, Outcome) @@ -90,10 +94,11 @@ def test_get_outcome_group(self, m): 'outcome_group_example_account', 'account_outcome_links_in_context', 'outcome_group_example_course', - 'course_outcome_links_in_context' + 'course_outcome_links_in_context', ] - }, m - ) + }, + m, + ) result = self.course_outcome_links[0].get_outcome_group() self.assertIsInstance(result, OutcomeGroup) result = self.account_outcome_links[0].get_outcome_group() @@ -115,9 +120,10 @@ def setUp(self): 'canvas_root_outcome_group', 'course_root_outcome_group', 'course_outcome_links_in_context', - 'outcome_example' - ] - }, m + 'outcome_example', + ], + }, + m, ) self.canvas_outcome_group = self.canvas.get_root_outcome_group() @@ -146,9 +152,11 @@ def test_update(self, m): 'outcome': [ 'outcome_group_update_global', 'outcome_group_update_account', - 'outcome_group_update_course' + 'outcome_group_update_course', ] - }, m) + }, + m, + ) new_title = "New Outcome Group Title" @@ -177,9 +185,11 @@ def test_delete(self, m): 'outcome': [ 'outcome_group_delete_global', 'outcome_group_delete_account', - 'outcome_group_delete_course' + 'outcome_group_delete_course', ] - }, m) + }, + m, + ) self.assertEqual(self.account_outcome_group.title, 'ROOT') result = self.account_outcome_group.delete() @@ -200,15 +210,19 @@ def test_list_linked_outcomes(self, m): 'outcome': [ 'outcome_group_list_linked_outcomes_account', 'outcome_group_list_linked_outcomes_global', - 'outcome_group_list_linked_outcomes_courses' + 'outcome_group_list_linked_outcomes_courses', ] - }, m) + }, + m, + ) with warnings.catch_warnings(record=True) as warning_list: result = self.account_outcome_group.list_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) self.assertEqual(result[0].outcome_group['id'], 2) - self.assertEqual(result[0].outcome_group['title'], "Account Test Outcome Group") + self.assertEqual( + result[0].outcome_group['title'], "Account Test Outcome Group" + ) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -217,7 +231,9 @@ def test_list_linked_outcomes(self, m): result = self.canvas_outcome_group.list_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) self.assertEqual(result[0].outcome_group['id'], 2) - self.assertEqual(result[0].outcome_group['title'], "Global Test Outcome Group") + self.assertEqual( + result[0].outcome_group['title'], "Global Test Outcome Group" + ) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -226,7 +242,9 @@ def test_list_linked_outcomes(self, m): result = self.course_outcome_group.list_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) self.assertEqual(result[0].outcome_group['id'], 2) - self.assertEqual(result[0].outcome_group['title'], "Course Test Outcome Group") + self.assertEqual( + result[0].outcome_group['title'], "Course Test Outcome Group" + ) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -238,9 +256,11 @@ def test_get_linked_outcomes(self, m): 'outcome': [ 'outcome_group_list_linked_outcomes_account', 'outcome_group_list_linked_outcomes_global', - 'outcome_group_list_linked_outcomes_courses' + 'outcome_group_list_linked_outcomes_courses', ] - }, m) + }, + m, + ) result = self.account_outcome_group.get_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) @@ -265,9 +285,11 @@ def test_link_existing(self, m): 'outcome_example', 'outcome_group_link_existing_global', 'outcome_group_link_existing_account', - 'outcome_group_link_existing_course' + 'outcome_group_link_existing_course', ] - }, m) + }, + m, + ) result = self.canvas_outcome_group.link_existing(self.example_outcome) self.assertIsInstance(result, OutcomeLink) @@ -300,9 +322,11 @@ def test_link_new(self, m): 'outcome': [ 'outcome_group_link_new_global', 'outcome_group_link_new_account', - 'outcome_group_link_new_course' + 'outcome_group_link_new_course', ] - }, m) + }, + m, + ) new_title = "New Outcome" @@ -332,9 +356,11 @@ def test_unlink_outcome(self, m): 'outcome_example', 'outcome_group_unlink_outcome_global', 'outcome_group_unlink_outcome_account', - 'outcome_group_unlink_outcome_course' + 'outcome_group_unlink_outcome_course', ] - }, m) + }, + m, + ) result = self.canvas_outcome_group.unlink_outcome(self.example_outcome) self.assertTrue(result) @@ -361,9 +387,11 @@ def test_list_subgroups(self, m): 'outcome': [ 'outcome_group_list_subgroups_global', 'outcome_group_list_subgroups_account', - 'outcome_group_list_subgroups_course' + 'outcome_group_list_subgroups_course', ] - }, m) + }, + m, + ) with warnings.catch_warnings(record=True) as warning_list: result = self.canvas_outcome_group.list_subgroups() @@ -408,9 +436,11 @@ def test_get_subgroups(self, m): 'outcome': [ 'outcome_group_list_subgroups_global', 'outcome_group_list_subgroups_account', - 'outcome_group_list_subgroups_course' + 'outcome_group_list_subgroups_course', ] - }, m) + }, + m, + ) result = self.canvas_outcome_group.get_subgroups() self.assertIsInstance(result[0], OutcomeGroup) @@ -467,24 +497,32 @@ def test_create_subgroup(self, m): 'outcome': [ 'outcome_group_create_subgroup_global', 'outcome_group_create_subgroup_account', - 'outcome_group_create_subgroup_course' + 'outcome_group_create_subgroup_course', ] - }, m) + }, + m, + ) new_title = "New Subgroup Title" result = self.canvas_outcome_group.create_subgroup(new_title) - self.assertEqual(self.canvas_outcome_group.id, result.parent_outcome_group['id']) + self.assertEqual( + self.canvas_outcome_group.id, result.parent_outcome_group['id'] + ) self.assertEqual(result.parent_outcome_group['title'], "Parent of Subgroup") self.assertEqual(result.title, "New Subgroup Title") result = self.account_outcome_group.create_subgroup(new_title) - self.assertEqual(self.canvas_outcome_group.id, result.parent_outcome_group['id']) + self.assertEqual( + self.canvas_outcome_group.id, result.parent_outcome_group['id'] + ) self.assertEqual(result.parent_outcome_group['title'], "Parent of Subgroup") self.assertEqual(result.title, "New Subgroup Title") result = self.course_outcome_group.create_subgroup(new_title) - self.assertEqual(self.canvas_outcome_group.id, result.parent_outcome_group['id']) + self.assertEqual( + self.canvas_outcome_group.id, result.parent_outcome_group['id'] + ) self.assertEqual(result.parent_outcome_group['title'], "Parent of Subgroup") self.assertEqual(result.title, "New Subgroup Title") @@ -495,32 +533,48 @@ def test_import_outcome_group(self, m): 'outcome': [ 'outcome_group_import_outcome_group_global', 'outcome_group_import_outcome_group_account', - 'outcome_group_import_outcome_group_course' + 'outcome_group_import_outcome_group_course', ] - }, m) + }, + m, + ) result = self.canvas_outcome_group.import_outcome_group(3) self.assertEqual(result.id, 4) self.assertEqual(result.title, "Global Imported Subgroup Title") - self.assertEqual(result.parent_outcome_group['id'], self.canvas_outcome_group.id) - self.assertEqual(result.parent_outcome_group['title'], self.canvas_outcome_group.title) + self.assertEqual( + result.parent_outcome_group['id'], self.canvas_outcome_group.id + ) + self.assertEqual( + result.parent_outcome_group['title'], self.canvas_outcome_group.title + ) result = self.account_outcome_group.import_outcome_group(3) self.assertEqual(result.id, 4) self.assertEqual(result.title, "Account Imported Subgroup Title") - self.assertEqual(result.parent_outcome_group['id'], self.account_outcome_group.id) - self.assertEqual(result.parent_outcome_group['title'], self.account_outcome_group.title) + self.assertEqual( + result.parent_outcome_group['id'], self.account_outcome_group.id + ) + self.assertEqual( + result.parent_outcome_group['title'], self.account_outcome_group.title + ) result = self.course_outcome_group.import_outcome_group(3) self.assertEqual(result.id, 4) self.assertEqual(result.title, "Course Imported Subgroup Title") - self.assertEqual(result.parent_outcome_group['id'], self.course_outcome_group.id) - self.assertEqual(result.parent_outcome_group['title'], self.course_outcome_group.title) + self.assertEqual( + result.parent_outcome_group['id'], self.course_outcome_group.id + ) + self.assertEqual( + result.parent_outcome_group['title'], self.course_outcome_group.title + ) result_by_obj = self.course_outcome_group.import_outcome_group(result) self.assertEqual(result_by_obj.id, 4) self.assertEqual(result_by_obj.title, "Course Imported Subgroup Title") - self.assertEqual(result_by_obj.parent_outcome_group['id'], self.course_outcome_group.id) + self.assertEqual( + result_by_obj.parent_outcome_group['id'], self.course_outcome_group.id + ) self.assertEqual( result_by_obj.parent_outcome_group['title'], self.course_outcome_group.title ) diff --git a/tests/test_page.py b/tests/test_page.py index c60df479..f0565e05 100644 --- a/tests/test_page.py +++ b/tests/test_page.py @@ -14,7 +14,6 @@ @requests_mock.Mocker() class TestPage(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -22,7 +21,7 @@ def setUp(self): requires = { 'course': ['get_by_id'], 'group': ['get_by_id', 'pages_get_page'], - 'page': ['get_page'] + 'page': ['get_page'], } register_uris(requires, m) @@ -155,7 +154,6 @@ def test_get_parent_group(self, m): @requests_mock.Mocker() class TestPageRevision(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -163,7 +161,7 @@ def setUp(self): requires = { 'course': ['get_by_id', 'get_page'], 'group': ['get_by_id', 'pages_get_page'], - 'page': ['get_latest_rev_by_id', 'get_latest_rev_by_id_group'] + 'page': ['get_latest_rev_by_id', 'get_latest_rev_by_id_group'], } register_uris(requires, m) diff --git a/tests/test_page_view.py b/tests/test_page_view.py index b8600ded..04dee047 100644 --- a/tests/test_page_view.py +++ b/tests/test_page_view.py @@ -10,7 +10,6 @@ @requests_mock.Mocker() class TestPageView(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) diff --git a/tests/test_paginated_list.py b/tests/test_paginated_list.py index 74bae5bb..73fa48f8 100644 --- a/tests/test_paginated_list.py +++ b/tests/test_paginated_list.py @@ -13,7 +13,6 @@ @requests_mock.Mocker() class TestPaginatedList(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) self.requester = self.canvas._Canvas__requester @@ -22,24 +21,14 @@ def setUp(self): def test_paginated_list_empty(self, m): register_uris({'paginated_list': ['empty']}, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'empty_list' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'empty_list') item_list = [item for item in pag_list] self.assertEqual(len(item_list), 0) def test_paginated_list_single(self, m): register_uris({'paginated_list': ['single']}, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'single_item' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'single_item') item_list = [item for item in pag_list] self.assertEqual(len(item_list), 1) self.assertIsInstance(item_list[0], User) @@ -47,12 +36,7 @@ def test_paginated_list_single(self, m): def test_paginated_list_two_one_page(self, m): register_uris({'paginated_list': ['2_1_page']}, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'two_objects_one_page' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'two_objects_one_page') item_list = [item for item in pag_list] self.assertEqual(len(item_list), 2) self.assertIsInstance(item_list[0], User) @@ -60,93 +44,53 @@ def test_paginated_list_two_one_page(self, m): def test_paginated_list_four_two_pages(self, m): register_uris({'paginated_list': ['4_2_pages_p1', '4_2_pages_p2']}, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'four_objects_two_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'four_objects_two_pages') item_list = [item for item in pag_list] self.assertEqual(len(item_list), 4) self.assertIsInstance(item_list[0], User) def test_paginated_list_six_three_pages(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') item_list = [item for item in pag_list] self.assertEqual(len(item_list), 6) self.assertIsInstance(item_list[0], User) # reusing iterator def test_iterator(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') list_1 = [item for item in pag_list] list_2 = [item for item in pag_list] self.assertEqual(list_1, list_2) # get item def test_getitem_first(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') first_item = pag_list[0] self.assertIsInstance(first_item, User) def test_getitem_second_page(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') third_item = pag_list[2] self.assertIsInstance(third_item, User) # slicing def test_slice_beginning(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') first_two_items = pag_list[:2] item_list = [item for item in first_two_items] self.assertEqual(len(item_list), 2) @@ -155,17 +99,10 @@ def test_slice_beginning(self, m): self.assertEqual(item_list[0].id, '1') def test_slice_middle(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') middle_two_items = pag_list[2:4] item_list = [item for item in middle_two_items] self.assertEqual(len(item_list), 2) @@ -174,17 +111,10 @@ def test_slice_middle(self, m): self.assertEqual(item_list[0].id, '3') def test_slice_end(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') middle_two_items = pag_list[4:6] item_list = [item for item in middle_two_items] self.assertEqual(len(item_list), 2) @@ -193,61 +123,36 @@ def test_slice_end(self, m): self.assertEqual(item_list[0].id, '5') def test_slice_oversize(self, m): - requires = { - 'paginated_list': ['4_2_pages_p1', '4_2_pages_p2'] - } + requires = {'paginated_list': ['4_2_pages_p1', '4_2_pages_p2']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'four_objects_two_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'four_objects_two_pages') oversized_slice = pag_list[0:10] item_list = [item for item in oversized_slice] self.assertEqual(len(item_list), 4) def test_slice_out_of_bounds(self, m): - requires = { - 'paginated_list': ['4_2_pages_p1', '4_2_pages_p2'] - } + requires = {'paginated_list': ['4_2_pages_p1', '4_2_pages_p2']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'four_objects_two_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'four_objects_two_pages') out_of_bounds = pag_list[4:5] item_list = [item for item in out_of_bounds] self.assertEqual(len(item_list), 0) # __repr__() def test_repr(self, m): - requires = { - 'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3'] - } + requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} register_uris(requires, m) - pag_list = PaginatedList( - User, - self.requester, - 'GET', - 'six_objects_three_pages' - ) + pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') self.assertEqual(pag_list.__repr__(), '') def test_root_element_incorrect(self, m): register_uris({'account': ['get_enrollment_terms']}, m) pag_list = PaginatedList( - EnrollmentTerm, - self.requester, - 'GET', - 'accounts/1/terms', - _root='wrong' + EnrollmentTerm, self.requester, 'GET', 'accounts/1/terms', _root='wrong' ) with self.assertRaises(ValueError): @@ -261,7 +166,7 @@ def test_root_element(self, m): self.requester, 'GET', 'accounts/1/terms', - _root='enrollment_terms' + _root='enrollment_terms', ) self.assertIsInstance(pag_list[0], EnrollmentTerm) diff --git a/tests/test_peer_review.py b/tests/test_peer_review.py index 092fc68c..1cddb71c 100644 --- a/tests/test_peer_review.py +++ b/tests/test_peer_review.py @@ -10,21 +10,22 @@ @requests_mock.Mocker() class TestPeerReview(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { 'course': ['get_by_id', 'get_assignment_by_id'], - 'assignment': ['list_peer_reviews'] + 'assignment': ['list_peer_reviews'], } register_uris(requires, m) self.course = self.canvas.get_course(1) self.assignment = self.course.get_assignment(1) - self.peer_reviews = [peer_review for peer_review in self.assignment.get_peer_reviews()] + self.peer_reviews = [ + peer_review for peer_review in self.assignment.get_peer_reviews() + ] # __str__() def test__str__(self, m): diff --git a/tests/test_planner.py b/tests/test_planner.py index 58eff05f..d87829b3 100644 --- a/tests/test_planner.py +++ b/tests/test_planner.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestPlannerNote(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -66,8 +65,7 @@ def test_create_planner_note(self, m): self.assertTrue(hasattr(note_create_1, 'title')) note_create_2 = self.canvas.create_planner_note( - title='Perform photosynthesis', - todo_date='2019-09-05T12:10:30Z' + title='Perform photosynthesis', todo_date='2019-09-05T12:10:30Z' ) self.assertIsInstance(note_create_2, PlannerNote) self.assertTrue(hasattr(note_create_2, 'title')) @@ -82,9 +80,8 @@ def test_update(self, m): self.assertEqual(note_update_1.title, 'Go to restroom') note_update_2 = self.note.update( - title='Go to restroom', - todo_date='2020-01-07T15:16:18Z' - ) + title='Go to restroom', todo_date='2020-01-07T15:16:18Z' + ) self.assertIsInstance(note_update_2, PlannerNote) self.assertEqual(note_update_2.title, 'Go to restroom') self.assertEqual(note_update_2.todo_date, '2020-01-07T15:16:18Z') @@ -102,7 +99,6 @@ def test_delete(self, m): @requests_mock.Mocker() class TestPlannerOverride(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -151,8 +147,7 @@ def test_create_planner_override(self, m): register_uris({'planner': ['create_planner_override']}, m) override_create = self.canvas.create_planner_override( - plannable_type='assignment', - plannable_id=69 + plannable_type='assignment', plannable_id=69 ) self.assertIsInstance(override_create, PlannerOverride) self.assertTrue(hasattr(override_create, 'plannable_id')) @@ -165,7 +160,9 @@ def test_create_planner_override_fail_1(self, m): # create_planner_override() def test_create_planner_override_fail_2(self, m): with self.assertRaises(RequiredFieldMissing): - self.canvas.create_planner_override(plannable_type='assignment', plannable_id=None) + self.canvas.create_planner_override( + plannable_type='assignment', plannable_id=None + ) # update() def test_update(self, m): diff --git a/tests/test_poll.py b/tests/test_poll.py index 4f065d14..9282b5c5 100644 --- a/tests/test_poll.py +++ b/tests/test_poll.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestPoll(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -58,8 +57,9 @@ def test_create_poll(self, m): self.assertIsInstance(new_poll_q, Poll) self.assertTrue(hasattr(new_poll_q, 'question')) - new_poll_q_d = self.canvas.create_poll([{'question': 'Is this a question?'}, - {'description': 'This is a test.'}]) + new_poll_q_d = self.canvas.create_poll( + [{'question': 'Is this a question?'}, {'description': 'This is a test.'}] + ) self.assertIsInstance(new_poll_q_d, Poll) self.assertTrue(hasattr(new_poll_q_d, 'question')) self.assertTrue(hasattr(new_poll_q_d, 'description')) @@ -77,10 +77,12 @@ def test_update(self, m): self.assertIsInstance(updated_poll_q, Poll) self.assertEqual(updated_poll_q.question, 'Is this not a question?') - updated_poll_q_and_d = self.poll.update([ + updated_poll_q_and_d = self.poll.update( + [ {'question': 'Is this not a question?'}, - {'description': 'This is not a test.'} - ]) + {'description': 'This is not a test.'}, + ] + ) self.assertIsInstance(updated_poll_q_and_d, Poll) self.assertEqual(updated_poll_q_and_d.question, 'Is this not a question?') self.assertEqual(updated_poll_q_and_d.description, 'This is not a test.') diff --git a/tests/test_poll_choice.py b/tests/test_poll_choice.py index a37036e0..b6b40e90 100644 --- a/tests/test_poll_choice.py +++ b/tests/test_poll_choice.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestPollChoice(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -60,20 +59,23 @@ def test_create_choice(self, m): self.assertIsInstance(new_choice_t, PollChoice) self.assertTrue(hasattr(new_choice_t, 'text')) - new_choice_t_ic = self.poll.create_choice([{'text': 'Example choice'}, - {'is_correct': True}]) + new_choice_t_ic = self.poll.create_choice( + [{'text': 'Example choice'}, {'is_correct': True}] + ) self.assertIsInstance(new_choice_t_ic, PollChoice) self.assertTrue(hasattr(new_choice_t_ic, 'text')) self.assertTrue(hasattr(new_choice_t_ic, 'is_correct')) - new_choice_t_p = self.poll.create_choice([{'text': 'Example choice'}, {'position': 1}]) + new_choice_t_p = self.poll.create_choice( + [{'text': 'Example choice'}, {'position': 1}] + ) self.assertIsInstance(new_choice_t_p, PollChoice) self.assertTrue(hasattr(new_choice_t_p, 'text')) self.assertTrue(hasattr(new_choice_t_p, 'position')) - new_choice_t_ic_p = self.poll.create_choice([{'text': 'Example choice'}, - {'is_correct': True}, - {'position': 1}]) + new_choice_t_ic_p = self.poll.create_choice( + [{'text': 'Example choice'}, {'is_correct': True}, {'position': 1}] + ) self.assertIsInstance(new_choice_t_ic_p, PollChoice) self.assertTrue(hasattr(new_choice_t_ic_p, 'text')) self.assertTrue(hasattr(new_choice_t_ic_p, 'is_correct')) @@ -92,21 +94,23 @@ def test_update(self, m): self.assertIsInstance(updated_choice_t, PollChoice) self.assertEqual(updated_choice_t.text, 'Changed example') - updated_choice_t_ic = self.poll.poll_choice.update([{'text': 'Changed example'}, - {'is_correct': False}]) + updated_choice_t_ic = self.poll.poll_choice.update( + [{'text': 'Changed example'}, {'is_correct': False}] + ) self.assertIsInstance(updated_choice_t_ic, PollChoice) self.assertEqual(updated_choice_t_ic.text, 'Changed example') self.assertFalse(updated_choice_t_ic.is_correct) - updated_choice_t_p = self.poll.poll_choice.update([{'text': 'Changed example'}, - {'position': 2}]) + updated_choice_t_p = self.poll.poll_choice.update( + [{'text': 'Changed example'}, {'position': 2}] + ) self.assertIsInstance(updated_choice_t_p, PollChoice) self.assertEqual(updated_choice_t_p.text, 'Changed example') self.assertEqual(updated_choice_t_p.position, 2) - updated_choice_t_ic_p = self.poll.poll_choice.update([{'text': 'Changed example'}, - {'is_correct': False}, - {'position': 2}]) + updated_choice_t_ic_p = self.poll.poll_choice.update( + [{'text': 'Changed example'}, {'is_correct': False}, {'position': 2}] + ) self.assertIsInstance(updated_choice_t_ic_p, PollChoice) self.assertEqual(updated_choice_t_ic_p.text, 'Changed example') self.assertFalse(updated_choice_t_ic.is_correct) diff --git a/tests/test_poll_session.py b/tests/test_poll_session.py index f90844ab..35178620 100644 --- a/tests/test_poll_session.py +++ b/tests/test_poll_session.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestPollSession(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -20,7 +19,7 @@ def setUp(self): requires = { 'user': ['get_by_id'], 'poll': ['get_poll'], - 'poll_session': ['get_session'] + 'poll_session': ['get_session'], } register_uris(requires, m) @@ -70,21 +69,23 @@ def test_create_session(self, m): self.assertIsInstance(new_session_cid, PollSession) self.assertEqual(new_session_cid.course_id, 1) - new_session_cid_sid = self.poll.create_session([{'course_id': 1}, - {'course_section_id': 1}]) + new_session_cid_sid = self.poll.create_session( + [{'course_id': 1}, {'course_section_id': 1}] + ) self.assertIsInstance(new_session_cid_sid, PollSession) self.assertEqual(new_session_cid_sid.course_id, 1) self.assertEqual(new_session_cid_sid.course_section_id, 1) - new_session_cid_hpr = self.poll.create_session([{'course_id': 1}, - {'has_public_results': False}]) + new_session_cid_hpr = self.poll.create_session( + [{'course_id': 1}, {'has_public_results': False}] + ) self.assertIsInstance(new_session_cid_hpr, PollSession) self.assertEqual(new_session_cid_hpr.course_id, 1) self.assertFalse(new_session_cid_hpr.has_public_results) - new_session_cid_sid_hpr = self.poll.create_session([{'course_id': 1}, - {'course_section_id': 1}, - {'has_public_results': False}]) + new_session_cid_sid_hpr = self.poll.create_session( + [{'course_id': 1}, {'course_section_id': 1}, {'has_public_results': False}] + ) self.assertIsInstance(new_session_cid_sid_hpr, PollSession) self.assertEqual(new_session_cid_sid_hpr.course_id, 1) self.assertEqual(new_session_cid_sid_hpr.course_section_id, 1) @@ -104,32 +105,22 @@ def test_update(self, m): self.assertEqual(updated_session_cid.course_id, 2) updated_session_cid_sid = self.poll.poll_session.update( - [ - {'course_id': 2}, - {'course_section_id': 2} - ] - ) + [{'course_id': 2}, {'course_section_id': 2}] + ) self.assertIsInstance(updated_session_cid_sid, PollSession) self.assertEqual(updated_session_cid_sid.course_id, 2) self.assertEqual(updated_session_cid_sid.course_section_id, 2) updated_session_cid_hpr = self.poll.poll_session.update( - [ - {'course_id': 2}, - {'has_public_results': True} - ] - ) + [{'course_id': 2}, {'has_public_results': True}] + ) self.assertIsInstance(updated_session_cid_hpr, PollSession) self.assertEqual(updated_session_cid_hpr.course_id, 2) self.assertTrue(updated_session_cid_hpr.has_public_results) updated_session_cid_sid_hpr = self.poll.poll_session.update( - [ - {'course_id': 2}, - {'course_section_id': 2}, - {'has_public_results': True} - ] - ) + [{'course_id': 2}, {'course_section_id': 2}, {'has_public_results': True}] + ) self.assertIsInstance(updated_session_cid_sid_hpr, PollSession) self.assertEqual(updated_session_cid_sid_hpr.course_id, 2) self.assertEqual(updated_session_cid_sid_hpr.course_section_id, 2) diff --git a/tests/test_poll_submission.py b/tests/test_poll_submission.py index 2ea3615b..27bed326 100644 --- a/tests/test_poll_submission.py +++ b/tests/test_poll_submission.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestPollSubmission(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -20,13 +19,15 @@ def setUp(self): requires = { 'poll': ['get_poll'], 'poll_session': ['get_session'], - 'poll_submission': ['get_submission'] + 'poll_submission': ['get_submission'], } register_uris(requires, m) self.poll = self.canvas.get_poll(1) self.poll.poll_session = self.poll.get_session(1) - self.poll.poll_session.poll_submission = self.poll.poll_session.get_submission(1) + self.poll.poll_session.poll_submission = self.poll.poll_session.get_submission( + 1 + ) # __str__() def test__str__(self, m): @@ -55,7 +56,9 @@ def test_get_submission(self, m): def test_create_submission(self, m): register_uris({'poll_submission': ['create_submission']}, m) - new_submission = self.poll.poll_session.create_submission([{'poll_choice_id': 1}]) + new_submission = self.poll.poll_session.create_submission( + [{'poll_choice_id': 1}] + ) self.assertIsInstance(new_submission, PollSubmission) self.assertEqual(new_submission.poll_choice_id, 1) diff --git a/tests/test_progress.py b/tests/test_progress.py index 8d16355f..b96a2d4e 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -11,14 +11,13 @@ @requests_mock.Mocker() class TestProgress(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: requires = { 'course': ['get_by_id', 'create_group_category'], - 'group': ['category_assign_members_false'] + 'group': ['category_assign_members_false'], } register_uris(requires, m) diff --git a/tests/test_quiz_group.py b/tests/test_quiz_group.py index 09ca78d1..490fc527 100644 --- a/tests/test_quiz_group.py +++ b/tests/test_quiz_group.py @@ -11,15 +11,13 @@ @requests_mock.Mocker() class TestQuizGroup(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id'], - 'quiz': ['get_by_id', 'get_quiz_group'] - }, m) + register_uris( + {'course': ['get_by_id'], 'quiz': ['get_by_id', 'get_quiz_group']}, m + ) self.course = self.canvas.get_course(1) self.quiz_group = self.course.get_quiz(1).get_quiz_group(1) @@ -43,7 +41,9 @@ def test_update(self, m): self.assertEqual(self.quiz_group.quiz_id, 1) self.assertEqual(self.quiz_group.name, quiz_group[0].get('name')) self.assertEqual(self.quiz_group.pick_count, quiz_group[0].get('pick_count')) - self.assertEqual(self.quiz_group.question_points, quiz_group[0].get('question_points')) + self.assertEqual( + self.quiz_group.question_points, quiz_group[0].get('question_points') + ) def test_update_empty_list(self, m): register_uris({'quiz_group': ['update']}, m) diff --git a/tests/test_rubric.py b/tests/test_rubric.py index 454b5c71..8843b9d4 100644 --- a/tests/test_rubric.py +++ b/tests/test_rubric.py @@ -10,14 +10,11 @@ @requests_mock.Mocker() class TestGradingStandard(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id', 'get_rubric_single'] - }, m) + register_uris({'course': ['get_by_id', 'get_rubric_single']}, m) self.course = self.canvas.get_course(1) self.rubric = self.course.get_rubric(1) diff --git a/tests/test_section.py b/tests/test_section.py index e7dfdfa4..ccc35704 100644 --- a/tests/test_section.py +++ b/tests/test_section.py @@ -17,7 +17,6 @@ @requests_mock.Mocker() class TestSection(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -51,11 +50,7 @@ def test_get_enrollments(self, m): self.assertIsInstance(enrollment_list[0], Enrollment) def test_cross_list_section(self, m): - register_uris( - { - 'course': ['get_by_id_2'], - 'section': ['crosslist_section'] - }, m) + register_uris({'course': ['get_by_id_2'], 'section': ['crosslist_section']}, m) section_by_id = self.section.cross_list_section(2) self.assertIsInstance(section_by_id, Section) @@ -91,8 +86,10 @@ def test_submit_assignment(self, m): { 'assignment': ['submit'], 'submission': ['get_by_id_section'], - 'user': ['get_by_id', 'get_user_assignments'] - }, m) + 'user': ['get_by_id', 'get_user_assignments'], + }, + m, + ) assignment_id = 1 sub_type = "online_upload" @@ -112,7 +109,9 @@ def test_submit_assignment(self, m): sub_type = "online_upload" sub_dict = {'submission_type': sub_type} with warnings.catch_warnings(record=True) as warning_list: - assignment_by_obj = self.section.submit_assignment(assignments_obj[0], sub_dict) + assignment_by_obj = self.section.submit_assignment( + assignments_obj[0], sub_dict + ) self.assertIsInstance(assignment_by_obj, Submission) self.assertTrue(hasattr(assignment_by_obj, 'submission_type')) @@ -133,8 +132,10 @@ def test_list_submissions(self, m): register_uris( { 'submission': ['list_submissions'], - 'user': ['get_by_id', 'get_user_assignments'] - }, m) + 'user': ['get_by_id', 'get_user_assignments'], + }, + m, + ) assignment_id = 1 with warnings.catch_warnings(record=True) as warning_list: @@ -212,8 +213,10 @@ def test_get_submission(self, m): register_uris( { 'submission': ['get_by_id_course'], - 'user': ['get_by_id', 'get_user_assignments'] - }, m) + 'user': ['get_by_id', 'get_user_assignments'], + }, + m, + ) assignment_id = 1 user_id = 1 @@ -229,7 +232,9 @@ def test_get_submission(self, m): user_obj = self.canvas.get_user(1) assignments_obj = user_obj.get_assignments(1) with warnings.catch_warnings(record=True) as warning_list: - submission_by_obj = self.section.get_submission(assignments_obj[0], user_obj) + submission_by_obj = self.section.get_submission( + assignments_obj[0], user_obj + ) self.assertIsInstance(submission_by_obj, Submission) self.assertTrue(hasattr(submission_by_obj, 'submission_type')) @@ -242,16 +247,16 @@ def test_update_submission(self, m): register_uris( { 'submission': ['get_by_id_section', 'edit'], - 'user': ['get_by_id', 'get_user_assignments'] - }, m) + 'user': ['get_by_id', 'get_user_assignments'], + }, + m, + ) assignment_id = 1 user_id = 1 with warnings.catch_warnings(record=True) as warning_list: submission_by_id = self.section.update_submission( - assignment_id, - user_id, - submission={'excuse': True} + assignment_id, user_id, submission={'excuse': True} ) self.assertIsInstance(submission_by_id, Submission) @@ -265,9 +270,7 @@ def test_update_submission(self, m): with warnings.catch_warnings(record=True) as warning_list: submission_by_obj = self.section.update_submission( - assignments_obj[0], - user_obj, - submission={'excuse': True} + assignments_obj[0], user_obj, submission={'excuse': True} ) self.assertIsInstance(submission_by_obj, Submission) @@ -282,13 +285,17 @@ def test_mark_submission_as_read(self, m): { 'course': ['mark_submission_as_read'], 'submission': ['get_by_id_section'], - 'user': ['get_by_id', 'get_user_assignments'] - }, m) + 'user': ['get_by_id', 'get_user_assignments'], + }, + m, + ) submission_id = 1 user_id = 1 with warnings.catch_warnings(record=True) as warning_list: - submission_by_id = self.section.mark_submission_as_read(submission_id, user_id) + submission_by_id = self.section.mark_submission_as_read( + submission_id, user_id + ) self.assertTrue(submission_by_id) @@ -298,7 +305,9 @@ def test_mark_submission_as_read(self, m): user_obj = self.canvas.get_user(1) with warnings.catch_warnings(record=True) as warning_list: assignments_obj = user_obj.get_assignments(1) - submission_by_obj = self.section.mark_submission_as_read(assignments_obj[0], user_obj) + submission_by_obj = self.section.mark_submission_as_read( + assignments_obj[0], user_obj + ) self.assertTrue(submission_by_obj) @@ -311,13 +320,17 @@ def test_mark_submission_as_unread(self, m): { 'course': ['mark_submission_as_unread'], 'submission': ['get_by_id_section'], - 'user': ['get_by_id', 'get_user_assignments'] - }, m) + 'user': ['get_by_id', 'get_user_assignments'], + }, + m, + ) user_id = 1 assignment_id = 1 with warnings.catch_warnings(record=True) as warning_list: - submission_by_id = self.section.mark_submission_as_unread(assignment_id, user_id) + submission_by_id = self.section.mark_submission_as_unread( + assignment_id, user_id + ) self.assertTrue(submission_by_id) self.assertEqual(len(warning_list), 1) @@ -327,8 +340,7 @@ def test_mark_submission_as_unread(self, m): assignments_obj = user_obj.get_assignments(1) with warnings.catch_warnings(record=True) as warning_list: submission_by_obj = self.section.mark_submission_as_unread( - assignments_obj[0], - user_obj + assignments_obj[0], user_obj ) self.assertTrue(submission_by_obj) @@ -338,16 +350,9 @@ def test_mark_submission_as_unread(self, m): def test_submissions_bulk_update(self, m): register_uris({'section': ['update_submissions']}, m) register_uris({'progress': ['course_progress']}, m) - progress = self.section.submissions_bulk_update(grade_data={ - '1': { - '1': { - 'posted_grade': 97 - }, - '2': { - 'posted_grade': 98 - } - } - }) + progress = self.section.submissions_bulk_update( + grade_data={'1': {'1': {'posted_grade': 97}, '2': {'posted_grade': 98}}} + ) self.assertIsInstance(progress, Progress) self.assertTrue(progress.context_type == "Course") progress = progress.query() diff --git a/tests/test_sis_import.py b/tests/test_sis_import.py index c9cdb975..34d2abf6 100644 --- a/tests/test_sis_import.py +++ b/tests/test_sis_import.py @@ -12,12 +12,14 @@ @requests_mock.Mocker() class TestSisImportGroup(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = {'account': ['get_by_id', 'get_role'], 'sis_import': ['get_by_id']} + requires = { + 'account': ['get_by_id', 'get_role'], + 'sis_import': ['get_by_id'], + } register_uris(requires, m) self.account = self.canvas.get_account(1) @@ -31,8 +33,11 @@ def test_abort_sis_import(self, m): self.assertIsInstance(aborted_sis_import, SisImport) - self.assertTrue(aborted_sis_import.workflow_state == "aborted" if - aborted_sis_import.progress < 100 else True) + self.assertTrue( + aborted_sis_import.workflow_state == "aborted" + if aborted_sis_import.progress < 100 + else True + ) # restore_states() def test_restore_states(self, m): diff --git a/tests/test_tab.py b/tests/test_tab.py index 6f916ef3..dfecd6ac 100644 --- a/tests/test_tab.py +++ b/tests/test_tab.py @@ -11,15 +11,17 @@ @requests_mock.Mocker() class TestTab(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id', 'list_tabs'], - 'group': ['get_by_id', 'list_tabs'] - }, m) + register_uris( + { + 'course': ['get_by_id', 'list_tabs'], + 'group': ['get_by_id', 'list_tabs'], + }, + m, + ) self.course = self.canvas.get_course(1) diff --git a/tests/test_uploader.py b/tests/test_uploader.py index 6cea0634..d6288fa7 100644 --- a/tests/test_uploader.py +++ b/tests/test_uploader.py @@ -12,7 +12,6 @@ @requests_mock.Mocker() class TestUploader(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) self.requester = self.canvas._Canvas__requester @@ -26,9 +25,7 @@ def tearDown(self): # start() def test_start(self, m): - requires = { - 'uploader': ['upload_response', 'upload_response_upload_url'] - } + requires = {'uploader': ['upload_response', 'upload_response_upload_url']} register_uris(requires, m) uploader = Uploader(self.requester, 'upload_response', self.file) @@ -39,9 +36,7 @@ def test_start(self, m): self.assertIn('url', result[1]) def test_start_path(self, m): - requires = { - 'uploader': ['upload_response', 'upload_response_upload_url'] - } + requires = {'uploader': ['upload_response', 'upload_response_upload_url']} register_uris(requires, m) uploader = Uploader(self.requester, 'upload_response', self.filename) @@ -60,18 +55,20 @@ def test_upload_no_upload_url(self, m): register_uris({'uploader': ['upload_response_no_upload_url']}, m) with self.assertRaises(ValueError): - Uploader(self.requester, 'upload_response_no_upload_url', self.filename).start() + Uploader( + self.requester, 'upload_response_no_upload_url', self.filename + ).start() def test_upload_no_upload_params(self, m): register_uris({'uploader': ['upload_response_no_upload_params']}, m) with self.assertRaises(ValueError): - Uploader(self.requester, 'upload_response_no_upload_params', self.filename).start() + Uploader( + self.requester, 'upload_response_no_upload_params', self.filename + ).start() def test_upload_fail(self, m): - requires = { - 'uploader': ['upload_fail', 'upload_response_fail'] - } + requires = {'uploader': ['upload_fail', 'upload_response_fail']} register_uris(requires, m) uploader = Uploader(self.requester, 'upload_response_fail', self.file) diff --git a/tests/test_user.py b/tests/test_user.py index d52077bd..f750fb1d 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -25,7 +25,6 @@ @requests_mock.Mocker() class TestUser(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) @@ -175,8 +174,10 @@ def test_user_get_assignments(self, m): register_uris( { 'course': ['get_by_id'], - 'user': ['get_user_assignments', 'get_user_assignments2'] - }, m) + 'user': ['get_user_assignments', 'get_user_assignments2'], + }, + m, + ) assignments_by_id = self.user.get_assignments(1) assignment_list = [assignment for assignment in assignments_by_id] @@ -263,11 +264,10 @@ def test_get_communication_channels(self, m): def test_create_communication_channels(self, m): register_uris({'user': ['create_comm_channel']}, m) - channel = { - "type": "email", - "address": "username@example.org" - } - new_channel = self.user.create_communication_channel(communication_channel=channel) + channel = {"type": "email", "address": "username@example.org"} + new_channel = self.user.create_communication_channel( + communication_channel=channel + ) self.assertIsInstance(new_channel, CommunicationChannel) @@ -443,8 +443,9 @@ def test_create_content_migration(self, m): self.assertTrue(hasattr(content_migration, 'migration_type')) def test_create_content_migration_migrator(self, m): - register_uris({'user': ['create_content_migration', - 'get_migration_systems_multiple']}, m) + register_uris( + {'user': ['create_content_migration', 'get_migration_systems_multiple']}, m + ) migrators = self.user.get_migration_systems() content_migration = self.user.create_content_migration(migrators[0]) @@ -532,14 +533,20 @@ def test_export_content(self, m): @requests_mock.Mocker() class TestUserDisplay(unittest.TestCase): - def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({ - 'course': ['get_by_id', 'get_assignment_by_id', 'list_gradeable_students'] - }, m) + register_uris( + { + 'course': [ + 'get_by_id', + 'get_assignment_by_id', + 'list_gradeable_students', + ] + }, + m, + ) self.course = self.canvas.get_course(1) self.assignment = self.course.get_assignment(1) diff --git a/tests/test_validate_docstrings.py b/tests/test_validate_docstrings.py index 23bc6305..77fb1818 100644 --- a/tests/test_validate_docstrings.py +++ b/tests/test_validate_docstrings.py @@ -77,14 +77,16 @@ def register_doc_uri(url, m, code=200): return file_name = url_groups.group(2) - with io.open('tests/fixtures/{}.html'.format(file_name), 'r', encoding='utf-8') as file: + with io.open( + 'tests/fixtures/{}.html'.format(file_name), 'r', encoding='utf-8' + ) as file: data = file.read() m.register_uri( 'GET', url_groups.group(1) + url_groups.group(2) + '.html', text=data, - status_code=code + status_code=code, ) @@ -96,10 +98,7 @@ def verb_mismatch(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request( - 'DELETE', - 'files/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'files/{}'.format(self.id)) return ExampleMethods(self._requester, response.json()) def invalid_verb(self): @@ -111,10 +110,7 @@ def invalid_verb(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request( - 'DELETE', - 'files/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'files/{}'.format(self.id)) return ExampleMethods(self._requester, response.json()) def no_api_call(self): @@ -132,10 +128,7 @@ def good_docstring(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request( - 'DELETE', - 'files/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'files/{}'.format(self.id)) return ExampleMethods(self._requester, response.json()) def multiple_endpoints(self, folder): @@ -152,10 +145,7 @@ def multiple_endpoints(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request( - 'GET', - 'folders/{}'.format(folder_id) - ) + response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) return Folder(self.__requester, response.json()) def multiline_URL(self, **kwargs): @@ -172,10 +162,9 @@ def multiline_URL(self, **kwargs): response = self._requester.request( 'GET', 'users/{}/communication_channels/{}/notification_preferences'.format( - self.user_id, - self.id + self.user_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json()['notification_preferences'] @@ -201,10 +190,7 @@ def invalid_URL(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request( - 'DELETE', - 'files/{}'.format(self.id) - ) + response = self._requester.request('DELETE', 'files/{}'.format(self.id)) return ExampleMethods(self._requester, response.json()) def missing_endpoint_URL(self, folder): @@ -221,10 +207,7 @@ def missing_endpoint_URL(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request( - 'GET', - 'folders/{}'.format(folder_id) - ) + response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) return Folder(self.__requester, response.json()) def endpoint_invalid(self, folder): @@ -241,10 +224,7 @@ def endpoint_invalid(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request( - 'GET', - 'folders/{}'.format(folder_id) - ) + response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) return Folder(self.__requester, response.json()) def not_an_endpoint(self, **kwargs): @@ -261,10 +241,9 @@ def not_an_endpoint(self, **kwargs): response = self._requester.request( 'GET', 'users/{}/communication_channels/{}/notification_preferences'.format( - self.user_id, - self.id + self.user_id, self.id ), - _kwargs=combine_kwargs(**kwargs) + _kwargs=combine_kwargs(**kwargs), ) return response.json()['notification_preferences'] diff --git a/tests/util.py b/tests/util.py index 89a2616b..864b6f7d 100644 --- a/tests/util.py +++ b/tests/util.py @@ -31,16 +31,19 @@ def register_uris(requirements, requests_mocker): obj = data.get(obj_name) if obj is None: - raise ValueError('{} does not exist in {}.json'.format( - obj_name.__repr__(), - fixture - )) + raise ValueError( + '{} does not exist in {}.json'.format(obj_name.__repr__(), fixture) + ) method = requests_mock.ANY if obj['method'] == 'ANY' else obj['method'] if obj['endpoint'] == 'ANY': url = requests_mock.ANY else: - url = get_institution_url(settings.BASE_URL) + '/api/v1/' + obj['endpoint'] + url = ( + get_institution_url(settings.BASE_URL) + + '/api/v1/' + + obj['endpoint'] + ) try: requests_mocker.register_uri( @@ -48,7 +51,7 @@ def register_uris(requirements, requests_mocker): url, json=obj.get('data'), status_code=obj.get('status_code', 200), - headers=obj.get('headers', {}) + headers=obj.get('headers', {}), ) except Exception as e: print(e) From 94dd6a3c5f92617f47814e85e1008e2160167d49 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 9 Jul 2019 16:58:58 -0400 Subject: [PATCH 07/65] Remove skip-string-normalization --- canvasapi/__init__.py | 2 +- canvasapi/account.py | 318 +++++++-------- canvasapi/appointment_group.py | 14 +- canvasapi/assignment.py | 86 ++-- canvasapi/authentication_provider.py | 12 +- canvasapi/blueprint.py | 58 +-- canvasapi/bookmark.py | 8 +- canvasapi/calendar_event.py | 10 +- canvasapi/canvas.py | 232 +++++------ canvasapi/canvas_object.py | 14 +- canvasapi/communication_channel.py | 48 +-- canvasapi/content_migration.py | 70 ++-- canvasapi/conversation.py | 18 +- canvasapi/course.py | 492 +++++++++++------------ canvasapi/course_epub_export.py | 6 +- canvasapi/current_user.py | 42 +- canvasapi/discussion_topic.py | 132 +++---- canvasapi/enrollment.py | 14 +- canvasapi/enrollment_term.py | 6 +- canvasapi/exceptions.py | 6 +- canvasapi/external_tool.py | 38 +- canvasapi/favorite.py | 6 +- canvasapi/file.py | 8 +- canvasapi/folder.py | 24 +- canvasapi/grading_period.py | 20 +- canvasapi/group.py | 194 ++++----- canvasapi/login.py | 6 +- canvasapi/module.py | 62 +-- canvasapi/outcome.py | 80 ++-- canvasapi/page.py | 68 ++-- canvasapi/paginated_list.py | 8 +- canvasapi/planner.py | 14 +- canvasapi/poll.py | 54 +-- canvasapi/poll_choice.py | 14 +- canvasapi/poll_session.py | 42 +- canvasapi/progress.py | 2 +- canvasapi/quiz.py | 158 ++++---- canvasapi/quiz_group.py | 18 +- canvasapi/section.py | 80 ++-- canvasapi/sis_import.py | 8 +- canvasapi/submission.py | 38 +- canvasapi/tab.py | 10 +- canvasapi/upload.py | 28 +- canvasapi/user.py | 142 +++---- pyproject.toml | 2 - tests/settings.py | 12 +- tests/test_account.py | 400 +++++++++---------- tests/test_appointment_group.py | 16 +- tests/test_assignment.py | 122 +++--- tests/test_authentication_providers.py | 12 +- tests/test_blueprint.py | 58 +-- tests/test_bookmark.py | 16 +- tests/test_calendar_event.py | 16 +- tests/test_canvas.py | 254 ++++++------ tests/test_canvas_object.py | 4 +- tests/test_communication_channel.py | 52 +-- tests/test_content_export.py | 6 +- tests/test_content_migration.py | 98 ++--- tests/test_conversation.py | 28 +- tests/test_course.py | 524 ++++++++++++------------- tests/test_current_user.py | 34 +- tests/test_discussion_topic.py | 152 +++---- tests/test_enrollment.py | 10 +- tests/test_enrollment_term.py | 14 +- tests/test_external_feed.py | 2 +- tests/test_external_tool.py | 30 +- tests/test_favorite.py | 12 +- tests/test_file.py | 18 +- tests/test_folder.py | 32 +- tests/test_grading_period.py | 36 +- tests/test_grading_standard.py | 2 +- tests/test_group.py | 226 +++++------ tests/test_login.py | 18 +- tests/test_module.py | 74 ++-- tests/test_notification_preference.py | 6 +- tests/test_outcome.py | 276 ++++++------- tests/test_page.py | 66 ++-- tests/test_page_view.py | 2 +- tests/test_paginated_list.py | 82 ++-- tests/test_peer_review.py | 4 +- tests/test_planner.py | 68 ++-- tests/test_poll.py | 46 +-- tests/test_poll_choice.py | 56 +-- tests/test_poll_session.py | 44 +-- tests/test_poll_submission.py | 28 +- tests/test_progress.py | 6 +- tests/test_quiz_group.py | 30 +- tests/test_requester.py | 74 ++-- tests/test_rubric.py | 2 +- tests/test_section.py | 80 ++-- tests/test_sis_import.py | 12 +- tests/test_submission.py | 52 +-- tests/test_tab.py | 6 +- tests/test_uploader.py | 32 +- tests/test_user.py | 160 ++++---- tests/test_validate_docstrings.py | 56 +-- tests/util.py | 22 +- 97 files changed, 3099 insertions(+), 3101 deletions(-) delete mode 100644 pyproject.toml diff --git a/canvasapi/__init__.py b/canvasapi/__init__.py index 975faf8a..599821b1 100644 --- a/canvasapi/__init__.py +++ b/canvasapi/__init__.py @@ -6,4 +6,4 @@ __all__ = ["Canvas"] -__version__ = '0.13.0' +__version__ = "0.13.0" diff --git a/canvasapi/account.py b/canvasapi/account.py index 95a9826d..11ed6015 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -32,12 +32,12 @@ def abort_sis_imports_pending(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - 'accounts/{}/sis_imports/abort_all_pending'.format(self.id), + "PUT", + "accounts/{}/sis_imports/abort_all_pending".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return response.json().get('aborted', False) + return response.json().get("aborted", False) def activate_role(self, role, **kwargs): """ @@ -53,8 +53,8 @@ def activate_role(self, role, **kwargs): role_id = obj_or_id(role, "role", (Role,)) response = self._requester.request( - 'POST', - 'accounts/{}/roles/{}/activate'.format(self.id, role_id), + "POST", + "accounts/{}/roles/{}/activate".format(self.id, role_id), _kwargs=combine_kwargs(**kwargs), ) return Role(self._requester, response.json()) @@ -71,12 +71,12 @@ def add_authentication_providers(self, **kwargs): from canvasapi.authentication_provider import AuthenticationProvider response = self._requester.request( - 'POST', - 'accounts/{}/authentication_providers'.format(self.id), + "POST", + "accounts/{}/authentication_providers".format(self.id), _kwargs=combine_kwargs(**kwargs), ) authentication_providers_json = response.json() - authentication_providers_json.update({'account_id': self.id}) + authentication_providers_json.update({"account_id": self.id}) return AuthenticationProvider(self._requester, authentication_providers_json) @@ -106,8 +106,8 @@ def add_grading_standards(self, title, grading_scheme_entry, **kwargs): kwargs["grading_scheme_entry"] = grading_scheme_entry response = self._requester.request( - 'POST', - 'accounts/%s/grading_standards' % (self.id), + "POST", + "accounts/%s/grading_standards" % (self.id), title=title, _kwargs=combine_kwargs(**kwargs), ) @@ -135,8 +135,8 @@ def close_notification_for_user(self, user, notification): notif_id = obj_or_id(notification, "notification", (AccountNotification,)) response = self._requester.request( - 'DELETE', - 'accounts/{}/users/{}/account_notifications/{}'.format( + "DELETE", + "accounts/{}/users/{}/account_notifications/{}".format( self.id, user_id, notif_id ), ) @@ -152,8 +152,8 @@ def create_account(self, **kwargs): :rtype: :class:`canvasapi.account.Account` """ response = self._requester.request( - 'POST', - 'accounts/{}/root_accounts'.format(self.id), + "POST", + "accounts/{}/root_accounts".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Account(self._requester, response.json()) @@ -173,11 +173,11 @@ def create_admin(self, user, **kwargs): from canvasapi.user import User user_id = obj_or_id(user, "user", (User,)) - kwargs['user_id'] = user_id + kwargs["user_id"] = user_id response = self._requester.request( - 'POST', - 'accounts/{}/admins'.format(self.id), + "POST", + "accounts/{}/admins".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Admin(self._requester, response.json()) @@ -197,20 +197,20 @@ def create_content_migration(self, migration_type, **kwargs): from canvasapi.content_migration import ContentMigration, Migrator if isinstance(migration_type, Migrator): - kwargs['migration_type'] = migration_type.type + kwargs["migration_type"] = migration_type.type elif isinstance(migration_type, string_types): - kwargs['migration_type'] = migration_type + kwargs["migration_type"] = migration_type else: - raise TypeError('Parameter migration_type must be of type Migrator or str') + raise TypeError("Parameter migration_type must be of type Migrator or str") response = self._requester.request( - 'POST', - 'accounts/{}/content_migrations'.format(self.id), + "POST", + "accounts/{}/content_migrations".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'account_id': self.id}) + response_json.update({"account_id": self.id}) return ContentMigration(self._requester, response_json) @@ -226,8 +226,8 @@ def create_course(self, **kwargs): from canvasapi.course import Course response = self._requester.request( - 'POST', - 'accounts/{}/courses'.format(self.id), + "POST", + "accounts/{}/courses".format(self.id), account_id=self.id, _kwargs=combine_kwargs(**kwargs), ) @@ -245,12 +245,12 @@ def create_enrollment_term(self, **kwargs): from canvasapi.enrollment_term import EnrollmentTerm response = self._requester.request( - 'POST', - 'accounts/{}/terms'.format(self.id), + "POST", + "accounts/{}/terms".format(self.id), _kwargs=combine_kwargs(**kwargs), ) enrollment_term_json = response.json() - enrollment_term_json.update({'account_id': self.id}) + enrollment_term_json.update({"account_id": self.id}) return EnrollmentTerm(self._requester, enrollment_term_json) @@ -277,8 +277,8 @@ def create_external_tool( from canvasapi.external_tool import ExternalTool response = self._requester.request( - 'POST', - 'accounts/{}/external_tools'.format(self.id), + "POST", + "accounts/{}/external_tools".format(self.id), name=name, privacy_level=privacy_level, consumer_key=consumer_key, @@ -286,7 +286,7 @@ def create_external_tool( _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'account_id': self.id}) + response_json.update({"account_id": self.id}) return ExternalTool(self._requester, response_json) @@ -304,8 +304,8 @@ def create_group_category(self, name, **kwargs): from canvasapi.group import GroupCategory response = self._requester.request( - 'POST', - 'accounts/{}/group_categories'.format(self.id), + "POST", + "accounts/{}/group_categories".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) @@ -322,13 +322,13 @@ def create_notification(self, account_notification, **kwargs): :type account_notification: dict :rtype: :class:`canvasapi.account.AccountNotification` """ - required_key_list = ['subject', 'message', 'start_at', 'end_at'] + required_key_list = ["subject", "message", "start_at", "end_at"] required_keys_present = all( (x in account_notification for x in required_key_list) ) if isinstance(account_notification, dict) and required_keys_present: - kwargs['account_notification'] = account_notification + kwargs["account_notification"] = account_notification else: raise RequiredFieldMissing( ( @@ -338,8 +338,8 @@ def create_notification(self, account_notification, **kwargs): ) response = self._requester.request( - 'POST', - 'accounts/{}/account_notifications'.format(self.id), + "POST", + "accounts/{}/account_notifications".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return AccountNotification(self._requester, response.json()) @@ -356,8 +356,8 @@ def create_role(self, label, **kwargs): :rtype: :class:`canvasapi.account.Role` """ response = self._requester.request( - 'POST', - 'accounts/{}/roles'.format(self.id), + "POST", + "accounts/{}/roles".format(self.id), label=label, _kwargs=combine_kwargs(**kwargs), ) @@ -380,14 +380,14 @@ def create_sis_import(self, attachment, **kwargs): try: response = self._requester.request( - 'POST', - 'accounts/{}/sis_imports'.format(self.id), - file={'attachment': attachment}, + "POST", + "accounts/{}/sis_imports".format(self.id), + file={"attachment": attachment}, _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'account_id': self.id}) + response_json.update({"account_id": self.id}) return SisImport(self._requester, response_json) finally: @@ -406,14 +406,14 @@ def create_subaccount(self, account, **kwargs): :rtype: :class:`canvasapi.account.Account` """ - if isinstance(account, dict) and 'name' in account: - kwargs['account'] = account + if isinstance(account, dict) and "name" in account: + kwargs["account"] = account else: raise RequiredFieldMissing("Dictionary with key 'name' is required.") response = self._requester.request( - 'POST', - 'accounts/{}/sub_accounts'.format(self.id), + "POST", + "accounts/{}/sub_accounts".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Account(self._requester, response.json()) @@ -431,14 +431,14 @@ def create_user(self, pseudonym, **kwargs): """ from canvasapi.user import User - if isinstance(pseudonym, dict) and 'unique_id' in pseudonym: - kwargs['pseudonym'] = pseudonym + if isinstance(pseudonym, dict) and "unique_id" in pseudonym: + kwargs["pseudonym"] = pseudonym else: raise RequiredFieldMissing("Dictionary with key 'unique_id' is required.") response = self._requester.request( - 'POST', - 'accounts/{}/users'.format(self.id), + "POST", + "accounts/{}/users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return User(self._requester, response.json()) @@ -458,21 +458,21 @@ def create_user_login(self, user, login, **kwargs): """ from canvasapi.login import Login - if isinstance(user, dict) and 'id' in user: - kwargs['user'] = user + if isinstance(user, dict) and "id" in user: + kwargs["user"] = user else: raise RequiredFieldMissing(("user must be a dictionary with keys " "'id'.")) - if isinstance(login, dict) and 'unique_id' in login: - kwargs['login'] = login + if isinstance(login, dict) and "unique_id" in login: + kwargs["login"] = login else: raise RequiredFieldMissing( ("login must be a dictionary with keys " "'unique_id'.") ) response = self._requester.request( - 'POST', - 'accounts/{}/logins'.format(self.id), + "POST", + "accounts/{}/logins".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Login(self._requester, response.json()) @@ -492,8 +492,8 @@ def deactivate_role(self, role, **kwargs): role_id = obj_or_id(role, "role", (Role,)) response = self._requester.request( - 'DELETE', - 'accounts/{}/roles/{}'.format(self.id, role_id), + "DELETE", + "accounts/{}/roles/{}".format(self.id, role_id), _kwargs=combine_kwargs(**kwargs), ) return Role(self._requester, response.json()) @@ -511,15 +511,15 @@ def delete(self): :returns: True if successfully deleted; False otherwise. :rtype: bool """ - if not hasattr(self, 'parent_account_id') or not self.parent_account_id: + if not hasattr(self, "parent_account_id") or not self.parent_account_id: raise CanvasException("Cannot delete a root account.") response = self._requester.request( - 'DELETE', - 'accounts/{}/sub_accounts/{}'.format(self.parent_account_id, self.id), + "DELETE", + "accounts/{}/sub_accounts/{}".format(self.parent_account_id, self.id), ) - return response.json().get('workflow_state') == 'deleted' + return response.json().get("workflow_state") == "deleted" def delete_grading_period(self, grading_period): """ @@ -540,11 +540,11 @@ def delete_grading_period(self, grading_period): ) response = self._requester.request( - 'DELETE', - 'accounts/{}/grading_periods/{}'.format(self.id, grading_period_id), + "DELETE", + "accounts/{}/grading_periods/{}".format(self.id, grading_period_id), ) - return response.json().get('delete') + return response.json().get("delete") def delete_user(self, user): """ @@ -571,7 +571,7 @@ def delete_user(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'DELETE', 'accounts/{}/users/{}'.format(self.id, user_id) + "DELETE", "accounts/{}/users/{}".format(self.id, user_id) ) return User(self._requester, response.json()) @@ -588,8 +588,8 @@ def get_admins(self, **kwargs): return PaginatedList( Admin, self._requester, - 'GET', - 'accounts/{}/admins'.format(self.id), + "GET", + "accounts/{}/admins".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -609,8 +609,8 @@ def get_all_outcome_links_in_context(self): return PaginatedList( OutcomeLink, self._requester, - 'GET', - 'accounts/{}/outcome_group_links'.format(self.id), + "GET", + "accounts/{}/outcome_group_links".format(self.id), ) def get_authentication_provider(self, authentication_provider, **kwargs): @@ -635,8 +635,8 @@ def get_authentication_provider(self, authentication_provider, **kwargs): ) response = self._requester.request( - 'GET', - 'accounts/{}/authentication_providers/{}'.format( + "GET", + "accounts/{}/authentication_providers/{}".format( self.id, authentication_providers_id ), _kwargs=combine_kwargs(**kwargs), @@ -659,9 +659,9 @@ def get_authentication_providers(self, **kwargs): return PaginatedList( AuthenticationProvider, self._requester, - 'GET', - 'accounts/{}/authentication_providers'.format(self.id), - {'account_id': self.id}, + "GET", + "accounts/{}/authentication_providers".format(self.id), + {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -684,13 +684,13 @@ def get_content_migration(self, content_migration, **kwargs): ) response = self._requester.request( - 'GET', - 'accounts/{}/content_migrations/{}'.format(self.id, migration_id), + "GET", + "accounts/{}/content_migrations/{}".format(self.id, migration_id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'account_id': self.id}) + response_json.update({"account_id": self.id}) return ContentMigration(self._requester, response_json) @@ -709,9 +709,9 @@ def get_content_migrations(self, **kwargs): return PaginatedList( ContentMigration, self._requester, - 'GET', - 'accounts/{}/content_migrations'.format(self.id), - {'account_id': self.id}, + "GET", + "accounts/{}/content_migrations".format(self.id), + {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -730,8 +730,8 @@ def get_courses(self, **kwargs): return PaginatedList( Course, self._requester, - 'GET', - 'accounts/{}/courses'.format(self.id), + "GET", + "accounts/{}/courses".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -746,7 +746,7 @@ def get_department_level_grade_data_completed(self): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/completed/grades'.format(self.id) + "GET", "accounts/{}/analytics/completed/grades".format(self.id) ) return response.json() @@ -761,7 +761,7 @@ def get_department_level_grade_data_current(self): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/current/grades'.format(self.id) + "GET", "accounts/{}/analytics/current/grades".format(self.id) ) return response.json() @@ -779,7 +779,7 @@ def get_department_level_grade_data_with_given_term(self, term_id): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/terms/{}/grades'.format(self.id, term_id) + "GET", "accounts/{}/analytics/terms/{}/grades".format(self.id, term_id) ) return response.json() @@ -794,7 +794,7 @@ def get_department_level_participation_data_completed(self): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/completed/activity'.format(self.id) + "GET", "accounts/{}/analytics/completed/activity".format(self.id) ) return response.json() @@ -809,7 +809,7 @@ def get_department_level_participation_data_current(self): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/current/activity'.format(self.id) + "GET", "accounts/{}/analytics/current/activity".format(self.id) ) return response.json() @@ -827,7 +827,7 @@ def get_department_level_participation_data_with_given_term(self, term_id): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/terms/{}/activity'.format(self.id, term_id) + "GET", "accounts/{}/analytics/terms/{}/activity".format(self.id, term_id) ) return response.json() @@ -842,7 +842,7 @@ def get_department_level_statistics_completed(self): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/completed/statistics'.format(self.id) + "GET", "accounts/{}/analytics/completed/statistics".format(self.id) ) return response.json() @@ -857,7 +857,7 @@ def get_department_level_statistics_current(self): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/current/statistics'.format(self.id) + "GET", "accounts/{}/analytics/current/statistics".format(self.id) ) return response.json() @@ -875,7 +875,7 @@ def get_department_level_statistics_with_given_term(self, term_id): """ response = self._requester.request( - 'GET', 'accounts/{}/analytics/terms/{}/statistics'.format(self.id, term_id) + "GET", "accounts/{}/analytics/terms/{}/statistics".format(self.id, term_id) ) return response.json() @@ -896,8 +896,8 @@ def get_enrollment(self, enrollment, **kwargs): enrollment_id = obj_or_id(enrollment, "enrollment", (Enrollment,)) response = self._requester.request( - 'GET', - 'accounts/{}/enrollments/{}'.format(self.id, enrollment_id), + "GET", + "accounts/{}/enrollments/{}".format(self.id, enrollment_id), _kwargs=combine_kwargs(**kwargs), ) return Enrollment(self._requester, response.json()) @@ -917,10 +917,10 @@ def get_enrollment_terms(self, **kwargs): return PaginatedList( EnrollmentTerm, self._requester, - 'GET', - 'accounts/{}/terms'.format(self.id), - {'account_id': self.id}, - _root='enrollment_terms', + "GET", + "accounts/{}/terms".format(self.id), + {"account_id": self.id}, + _root="enrollment_terms", _kwargs=combine_kwargs(**kwargs), ) @@ -939,10 +939,10 @@ def get_external_tool(self, tool): tool_id = obj_or_id(tool, "tool", (ExternalTool,)) response = self._requester.request( - 'GET', 'accounts/{}/external_tools/{}'.format(self.id, tool_id) + "GET", "accounts/{}/external_tools/{}".format(self.id, tool_id) ) tool_json = response.json() - tool_json.update({'account_id': self.id}) + tool_json.update({"account_id": self.id}) return ExternalTool(self._requester, tool_json) @@ -959,9 +959,9 @@ def get_external_tools(self, **kwargs): return PaginatedList( ExternalTool, self._requester, - 'GET', - 'accounts/{}/external_tools'.format(self.id), - {'account_id': self.id}, + "GET", + "accounts/{}/external_tools".format(self.id), + {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -979,9 +979,9 @@ def get_grading_periods(self, **kwargs): return PaginatedList( GradingPeriod, self._requester, - 'GET', - 'accounts/{}/grading_periods'.format(self.id), - {'account_id': self.id}, + "GET", + "accounts/{}/grading_periods".format(self.id), + {"account_id": self.id}, _root="grading_periods", kwargs=combine_kwargs(**kwargs), ) @@ -1000,8 +1000,8 @@ def get_grading_standards(self, **kwargs): return PaginatedList( GradingStandard, self._requester, - 'GET', - 'accounts/%s/grading_standards' % (self.id), + "GET", + "accounts/%s/grading_standards" % (self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1020,8 +1020,8 @@ def get_group_categories(self, **kwargs): return PaginatedList( GroupCategory, self._requester, - 'GET', - 'accounts/{}/group_categories'.format(self.id), + "GET", + "accounts/{}/group_categories".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1039,8 +1039,8 @@ def get_groups(self, **kwargs): return PaginatedList( Group, self._requester, - 'GET', - 'accounts/{}/groups'.format(self.id), + "GET", + "accounts/{}/groups".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1059,8 +1059,8 @@ def get_index_of_reports(self, report_type): return PaginatedList( AccountReport, self._requester, - 'GET', - 'accounts/{}/reports/{}'.format(self.id, report_type), + "GET", + "accounts/{}/reports/{}".format(self.id, report_type), ) def get_migration_systems(self, **kwargs): @@ -1078,9 +1078,9 @@ def get_migration_systems(self, **kwargs): return PaginatedList( Migrator, self._requester, - 'GET', - 'accounts/{}/content_migrations/migrators'.format(self.id), - {'account_id': self.id}, + "GET", + "accounts/{}/content_migrations/migrators".format(self.id), + {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1101,7 +1101,7 @@ def get_outcome_group(self, group): outcome_group_id = obj_or_id(group, "outcome group", (OutcomeGroup,)) response = self._requester.request( - 'GET', 'accounts/{}/outcome_groups/{}'.format(self.id, outcome_group_id) + "GET", "accounts/{}/outcome_groups/{}".format(self.id, outcome_group_id) ) return OutcomeGroup(self._requester, response.json()) @@ -1122,8 +1122,8 @@ def get_outcome_groups_in_context(self): return PaginatedList( OutcomeGroup, self._requester, - 'GET', - 'accounts/{}/outcome_groups'.format(self.id), + "GET", + "accounts/{}/outcome_groups".format(self.id), ) def get_outcome_import_status(self, outcome_import, **kwargs): @@ -1169,7 +1169,7 @@ def get_reports(self): :class:`canvasapi.account.AccountReport` """ return PaginatedList( - AccountReport, self._requester, 'GET', 'accounts/{}/reports'.format(self.id) + AccountReport, self._requester, "GET", "accounts/{}/reports".format(self.id) ) def get_role(self, role): @@ -1187,7 +1187,7 @@ def get_role(self, role): role_id = obj_or_id(role, "role", (Role,)) response = self._requester.request( - 'GET', 'accounts/{}/roles/{}'.format(self.id, role_id) + "GET", "accounts/{}/roles/{}".format(self.id, role_id) ) return Role(self._requester, response.json()) @@ -1205,8 +1205,8 @@ def get_roles(self, **kwargs): return PaginatedList( Role, self._requester, - 'GET', - 'accounts/{}/roles'.format(self.id), + "GET", + "accounts/{}/roles".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1223,7 +1223,7 @@ def get_root_outcome_group(self): from canvasapi.outcome import OutcomeGroup response = self._requester.request( - 'GET', 'accounts/{}/root_outcome_group'.format(self.id) + "GET", "accounts/{}/root_outcome_group".format(self.id) ) return OutcomeGroup(self._requester, response.json()) @@ -1239,8 +1239,8 @@ def get_rubric(self, rubric_id, **kwargs): :rtype: :class:`canvasapi.rubric.Rubric` """ response = self._requester.request( - 'GET', - 'accounts/%s/rubrics/%s' % (self.id, rubric_id), + "GET", + "accounts/%s/rubrics/%s" % (self.id, rubric_id), _kwargs=combine_kwargs(**kwargs), ) @@ -1259,8 +1259,8 @@ def get_rubrics(self, **kwargs): return PaginatedList( Rubric, self._requester, - 'GET', - 'accounts/%s/rubrics' % (self.id), + "GET", + "accounts/%s/rubrics" % (self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1278,7 +1278,7 @@ def get_single_grading_standard(self, grading_standard_id, **kwargs): response = self._requester.request( "GET", - 'accounts/%s/grading_standards/%d' % (self.id, grading_standard_id), + "accounts/%s/grading_standards/%d" % (self.id, grading_standard_id), _kwargs=combine_kwargs(**kwargs), ) return GradingStandard(self._requester, response.json()) @@ -1298,13 +1298,13 @@ def get_sis_import(self, sis_import, **kwargs): sis_import_id = obj_or_id(sis_import, "sis_import", (SisImport,)) response = self._requester.request( - 'GET', - 'accounts/{}/sis_imports/{}'.format(self.id, sis_import_id), + "GET", + "accounts/{}/sis_imports/{}".format(self.id, sis_import_id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'account_id': self.id}) + response_json.update({"account_id": self.id}) return SisImport(self._requester, response_json) @@ -1322,10 +1322,10 @@ def get_sis_imports(self, **kwargs): return PaginatedList( SisImport, self._requester, - 'GET', - 'accounts/{}/sis_imports'.format(self.id), - {'account_id': self.id}, - _root='sis_imports', + "GET", + "accounts/{}/sis_imports".format(self.id), + {"account_id": self.id}, + _root="sis_imports", _kwargs=combine_kwargs(**kwargs), ) @@ -1343,10 +1343,10 @@ def get_sis_imports_running(self, **kwargs): return PaginatedList( SisImport, self._requester, - 'GET', - 'accounts/{}/sis_imports/importing'.format(self.id), - {'account_id': self.id}, - _root='sis_imports', + "GET", + "accounts/{}/sis_imports/importing".format(self.id), + {"account_id": self.id}, + _root="sis_imports", _kwargs=combine_kwargs(**kwargs), ) @@ -1366,8 +1366,8 @@ def get_subaccounts(self, recursive=False): return PaginatedList( Account, self._requester, - 'GET', - 'accounts/{}/sub_accounts'.format(self.id), + "GET", + "accounts/{}/sub_accounts".format(self.id), recursive=recursive, ) @@ -1386,8 +1386,8 @@ def get_user_logins(self, **kwargs): return PaginatedList( Login, self._requester, - 'GET', - 'accounts/{}/logins'.format(self.id), + "GET", + "accounts/{}/logins".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1413,8 +1413,8 @@ def get_user_notifications(self, user): return PaginatedList( AccountNotification, self._requester, - 'GET', - 'accounts/{}/users/{}/account_notifications'.format(self.id, user_id), + "GET", + "accounts/{}/users/{}/account_notifications".format(self.id, user_id), ) def get_users(self, **kwargs): @@ -1431,8 +1431,8 @@ def get_users(self, **kwargs): return PaginatedList( User, self._requester, - 'GET', - 'accounts/{}/users'.format(self.id), + "GET", + "accounts/{}/users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1632,8 +1632,8 @@ def show_account_auth_settings(self, **kwargs): """ response = self._requester.request( - 'GET', - 'accounts/{}/sso_settings'.format(self.id), + "GET", + "accounts/{}/sso_settings".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1650,10 +1650,10 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', 'accounts/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "accounts/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - if 'name' in response.json(): + if "name" in response.json(): super(Account, self).set_attributes(response.json()) return True else: @@ -1670,8 +1670,8 @@ def update_account_auth_settings(self, **kwargs): """ response = self._requester.request( - 'PUT', - 'accounts/{}/sso_settings'.format(self.id), + "PUT", + "accounts/{}/sso_settings".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1692,8 +1692,8 @@ def update_role(self, role, **kwargs): role_id = obj_or_id(role, "role", (Role,)) response = self._requester.request( - 'PUT', - 'accounts/{}/roles/{}'.format(self.id, role_id), + "PUT", + "accounts/{}/roles/{}".format(self.id, role_id), _kwargs=combine_kwargs(**kwargs), ) return Role(self._requester, response.json()) @@ -1726,4 +1726,4 @@ def __str__(self): # pragma: no cover @python_2_unicode_compatible class Admin(CanvasObject): def __str__(self): # pragma: no cover - return "{} {} ({})".format(self.user['name'], self.user['id'], self.id) + return "{} {} ({})".format(self.user["name"], self.user["id"], self.id) diff --git a/canvasapi/appointment_group.py b/canvasapi/appointment_group.py index f12194db..4a666da8 100644 --- a/canvasapi/appointment_group.py +++ b/canvasapi/appointment_group.py @@ -22,8 +22,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.appointment_group.AppointmentGroup` """ response = self._requester.request( - 'DELETE', - 'appointment_groups/{}'.format(self.id), + "DELETE", + "appointment_groups/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return AppointmentGroup(self._requester, response.json()) @@ -40,20 +40,20 @@ def edit(self, appointment_group, **kwargs): :rtype: :class:`canvasapi.appointment_group.AppointmentGroup` """ - if isinstance(appointment_group, dict) and 'context_codes' in appointment_group: - kwargs['appointment_group'] = appointment_group + if isinstance(appointment_group, dict) and "context_codes" in appointment_group: + kwargs["appointment_group"] = appointment_group else: raise RequiredFieldMissing( "Dictionary with key 'context_codes' is required." ) response = self._requester.request( - 'PUT', - 'appointment_groups/{}'.format(self.id), + "PUT", + "appointment_groups/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - if 'title' in response.json(): + if "title" in response.json(): super(AppointmentGroup, self).set_attributes(response.json()) return AppointmentGroup(self._requester, response.json()) diff --git a/canvasapi/assignment.py b/canvasapi/assignment.py index 732ce3a4..cd549ca0 100644 --- a/canvasapi/assignment.py +++ b/canvasapi/assignment.py @@ -29,8 +29,8 @@ def create_override(self, **kwargs): :rtype: :class:`canvasapi.assignment.AssignmentOverride` """ response = self._requester.request( - 'POST', - 'courses/{}/assignments/{}/overrides'.format(self.course_id, self.id), + "POST", + "courses/{}/assignments/{}/overrides".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -47,8 +47,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.assignment.Assignment` """ response = self._requester.request( - 'DELETE', - 'courses/{}/assignments/{}'.format(self.course_id, self.id), + "DELETE", + "courses/{}/assignments/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return Assignment(self._requester, response.json()) @@ -63,12 +63,12 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.assignment.Assignment` """ response = self._requester.request( - 'PUT', - 'courses/{}/assignments/{}'.format(self.course_id, self.id), + "PUT", + "courses/{}/assignments/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - if 'name' in response.json(): + if "name" in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json()) @@ -86,11 +86,11 @@ def get_gradeable_students(self, **kwargs): return PaginatedList( UserDisplay, self._requester, - 'GET', - 'courses/{}/assignments/{}/gradeable_students'.format( + "GET", + "courses/{}/assignments/{}/gradeable_students".format( self.course_id, self.id ), - {'course_id': self.course_id}, + {"course_id": self.course_id}, _kwargs=combine_kwargs(**kwargs), ) @@ -109,8 +109,8 @@ def get_override(self, override, **kwargs): override_id = obj_or_id(override, "override", (AssignmentOverride,)) response = self._requester.request( - 'GET', - 'courses/{}/assignments/{}/overrides/{}'.format( + "GET", + "courses/{}/assignments/{}/overrides/{}".format( self.course_id, self.id, override_id ), _kwargs=combine_kwargs(**kwargs), @@ -133,9 +133,9 @@ def get_overrides(self, **kwargs): return PaginatedList( AssignmentOverride, self._requester, - 'GET', - 'courses/{}/assignments/{}/overrides'.format(self.course_id, self.id), - {'course_id': self.course_id}, + "GET", + "courses/{}/assignments/{}/overrides".format(self.course_id, self.id), + {"course_id": self.course_id}, _kwargs=combine_kwargs(**kwargs), ) @@ -152,8 +152,8 @@ def get_peer_reviews(self, **kwargs): return PaginatedList( PeerReview, self._requester, - 'GET', - 'courses/{}/assignments/{}/peer_reviews'.format(self.course_id, self.id), + "GET", + "courses/{}/assignments/{}/peer_reviews".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -172,8 +172,8 @@ def get_submission(self, user, **kwargs): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', - 'courses/{}/assignments/{}/submissions/{}'.format( + "GET", + "courses/{}/assignments/{}/submissions/{}".format( self.course_id, self.id, user_id ), _kwargs=combine_kwargs(**kwargs), @@ -196,9 +196,9 @@ def get_submissions(self, **kwargs): return PaginatedList( Submission, self._requester, - 'GET', - 'courses/{}/assignments/{}/submissions'.format(self.course_id, self.id), - {'course_id': self.course_id}, + "GET", + "courses/{}/assignments/{}/submissions".format(self.course_id, self.id), + {"course_id": self.course_id}, _kwargs=combine_kwargs(**kwargs), ) @@ -217,28 +217,28 @@ def submit(self, submission, file=None, **kwargs): :rtype: :class:`canvasapi.submission.Submission` """ - if isinstance(submission, dict) and 'submission_type' in submission: - kwargs['submission'] = submission + if isinstance(submission, dict) and "submission_type" in submission: + kwargs["submission"] = submission else: raise RequiredFieldMissing( "Dictionary with key 'submission_type' is required." ) if file: - if submission.get('submission_type') != 'online_upload': + if submission.get("submission_type") != "online_upload": raise ValueError( "To upload a file, `submission['submission_type']` must be `online_upload`." ) upload_response = self.upload_to_submission(file, **kwargs) if upload_response[0]: - kwargs['submission']['file_ids'] = [upload_response[1]['id']] + kwargs["submission"]["file_ids"] = [upload_response[1]["id"]] else: - raise CanvasException('File upload failed. Not submitting.') + raise CanvasException("File upload failed. Not submitting.") response = self._requester.request( - 'POST', - 'courses/{}/assignments/{}/submissions'.format(self.course_id, self.id), + "POST", + "courses/{}/assignments/{}/submissions".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() @@ -258,15 +258,15 @@ def submissions_bulk_update(self, **kwargs): :rtype: :class:`canvasapi.progress.Progress` """ response = self._requester.request( - 'POST', - 'courses/{}/assignments/{}/submissions/update_grades'.format( + "POST", + "courses/{}/assignments/{}/submissions/update_grades".format( self.course_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) - def upload_to_submission(self, file, user='self', **kwargs): + def upload_to_submission(self, file, user="self", **kwargs): """ Upload a file to a submission. @@ -288,7 +288,7 @@ def upload_to_submission(self, file, user='self', **kwargs): return Uploader( self._requester, - 'courses/{}/assignments/{}/submissions/{}/files'.format( + "courses/{}/assignments/{}/submissions/{}/files".format( self.course_id, self.id, user_id ), file, @@ -311,12 +311,12 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.assignment.AssignmentGroup` """ response = self._requester.request( - 'PUT', - 'courses/{}/assignment_groups/{}'.format(self.course_id, self.id), + "PUT", + "courses/{}/assignment_groups/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - if 'name' in response.json(): + if "name" in response.json(): super(AssignmentGroup, self).set_attributes(response.json()) return AssignmentGroup(self._requester, response.json()) @@ -331,8 +331,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.assignment.AssignmentGroup` """ response = self._requester.request( - 'DELETE', - 'courses/{}/assignment_groups/{}'.format(self.course_id, self.id), + "DELETE", + "courses/{}/assignment_groups/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return AssignmentGroup(self._requester, response.json()) @@ -354,8 +354,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.assignment.AssignmentGroup` """ response = self._requester.request( - 'DELETE', - 'courses/{}/assignments/{}/overrides/{}'.format( + "DELETE", + "courses/{}/assignments/{}/overrides/{}".format( self.course_id, self.assignment_id, self.id ), ) @@ -377,15 +377,15 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.assignment.AssignmentOverride` """ response = self._requester.request( - 'PUT', - 'courses/{}/assignments/{}/overrides/{}'.format( + "PUT", + "courses/{}/assignments/{}/overrides/{}".format( self.course_id, self.assignment_id, self.id ), ) response_json = response.json() response_json.update(course_id=self.course_id) - if 'title' in response_json: + if "title" in response_json: super(AssignmentOverride, self).set_attributes(response_json) return self diff --git a/canvasapi/authentication_provider.py b/canvasapi/authentication_provider.py index 0e6253aa..685240f3 100644 --- a/canvasapi/authentication_provider.py +++ b/canvasapi/authentication_provider.py @@ -21,15 +21,15 @@ def update(self, **kwargs): :rtype: :class:`canvasapi.authentication_provider.AuthenticationProvider` """ response = self._requester.request( - 'PUT', - 'accounts/{}/authentication_providers/{}'.format(self.account_id, self.id), + "PUT", + "accounts/{}/authentication_providers/{}".format(self.account_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - if response.json().get('auth_type'): + if response.json().get("auth_type"): super(AuthenticationProvider, self).set_attributes(response.json()) - return response.json().get('auth_type') + return response.json().get("auth_type") def delete(self): """ @@ -41,7 +41,7 @@ def delete(self): :rtype: :class:`canvasapi.authentication_provider.AuthenticationProvider` """ response = self._requester.request( - 'DELETE', - 'accounts/{}/authentication_providers/{}'.format(self.account_id, self.id), + "DELETE", + "accounts/{}/authentication_providers/{}".format(self.account_id, self.id), ) return AuthenticationProvider(self._requester, response.json()) diff --git a/canvasapi/blueprint.py b/canvasapi/blueprint.py index 13dff0e9..ad40862e 100644 --- a/canvasapi/blueprint.py +++ b/canvasapi/blueprint.py @@ -23,14 +23,14 @@ def associated_course_migration(self, **kwargs): :rtype: :class:`canvasapi.blueprint.BlueprintMigration` """ response = self._requester.request( - 'POST', - 'courses/{}/blueprint_templates/{}/migrations'.format( + "POST", + "courses/{}/blueprint_templates/{}/migrations".format( self.course_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return BlueprintMigration(self._requester, response_json) def change_blueprint_restrictions( @@ -58,8 +58,8 @@ def change_blueprint_restrictions( kwargs["restricted"] = restricted response = self._requester.request( - 'PUT', - 'courses/{}/blueprint_templates/{}/restrict_item'.format( + "PUT", + "courses/{}/blueprint_templates/{}/restrict_item".format( self.course_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -82,8 +82,8 @@ def get_associated_courses(self, **kwargs): return PaginatedList( Course, self._requester, - 'GET', - 'courses/{}/blueprint_templates/{}/associated_courses'.format( + "GET", + "courses/{}/blueprint_templates/{}/associated_courses".format( self.course_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -104,8 +104,8 @@ def get_unsynced_changes(self, **kwargs): return PaginatedList( ChangeRecord, self._requester, - 'GET', - 'courses/{}/blueprint_templates/{}/unsynced_changes'.format( + "GET", + "courses/{}/blueprint_templates/{}/unsynced_changes".format( self.course_id, self.id ), kwargs=combine_kwargs(**kwargs), @@ -126,11 +126,11 @@ def list_blueprint_migrations(self, **kwargs): return PaginatedList( BlueprintMigration, self._requester, - 'GET', - 'courses/{}/blueprint_templates/{}/migrations'.format( + "GET", + "courses/{}/blueprint_templates/{}/migrations".format( self.course_id, self.id ), - {'course_id': self.course_id}, + {"course_id": self.course_id}, kwargs=combine_kwargs(**kwargs), ) @@ -149,16 +149,16 @@ def show_blueprint_migration(self, migration, **kwargs): :rtype: :class:`canvasapi.blueprint.BlueprintMigration` """ - migration_id = obj_or_id(migration, 'migration', (BlueprintMigration,)) + migration_id = obj_or_id(migration, "migration", (BlueprintMigration,)) response = self._requester.request( - 'GET', - 'courses/{}/blueprint_templates/{}/migrations/{}'.format( + "GET", + "courses/{}/blueprint_templates/{}/migrations/{}".format( self.course_id, self.id, migration_id ), kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return BlueprintMigration(self._requester, response_json) def update_associated_courses(self, **kwargs): @@ -173,8 +173,8 @@ def update_associated_courses(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - 'courses/{}/blueprint_templates/{}/update_associations'.format( + "PUT", + "courses/{}/blueprint_templates/{}/update_associations".format( self.course_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -203,8 +203,8 @@ def get_details(self, **kwargs): return PaginatedList( ChangeRecord, self._requester, - 'GET', - 'courses/{}/blueprint_templates/{}/migrations/{}/details'.format( + "GET", + "courses/{}/blueprint_templates/{}/migrations/{}/details".format( self.course_id, self.template_id, self.id ), kwargs=combine_kwargs(**kwargs), @@ -226,8 +226,8 @@ def get_import_details(self, **kwargs): return PaginatedList( ChangeRecord, self._requester, - 'GET', - 'courses/{}/blueprint_subscriptions/{}/migrations/{}/details'.format( + "GET", + "courses/{}/blueprint_subscriptions/{}/migrations/{}/details".format( self.course_id, self.subscription_id, self.id ), kwargs=combine_kwargs(**kwargs), @@ -261,11 +261,11 @@ def list_blueprint_imports(self, **kwargs): return PaginatedList( BlueprintMigration, self._requester, - 'GET', - 'courses/{}/blueprint_subscriptions/{}/migrations'.format( + "GET", + "courses/{}/blueprint_subscriptions/{}/migrations".format( self.course_id, self.id ), - {'course_id': self.id}, + {"course_id": self.id}, kwargs=combine_kwargs(**kwargs), ) @@ -284,14 +284,14 @@ def show_blueprint_import(self, migration, **kwargs): :rtype: :class:`canvasapi.blueprint.BlueprintMigration` """ - migration_id = obj_or_id(migration, 'migration', (BlueprintMigration,)) + migration_id = obj_or_id(migration, "migration", (BlueprintMigration,)) response = self._requester.request( - 'GET', - 'courses/{}/blueprint_subscriptions/{}/migrations/{}'.format( + "GET", + "courses/{}/blueprint_subscriptions/{}/migrations/{}".format( self.course_id, self.id, migration_id ), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return BlueprintMigration(self._requester, response_json) diff --git a/canvasapi/bookmark.py b/canvasapi/bookmark.py index 2e046626..bc489758 100644 --- a/canvasapi/bookmark.py +++ b/canvasapi/bookmark.py @@ -21,7 +21,7 @@ def delete(self): :rtype: :class:`canvasapi.bookmark.Bookmark` """ response = self._requester.request( - 'DELETE', 'users/self/bookmarks/{}'.format(self.id) + "DELETE", "users/self/bookmarks/{}".format(self.id) ) return Bookmark(self._requester, response.json()) @@ -35,12 +35,12 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.bookmark.Bookmark` """ response = self._requester.request( - 'PUT', - 'users/self/bookmarks/{}'.format(self.id), + "PUT", + "users/self/bookmarks/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - if 'name' in response.json() and 'url' in response.json(): + if "name" in response.json() and "url" in response.json(): super(Bookmark, self).set_attributes(response.json()) return Bookmark(self._requester, response.json()) diff --git a/canvasapi/calendar_event.py b/canvasapi/calendar_event.py index 18db5b1e..15ce44b1 100644 --- a/canvasapi/calendar_event.py +++ b/canvasapi/calendar_event.py @@ -18,8 +18,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ response = self._requester.request( - 'DELETE', - 'calendar_events/{}'.format(self.id), + "DELETE", + "calendar_events/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return CalendarEvent(self._requester, response.json()) @@ -34,12 +34,12 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ response = self._requester.request( - 'PUT', - 'calendar_events/{}'.format(self.id), + "PUT", + "calendar_events/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - if 'title' in response.json(): + if "title" in response.json(): super(CalendarEvent, self).set_attributes(response.json()) return CalendarEvent(self._requester, response.json()) diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py index 0037da22..e912ad80 100644 --- a/canvasapi/canvas.py +++ b/canvasapi/canvas.py @@ -17,7 +17,7 @@ from canvasapi.util import combine_kwargs, get_institution_url, obj_or_id -warnings.simplefilter('always', DeprecationWarning) +warnings.simplefilter("always", DeprecationWarning) class Canvas(object): @@ -34,14 +34,14 @@ def __init__(self, base_url, access_token): """ new_url = get_institution_url(base_url) - if 'api/v1' in base_url: + if "api/v1" in base_url: warnings.warn( "`base_url` no longer requires an API version be specified. " "Rewriting `base_url` to {}".format(new_url), DeprecationWarning, ) - if 'http://' in base_url: + if "http://" in base_url: warnings.warn( "Canvas may respond unexpectedly when making requests to HTTP " "URLs. If possible, please use HTTPS.", @@ -54,14 +54,14 @@ def __init__(self, base_url, access_token): UserWarning, ) - if '://' not in base_url: + if "://" not in base_url: warnings.warn( "An invalid `base_url` for the Canvas API Instance was used. " "Please provide a valid HTTP or HTTPS URL if possible.", UserWarning, ) - base_url = new_url + '/api/v1/' + base_url = new_url + "/api/v1/" self.__requester = Requester(base_url, access_token) @@ -75,7 +75,7 @@ def create_account(self, **kwargs): :rtype: :class:`canvasapi.account.Account` """ response = self.__requester.request( - 'POST', 'accounts', _kwargs=combine_kwargs(**kwargs) + "POST", "accounts", _kwargs=combine_kwargs(**kwargs) ) return Account(self.__requester, response.json()) @@ -96,13 +96,13 @@ def get_account(self, account, use_sis_id=False, **kwargs): """ if use_sis_id: account_id = account - uri_str = 'accounts/sis_account_id:{}' + uri_str = "accounts/sis_account_id:{}" else: account_id = obj_or_id(account, "account", (Account,)) - uri_str = 'accounts/{}' + uri_str = "accounts/{}" response = self.__requester.request( - 'GET', uri_str.format(account_id), _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(account_id), _kwargs=combine_kwargs(**kwargs) ) return Account(self.__requester, response.json()) @@ -123,8 +123,8 @@ def get_accounts(self, **kwargs): return PaginatedList( Account, self.__requester, - 'GET', - 'accounts', + "GET", + "accounts", _kwargs=combine_kwargs(**kwargs), ) @@ -142,7 +142,7 @@ def get_course_accounts(self): :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.account.Account` """ - return PaginatedList(Account, self.__requester, 'GET', 'course_accounts') + return PaginatedList(Account, self.__requester, "GET", "course_accounts") def get_course(self, course, use_sis_id=False, **kwargs): """ @@ -161,13 +161,13 @@ def get_course(self, course, use_sis_id=False, **kwargs): """ if use_sis_id: course_id = course - uri_str = 'courses/sis_course_id:{}' + uri_str = "courses/sis_course_id:{}" else: course_id = obj_or_id(course, "course", (Course,)) - uri_str = 'courses/{}' + uri_str = "courses/{}" response = self.__requester.request( - 'GET', uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) ) return Course(self.__requester, response.json()) @@ -191,14 +191,14 @@ def get_user(self, user, id_type=None): :rtype: :class:`canvasapi.user.User` """ if id_type: - uri = 'users/{}:{}'.format(id_type, user) - elif user == 'self': - uri = 'users/self' + uri = "users/{}:{}".format(id_type, user) + elif user == "self": + uri = "users/self" else: user_id = obj_or_id(user, "user", (User,)) - uri = 'users/{}'.format(user_id) + uri = "users/{}".format(user_id) - response = self.__requester.request('GET', uri) + response = self.__requester.request("GET", uri) return User(self.__requester, response.json()) def get_current_user(self): @@ -215,7 +215,7 @@ def get_courses(self, **kwargs): :class:`canvasapi.course.Course` """ return PaginatedList( - Course, self.__requester, 'GET', 'courses', _kwargs=combine_kwargs(**kwargs) + Course, self.__requester, "GET", "courses", _kwargs=combine_kwargs(**kwargs) ) def get_activity_stream_summary(self): @@ -227,7 +227,7 @@ def get_activity_stream_summary(self): :rtype: dict """ - response = self.__requester.request('GET', 'users/self/activity_stream/summary') + response = self.__requester.request("GET", "users/self/activity_stream/summary") return response.json() def get_todo_items(self): @@ -239,7 +239,7 @@ def get_todo_items(self): :rtype: dict """ - response = self.__requester.request('GET', 'users/self/todo') + response = self.__requester.request("GET", "users/self/todo") return response.json() def get_upcoming_events(self): @@ -252,7 +252,7 @@ def get_upcoming_events(self): :rtype: dict """ - response = self.__requester.request('GET', 'users/self/upcoming_events') + response = self.__requester.request("GET", "users/self/upcoming_events") return response.json() def get_course_nicknames(self): @@ -268,7 +268,7 @@ def get_course_nicknames(self): from canvasapi.course import CourseNickname return PaginatedList( - CourseNickname, self.__requester, 'GET', 'users/self/course_nicknames' + CourseNickname, self.__requester, "GET", "users/self/course_nicknames" ) def get_course_nickname(self, course): @@ -288,7 +288,7 @@ def get_course_nickname(self, course): course_id = obj_or_id(course, "course", (Course,)) response = self.__requester.request( - 'GET', 'users/self/course_nicknames/{}'.format(course_id) + "GET", "users/self/course_nicknames/{}".format(course_id) ) return CourseNickname(self.__requester, response.json()) @@ -309,13 +309,13 @@ def get_section(self, section, use_sis_id=False, **kwargs): """ if use_sis_id: section_id = section - uri_str = 'sections/sis_section_id:{}' + uri_str = "sections/sis_section_id:{}" else: section_id = obj_or_id(section, "section", (Section,)) - uri_str = 'sections/{}' + uri_str = "sections/{}" response = self.__requester.request( - 'GET', uri_str.format(section_id), _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(section_id), _kwargs=combine_kwargs(**kwargs) ) return Section(self.__requester, response.json()) @@ -340,7 +340,7 @@ def set_course_nickname(self, course, nickname): course_id = obj_or_id(course, "course", (Course,)) response = self.__requester.request( - 'PUT', 'users/self/course_nicknames/{}'.format(course_id), nickname=nickname + "PUT", "users/self/course_nicknames/{}".format(course_id), nickname=nickname ) return CourseNickname(self.__requester, response.json()) @@ -356,8 +356,8 @@ def clear_course_nicknames(self): :rtype: bool """ - response = self.__requester.request('DELETE', 'users/self/course_nicknames') - return response.json().get('message') == 'OK' + response = self.__requester.request("DELETE", "users/self/course_nicknames") + return response.json().get("message") == "OK" def search_accounts(self, **kwargs): """ @@ -370,7 +370,7 @@ def search_accounts(self, **kwargs): :rtype: dict """ response = self.__requester.request( - 'GET', 'accounts/search', _kwargs=combine_kwargs(**kwargs) + "GET", "accounts/search", _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -384,7 +384,7 @@ def create_group(self, **kwargs): :rtype: :class:`canvasapi.group.Group` """ response = self.__requester.request( - 'POST', 'groups', _kwargs=combine_kwargs(**kwargs) + "POST", "groups", _kwargs=combine_kwargs(**kwargs) ) return Group(self.__requester, response.json()) @@ -408,13 +408,13 @@ def get_group(self, group, use_sis_id=False, **kwargs): if use_sis_id: group_id = group - uri_str = 'groups/sis_group_id:{}' + uri_str = "groups/sis_group_id:{}" else: group_id = obj_or_id(group, "group", (Group,)) - uri_str = 'groups/{}' + uri_str = "groups/{}" response = self.__requester.request( - 'GET', uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) ) return Group(self.__requester, response.json()) @@ -433,7 +433,7 @@ def get_group_category(self, category): category_id = obj_or_id(category, "category", (GroupCategory,)) response = self.__requester.request( - 'GET', 'group_categories/{}'.format(category_id) + "GET", "group_categories/{}".format(category_id) ) return GroupCategory(self.__requester, response.json()) @@ -455,11 +455,11 @@ def create_conversation(self, recipients, body, **kwargs): """ from canvasapi.conversation import Conversation - kwargs['recipients'] = recipients - kwargs['body'] = body + kwargs["recipients"] = recipients + kwargs["body"] = body response = self.__requester.request( - 'POST', 'conversations', _kwargs=combine_kwargs(**kwargs) + "POST", "conversations", _kwargs=combine_kwargs(**kwargs) ) return [Conversation(self.__requester, convo) for convo in response.json()] @@ -480,8 +480,8 @@ def get_conversation(self, conversation, **kwargs): conversation_id = obj_or_id(conversation, "conversation", (Conversation,)) response = self.__requester.request( - 'GET', - 'conversations/{}'.format(conversation_id), + "GET", + "conversations/{}".format(conversation_id), _kwargs=combine_kwargs(**kwargs), ) return Conversation(self.__requester, response.json()) @@ -501,8 +501,8 @@ def get_conversations(self, **kwargs): return PaginatedList( Conversation, self.__requester, - 'GET', - 'conversations', + "GET", + "conversations", _kwargs=combine_kwargs(**kwargs), ) @@ -515,7 +515,7 @@ def conversations_mark_all_as_read(self): :rtype: `bool` """ - response = self.__requester.request('POST', 'conversations/mark_all_as_read') + response = self.__requester.request("POST", "conversations/mark_all_as_read") return response.json() == {} def conversations_unread_count(self): @@ -528,7 +528,7 @@ def conversations_unread_count(self): :returns: simple object with unread_count, example: {'unread_count': '7'} :rtype: `dict` """ - response = self.__requester.request('GET', 'conversations/unread_count') + response = self.__requester.request("GET", "conversations/unread_count") return response.json() @@ -545,7 +545,7 @@ def conversations_get_running_batches(self): :rtype: `dict` """ - response = self.__requester.request('GET', 'conversations/batches') + response = self.__requester.request("GET", "conversations/batches") return response.json() @@ -565,32 +565,32 @@ def conversations_batch_update(self, conversation_ids, event): from canvasapi.progress import Progress ALLOWED_EVENTS = [ - 'mark_as_read', - 'mark_as_unread', - 'star', - 'unstar', - 'archive', - 'destroy', + "mark_as_read", + "mark_as_unread", + "star", + "unstar", + "archive", + "destroy", ] try: if event not in ALLOWED_EVENTS: raise ValueError( - '{} is not a valid action. Please use one of the following: {}'.format( - event, ','.join(ALLOWED_EVENTS) + "{} is not a valid action. Please use one of the following: {}".format( + event, ",".join(ALLOWED_EVENTS) ) ) if len(conversation_ids) > 500: raise ValueError( - 'You have requested {} updates, which exceeds the limit of 500'.format( + "You have requested {} updates, which exceeds the limit of 500".format( len(conversation_ids) ) ) response = self.__requester.request( - 'PUT', - 'conversations', + "PUT", + "conversations", event=event, **{"conversation_ids[]": conversation_ids} ) @@ -613,15 +613,15 @@ def create_calendar_event(self, calendar_event, **kwargs): """ from canvasapi.calendar_event import CalendarEvent - if isinstance(calendar_event, dict) and 'context_code' in calendar_event: - kwargs['calendar_event'] = calendar_event + if isinstance(calendar_event, dict) and "context_code" in calendar_event: + kwargs["calendar_event"] = calendar_event else: raise RequiredFieldMissing( "Dictionary with key 'context_codes' is required." ) response = self.__requester.request( - 'POST', 'calendar_events', _kwargs=combine_kwargs(**kwargs) + "POST", "calendar_events", _kwargs=combine_kwargs(**kwargs) ) return CalendarEvent(self.__requester, response.json()) @@ -663,8 +663,8 @@ def get_calendar_events(self, **kwargs): return PaginatedList( CalendarEvent, self.__requester, - 'GET', - 'calendar_events', + "GET", + "calendar_events", _kwargs=combine_kwargs(**kwargs), ) @@ -687,7 +687,7 @@ def get_calendar_event(self, calendar_event): ) response = self.__requester.request( - 'GET', 'calendar_events/{}'.format(calendar_event_id) + "GET", "calendar_events/{}".format(calendar_event_id) ) return CalendarEvent(self.__requester, response.json()) @@ -713,14 +713,14 @@ def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs): ) if participant_id: - uri = 'calendar_events/{}/reservations/{}'.format( + uri = "calendar_events/{}/reservations/{}".format( calendar_event_id, participant_id ) else: - uri = 'calendar_events/{}/reservations'.format(calendar_event_id) + uri = "calendar_events/{}/reservations".format(calendar_event_id) response = self.__requester.request( - 'POST', uri, _kwargs=combine_kwargs(**kwargs) + "POST", uri, _kwargs=combine_kwargs(**kwargs) ) return CalendarEvent(self.__requester, response.json()) @@ -761,8 +761,8 @@ def get_appointment_groups(self, **kwargs): return PaginatedList( AppointmentGroup, self.__requester, - 'GET', - 'appointment_groups', + "GET", + "appointment_groups", _kwargs=combine_kwargs(**kwargs), ) @@ -785,7 +785,7 @@ def get_appointment_group(self, appointment_group): ) response = self.__requester.request( - 'GET', 'appointment_groups/{}'.format(appointment_group_id) + "GET", "appointment_groups/{}".format(appointment_group_id) ) return AppointmentGroup(self.__requester, response.json()) @@ -806,24 +806,24 @@ def create_appointment_group(self, appointment_group, **kwargs): if ( isinstance(appointment_group, dict) - and 'context_codes' in appointment_group - and 'title' in appointment_group + and "context_codes" in appointment_group + and "title" in appointment_group ): - kwargs['appointment_group'] = appointment_group + kwargs["appointment_group"] = appointment_group elif ( isinstance(appointment_group, dict) - and 'context_codes' not in appointment_group + and "context_codes" not in appointment_group ): raise RequiredFieldMissing( "Dictionary with key 'context_codes' is missing." ) - elif isinstance(appointment_group, dict) and 'title' not in appointment_group: + elif isinstance(appointment_group, dict) and "title" not in appointment_group: raise RequiredFieldMissing("Dictionary with key 'title' is missing.") response = self.__requester.request( - 'POST', 'appointment_groups', _kwargs=combine_kwargs(**kwargs) + "POST", "appointment_groups", _kwargs=combine_kwargs(**kwargs) ) return AppointmentGroup(self.__requester, response.json()) @@ -874,8 +874,8 @@ def get_user_participants(self, appointment_group, **kwargs): return PaginatedList( User, self.__requester, - 'GET', - 'appointment_groups/{}/users'.format(appointment_group_id), + "GET", + "appointment_groups/{}/users".format(appointment_group_id), _kwargs=combine_kwargs(**kwargs), ) @@ -925,8 +925,8 @@ def get_group_participants(self, appointment_group, **kwargs): return PaginatedList( Group, self.__requester, - 'GET', - 'appointment_groups/{}/groups'.format(appointment_group_id), + "GET", + "appointment_groups/{}/groups".format(appointment_group_id), _kwargs=combine_kwargs(**kwargs), ) @@ -945,7 +945,7 @@ def get_file(self, file, **kwargs): file_id = obj_or_id(file, "file", (File,)) response = self.__requester.request( - 'GET', 'files/{}'.format(file_id), _kwargs=combine_kwargs(**kwargs) + "GET", "files/{}".format(file_id), _kwargs=combine_kwargs(**kwargs) ) return File(self.__requester, response.json()) @@ -963,7 +963,7 @@ def get_folder(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) + response = self.__requester.request("GET", "folders/{}".format(folder_id)) return Folder(self.__requester, response.json()) def search_recipients(self, **kwargs): @@ -977,11 +977,11 @@ def search_recipients(self, **kwargs): :rtype: `list` """ - if 'search' not in kwargs: - kwargs['search'] = ' ' + if "search" not in kwargs: + kwargs["search"] = " " response = self.__requester.request( - 'GET', 'search/recipients', _kwargs=combine_kwargs(**kwargs) + "GET", "search/recipients", _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -996,7 +996,7 @@ def search_all_courses(self, **kwargs): :rtype: `list` """ response = self.__requester.request( - 'GET', 'search/all_courses', _kwargs=combine_kwargs(**kwargs) + "GET", "search/all_courses", _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -1016,7 +1016,7 @@ def get_outcome(self, outcome): from canvasapi.outcome import Outcome outcome_id = obj_or_id(outcome, "outcome", (Outcome,)) - response = self.__requester.request('GET', 'outcomes/{}'.format(outcome_id)) + response = self.__requester.request("GET", "outcomes/{}".format(outcome_id)) return Outcome(self.__requester, response.json()) def get_root_outcome_group(self): @@ -1031,7 +1031,7 @@ def get_root_outcome_group(self): """ from canvasapi.outcome import OutcomeGroup - response = self.__requester.request('GET', 'global/root_outcome_group') + response = self.__requester.request("GET", "global/root_outcome_group") return OutcomeGroup(self.__requester, response.json()) def get_outcome_group(self, group): @@ -1052,7 +1052,7 @@ def get_outcome_group(self, group): outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,)) response = self.__requester.request( - 'GET', 'global/outcome_groups/{}'.format(outcome_group_id) + "GET", "global/outcome_groups/{}".format(outcome_group_id) ) return OutcomeGroup(self.__requester, response.json()) @@ -1075,7 +1075,7 @@ def get_progress(self, progress, **kwargs): progress_id = obj_or_id(progress, "progress", (Progress,)) response = self.__requester.request( - 'GET', 'progress/{}'.format(progress_id), _kwargs=combine_kwargs(**kwargs) + "GET", "progress/{}".format(progress_id), _kwargs=combine_kwargs(**kwargs) ) return Progress(self.__requester, response.json()) @@ -1094,8 +1094,8 @@ def get_announcements(self, **kwargs): return PaginatedList( DiscussionTopic, self.__requester, - 'GET', - 'announcements', + "GET", + "announcements", _kwargs=combine_kwargs(**kwargs), ) @@ -1114,9 +1114,9 @@ def get_polls(self, **kwargs): return PaginatedList( Poll, self.__requester, - 'GET', - 'polls', - _root='polls', + "GET", + "polls", + _root="polls", _kwargs=combine_kwargs(**kwargs), ) @@ -1136,9 +1136,9 @@ def get_poll(self, poll, **kwargs): poll_id = obj_or_id(poll, "poll", (Poll,)) response = self.__requester.request( - 'GET', 'polls/{}'.format(poll_id), _kwargs=combine_kwargs(**kwargs) + "GET", "polls/{}".format(poll_id), _kwargs=combine_kwargs(**kwargs) ) - return Poll(self.__requester, response.json()['polls'][0]) + return Poll(self.__requester, response.json()["polls"][0]) def create_poll(self, poll, **kwargs): """ @@ -1156,18 +1156,18 @@ def create_poll(self, poll, **kwargs): if ( isinstance(poll, list) and isinstance(poll[0], dict) - and 'question' in poll[0] + and "question" in poll[0] ): - kwargs['poll'] = poll + kwargs["poll"] = poll else: raise RequiredFieldMissing( "Dictionary with key 'question' and is required." ) response = self.__requester.request( - 'POST', 'polls', _kwargs=combine_kwargs(**kwargs) + "POST", "polls", _kwargs=combine_kwargs(**kwargs) ) - return Poll(self.__requester, response.json()['polls'][0]) + return Poll(self.__requester, response.json()["polls"][0]) def get_planner_notes(self, **kwargs): """ @@ -1184,8 +1184,8 @@ def get_planner_notes(self, **kwargs): return PaginatedList( PlannerNote, self.__requester, - 'GET', - 'planner_notes', + "GET", + "planner_notes", _kwargs=combine_kwargs(**kwargs), ) @@ -1211,8 +1211,8 @@ def get_planner_note(self, planner_note, **kwargs): ) response = self.__requester.request( - 'GET', - 'planner_notes/{}'.format(planner_note_id), + "GET", + "planner_notes/{}".format(planner_note_id), _kwargs=combine_kwargs(**kwargs), ) @@ -1230,7 +1230,7 @@ def create_planner_note(self, **kwargs): from canvasapi.planner import PlannerNote response = self.__requester.request( - 'POST', 'planner_notes', _kwargs=combine_kwargs(**kwargs) + "POST", "planner_notes", _kwargs=combine_kwargs(**kwargs) ) return PlannerNote(self.__requester, response.json()) @@ -1249,8 +1249,8 @@ def get_planner_overrides(self, **kwargs): return PaginatedList( PlannerOverride, self.__requester, - 'GET', - 'planner/overrides', + "GET", + "planner/overrides", _kwargs=combine_kwargs(**kwargs), ) @@ -1280,8 +1280,8 @@ def get_planner_override(self, planner_override, **kwargs): ) response = self.__requester.request( - 'GET', - 'planner/overrides/{}'.format(planner_override_id), + "GET", + "planner/overrides/{}".format(planner_override_id), _kwargs=combine_kwargs(**kwargs), ) @@ -1306,16 +1306,16 @@ def create_planner_override(self, plannable_type, plannable_id, **kwargs): from six import text_type, integer_types if isinstance(plannable_type, text_type): - kwargs['plannable_type'] = plannable_type + kwargs["plannable_type"] = plannable_type else: raise RequiredFieldMissing("plannable_type is required as a str.") if isinstance(plannable_id, integer_types): - kwargs['plannable_id'] = plannable_id + kwargs["plannable_id"] = plannable_id else: raise RequiredFieldMissing("plannable_id is required as an int.") response = self.__requester.request( - 'POST', 'planner/overrides', _kwargs=combine_kwargs(**kwargs) + "POST", "planner/overrides", _kwargs=combine_kwargs(**kwargs) ) return PlannerOverride(self.__requester, response.json()) @@ -1333,8 +1333,8 @@ def get_epub_exports(self, **kwargs): return PaginatedList( CourseEpubExport, self.__requester, - 'GET', - 'epub_exports', + "GET", + "epub_exports", _root="courses", kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/canvas_object.py b/canvasapi/canvas_object.py index 5b0b8c0d..f146ade5 100644 --- a/canvasapi/canvas_object.py +++ b/canvasapi/canvas_object.py @@ -6,7 +6,7 @@ from six import text_type -DATE_PATTERN = re.compile('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z') +DATE_PATTERN = re.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z") class CanvasObject(object): @@ -29,14 +29,14 @@ def __init__(self, requester, attributes): def __repr__(self): # pragma: no cover classname = self.__class__.__name__ - attrs = ', '.join( + attrs = ", ".join( [ - '{}={}'.format(attr, val) + "{}={}".format(attr, val) for attr, val in self.__dict__.items() - if attr != 'attributes' + if attr != "attributes" ] ) # noqa - return '{}({})'.format(classname, attrs) + return "{}({})".format(classname, attrs) def to_json(self): """ @@ -76,6 +76,6 @@ def set_attributes(self, attributes): # datetime field if DATE_PATTERN.match(text_type(value)): - naive = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') + naive = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") aware = naive.replace(tzinfo=pytz.utc) - self.__setattr__(attribute + '_date', aware) + self.__setattr__(attribute + "_date", aware) diff --git a/canvasapi/communication_channel.py b/canvasapi/communication_channel.py index 3be25987..76c29f1b 100644 --- a/canvasapi/communication_channel.py +++ b/canvasapi/communication_channel.py @@ -50,14 +50,14 @@ def get_preferences(self, **kwargs): :rtype: `list` """ response = self._requester.request( - 'GET', - 'users/{}/communication_channels/{}/notification_preferences'.format( + "GET", + "users/{}/communication_channels/{}/notification_preferences".format( self.user_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - return response.json()['notification_preferences'] + return response.json()["notification_preferences"] def list_preference_categories(self, **kwargs): """ @@ -99,13 +99,13 @@ def get_preference_categories(self, **kwargs): :rtype: `list` """ response = self._requester.request( - 'GET', - 'users/{}/communication_channels/{}/notification_preference_categories'.format( + "GET", + "users/{}/communication_channels/{}/notification_preference_categories".format( self.user_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - return response.json()['categories'] + return response.json()["categories"] def get_preference(self, notification): """ @@ -122,12 +122,12 @@ def get_preference(self, notification): :rtype: :class:`canvasapi.notification_preference.NotificationPreference` """ response = self._requester.request( - 'GET', - 'users/{}/communication_channels/{}/notification_preferences/{}'.format( + "GET", + "users/{}/communication_channels/{}/notification_preferences/{}".format( self.user_id, self.id, notification ), ) - data = response.json()['notification_preferences'][0] + data = response.json()["notification_preferences"][0] return NotificationPreference(self._requester, data) def update_preference(self, notification, frequency, **kwargs): @@ -147,15 +147,15 @@ def update_preference(self, notification, frequency, **kwargs): :rtype: :class:`canvasapi.notification_preference.NotificationPreference` """ - kwargs['notification_preferences[frequency]'] = frequency + kwargs["notification_preferences[frequency]"] = frequency response = self._requester.request( - 'PUT', - 'users/self/communication_channels/{}/notification_preferences/{}'.format( + "PUT", + "users/self/communication_channels/{}/notification_preferences/{}".format( self.id, notification ), _kwargs=combine_kwargs(**kwargs), ) - data = response.json()['notification_preferences'][0] + data = response.json()["notification_preferences"][0] return NotificationPreference(self._requester, data) def update_preferences_by_catagory(self, category, frequency, **kwargs): @@ -177,15 +177,15 @@ def update_preferences_by_catagory(self, category, frequency, **kwargs): :rtype: :class:`canvasapi.notification_preference.NotificationPreference` """ - kwargs['notification_preferences[frequency]'] = frequency + kwargs["notification_preferences[frequency]"] = frequency response = self._requester.request( - 'PUT', - 'users/self/communication_channels/{}/notification_preference_categories/{}'.format( + "PUT", + "users/self/communication_channels/{}/notification_preference_categories/{}".format( self.id, category ), _kwargs=combine_kwargs(**kwargs), ) - return response.json()['notification_preferences'] + return response.json()["notification_preferences"] def update_multiple_preferences(self, notification_preferences, **kwargs): """ @@ -207,20 +207,20 @@ def update_multiple_preferences(self, notification_preferences, **kwargs): for key, value in notification_preferences.items(): try: - if not value['frequency']: + if not value["frequency"]: return False except KeyError: return False - kwargs['notification_preferences'] = notification_preferences + kwargs["notification_preferences"] = notification_preferences response = self._requester.request( - 'PUT', - 'users/self/communication_channels/{}/notification_preferences'.format( + "PUT", + "users/self/communication_channels/{}/notification_preferences".format( self.id ), _kwargs=combine_kwargs(**kwargs), ) - return response.json()['notification_preferences'] + return response.json()["notification_preferences"] return False def delete(self): @@ -235,7 +235,7 @@ def delete(self): """ response = self._requester.request( - 'DELETE', 'users/{}/communication_channels/{}'.format(self.user_id, self.id) + "DELETE", "users/{}/communication_channels/{}".format(self.user_id, self.id) ) - return response.json().get('workflow_state') == 'deleted' + return response.json().get("workflow_state") == "deleted" diff --git a/canvasapi/content_migration.py b/canvasapi/content_migration.py index e1f276ef..851ea98b 100644 --- a/canvasapi/content_migration.py +++ b/canvasapi/content_migration.py @@ -20,13 +20,13 @@ def _parent_id(self): :rtype: int """ - if hasattr(self, 'course_id'): + if hasattr(self, "course_id"): return self.course_id - elif hasattr(self, 'group_id'): + elif hasattr(self, "group_id"): return self.group_id - elif hasattr(self, 'account_id'): + elif hasattr(self, "account_id"): return self.account_id - elif hasattr(self, 'user_id'): + elif hasattr(self, "user_id"): return self.user_id else: raise ValueError( @@ -40,14 +40,14 @@ def _parent_type(self): :rtype: str """ - if hasattr(self, 'course_id'): - return 'course' - elif hasattr(self, 'group_id'): - return 'group' - elif hasattr(self, 'account_id'): - return 'account' - elif hasattr(self, 'user_id'): - return 'user' + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "group_id"): + return "group" + elif hasattr(self, "account_id"): + return "account" + elif hasattr(self, "user_id"): + return "user" else: raise ValueError( "Content Migration does not have an account_id, course_id, group_id or user_id" @@ -85,8 +85,8 @@ def get_migration_issue(self, migration_issue, **kwargs): ) response = self._requester.request( - 'GET', - '{}s/{}/content_migrations/{}/migration_issues/{}'.format( + "GET", + "{}s/{}/content_migrations/{}/migration_issues/{}".format( self._parent_type, self._parent_id, self.id, migration_issue_id ), _kwargs=combine_kwargs(**kwargs), @@ -95,9 +95,9 @@ def get_migration_issue(self, migration_issue, **kwargs): response_json = response.json() response_json.update( { - 'context_type': self._parent_type, - 'context_id': self._parent_id, - 'content_migration_id': self.id, + "context_type": self._parent_type, + "context_id": self._parent_id, + "content_migration_id": self.id, } ) @@ -131,14 +131,14 @@ def get_migration_issues(self, **kwargs): return PaginatedList( MigrationIssue, self._requester, - 'GET', - '{}s/{}/content_migrations/{}/migration_issues/'.format( + "GET", + "{}s/{}/content_migrations/{}/migration_issues/".format( self._parent_type, self._parent_id, self.id ), { - 'context_type': self._parent_type, - 'context_id': self._parent_id, - 'content_migration_id': self.id, + "context_type": self._parent_type, + "context_id": self._parent_id, + "content_migration_id": self.id, }, _kwargs=combine_kwargs(**kwargs), ) @@ -158,18 +158,18 @@ def get_parent(self, **kwargs): from canvasapi.user import User response = self._requester.request( - 'GET', - '{}s/{}'.format(self._parent_type, self._parent_id), + "GET", + "{}s/{}".format(self._parent_type, self._parent_id), _kwargs=combine_kwargs(**kwargs), ) - if self._parent_type == 'group': + if self._parent_type == "group": return Group(self._requester, response.json()) - elif self._parent_type == 'course': + elif self._parent_type == "course": return Course(self._requester, response.json()) - elif self._parent_type == 'account': + elif self._parent_type == "account": return Account(self._requester, response.json()) - elif self._parent_type == 'user': + elif self._parent_type == "user": return User(self._requester, response.json()) def get_progress(self, **kwargs): @@ -187,7 +187,7 @@ def get_progress(self, **kwargs): progress_id = self.progress_url.split("/")[-1] response = self._requester.request( - 'GET', 'progress/{}'.format(progress_id), _kwargs=combine_kwargs(**kwargs) + "GET", "progress/{}".format(progress_id), _kwargs=combine_kwargs(**kwargs) ) return Progress(self._requester, response.json()) @@ -211,14 +211,14 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/content_migrations/{}'.format( + "PUT", + "{}s/{}/content_migrations/{}".format( self._parent_type, self._parent_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - if 'migration_type' in response.json(): + if "migration_type" in response.json(): super(ContentMigration, self).set_attributes(response.json()) return True else: @@ -251,14 +251,14 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/content_migrations/{}/migration_issues/{}'.format( + "PUT", + "{}s/{}/content_migrations/{}/migration_issues/{}".format( self.context_type, self.context_id, self.content_migration_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - if 'workflow_state' in response.json(): + if "workflow_state" in response.json(): super(MigrationIssue, self).set_attributes(response.json()) return True else: diff --git a/canvasapi/conversation.py b/canvasapi/conversation.py index a4edba2f..d3d75261 100644 --- a/canvasapi/conversation.py +++ b/canvasapi/conversation.py @@ -21,10 +21,10 @@ def edit(self, **kwargs): :rtype: `bool` """ response = self._requester.request( - 'PUT', 'conversations/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "conversations/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - if response.json().get('id'): + if response.json().get("id"): super(Conversation, self).set_attributes(response.json()) return True else: @@ -39,9 +39,9 @@ def delete(self): :rtype: `bool` """ - response = self._requester.request('DELETE', 'conversations/{}'.format(self.id)) + response = self._requester.request("DELETE", "conversations/{}".format(self.id)) - if response.json().get('id'): + if response.json().get("id"): super(Conversation, self).set_attributes(response.json()) return True else: @@ -62,8 +62,8 @@ def add_recipients(self, recipients): :rtype: :class:`canvasapi.account.Conversation` """ response = self._requester.request( - 'POST', - 'conversations/{}/add_recipients'.format(self.id), + "POST", + "conversations/{}/add_recipients".format(self.id), recipients=recipients, ) return Conversation(self._requester, response.json()) @@ -81,8 +81,8 @@ def add_message(self, body, **kwargs): :rtype: :class:`canvasapi.account.Conversation` """ response = self._requester.request( - 'POST', - 'conversations/{}/add_message'.format(self.id), + "POST", + "conversations/{}/add_message".format(self.id), body=body, _kwargs=combine_kwargs(**kwargs), ) @@ -103,6 +103,6 @@ def delete_messages(self, remove): :rtype: `dict` """ response = self._requester.request( - 'POST', 'conversations/{}/remove_messages'.format(self.id), remove=remove + "POST", "conversations/{}/remove_messages".format(self.id), remove=remove ) return response.json() diff --git a/canvasapi/course.py b/canvasapi/course.py index f63394d8..509001d3 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -30,13 +30,13 @@ from canvasapi.rubric import Rubric -warnings.simplefilter('always', DeprecationWarning) +warnings.simplefilter("always", DeprecationWarning) @python_2_unicode_compatible class Course(CanvasObject): def __str__(self): - return '{} {} ({})'.format(self.course_code, self.name, self.id) + return "{} {} ({})".format(self.course_code, self.name, self.id) def conclude(self): """ @@ -49,10 +49,10 @@ def conclude(self): :rtype: bool """ response = self._requester.request( - 'DELETE', 'courses/{}'.format(self.id), event="conclude" + "DELETE", "courses/{}".format(self.id), event="conclude" ) - return response.json().get('conclude') + return response.json().get("conclude") def create_assignment_overrides(self, assignment_overrides, **kwargs): """ @@ -69,14 +69,14 @@ def create_assignment_overrides(self, assignment_overrides, **kwargs): """ from canvasapi.assignment import AssignmentOverride - kwargs['assignment_overrides'] = assignment_overrides + kwargs["assignment_overrides"] = assignment_overrides return PaginatedList( AssignmentOverride, self._requester, - 'POST', - 'courses/{}/assignments/overrides'.format(self.id), - {'course_id': self.id}, + "POST", + "courses/{}/assignments/overrides".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -91,9 +91,9 @@ def delete(self): :rtype: bool """ response = self._requester.request( - 'DELETE', 'courses/{}'.format(self.id), event="delete" + "DELETE", "courses/{}".format(self.id), event="delete" ) - return response.json().get('delete') + return response.json().get("delete") def update(self, **kwargs): """ @@ -106,13 +106,13 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', 'courses/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "courses/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - if response.json().get('name'): + if response.json().get("name"): super(Course, self).set_attributes(response.json()) - return response.json().get('name') + return response.json().get("name") def update_assignment_overrides(self, assignment_overrides, **kwargs): """ @@ -131,14 +131,14 @@ def update_assignment_overrides(self, assignment_overrides, **kwargs): """ from canvasapi.assignment import AssignmentOverride - kwargs['assignment_overrides'] = assignment_overrides + kwargs["assignment_overrides"] = assignment_overrides return PaginatedList( AssignmentOverride, self._requester, - 'PUT', - 'courses/{}/assignments/overrides'.format(self.id), - {'course_id': self.id}, + "PUT", + "courses/{}/assignments/overrides".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -160,12 +160,12 @@ def get_user(self, user, user_id_type=None): from canvasapi.user import User if user_id_type: - uri = 'courses/{}/users/{}:{}'.format(self.id, user_id_type, user) + uri = "courses/{}/users/{}:{}".format(self.id, user_id_type, user) else: user_id = obj_or_id(user, "user", (User,)) - uri = 'courses/{}/users/{}'.format(self.id, user_id) + uri = "courses/{}/users/{}".format(self.id, user_id) - response = self._requester.request('GET', uri) + response = self._requester.request("GET", uri) return User(self._requester, response.json()) def get_users(self, **kwargs): @@ -183,8 +183,8 @@ def get_users(self, **kwargs): return PaginatedList( User, self._requester, - 'GET', - 'courses/{}/search_users'.format(self.id), + "GET", + "courses/{}/search_users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -204,12 +204,12 @@ def enroll_user(self, user, enrollment_type, **kwargs): from canvasapi.enrollment import Enrollment from canvasapi.user import User - kwargs['enrollment[user_id]'] = obj_or_id(user, "user", (User,)) - kwargs['enrollment[type]'] = enrollment_type + kwargs["enrollment[user_id]"] = obj_or_id(user, "user", (User,)) + kwargs["enrollment[type]"] = enrollment_type response = self._requester.request( - 'POST', - 'courses/{}/enrollments'.format(self.id), + "POST", + "courses/{}/enrollments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -229,7 +229,7 @@ def get_recent_students(self): from canvasapi.user import User return PaginatedList( - User, self._requester, 'GET', 'courses/{}/recent_students'.format(self.id) + User, self._requester, "GET", "courses/{}/recent_students".format(self.id) ) def preview_html(self, html): @@ -244,9 +244,9 @@ def preview_html(self, html): :rtype: str """ response = self._requester.request( - 'POST', 'courses/{}/preview_html'.format(self.id), html=html + "POST", "courses/{}/preview_html".format(self.id), html=html ) - return response.json().get('html', '') + return response.json().get("html", "") def get_settings(self): """ @@ -257,7 +257,7 @@ def get_settings(self): :rtype: dict """ - response = self._requester.request('GET', 'courses/{}/settings'.format(self.id)) + response = self._requester.request("GET", "courses/{}/settings".format(self.id)) return response.json() def update_settings(self, **kwargs): @@ -270,7 +270,7 @@ def update_settings(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'PUT', 'courses/{}/settings'.format(self.id), **kwargs + "PUT", "courses/{}/settings".format(self.id), **kwargs ) return response.json() @@ -288,7 +288,7 @@ def upload(self, file, **kwargs): :rtype: tuple """ return Uploader( - self._requester, 'courses/{}/files'.format(self.id), file, **kwargs + self._requester, "courses/{}/files".format(self.id), file, **kwargs ).start() def reset(self): @@ -302,7 +302,7 @@ def reset(self): :rtype: :class:`canvasapi.course.Course` """ response = self._requester.request( - 'POST', 'courses/{}/reset_content'.format(self.id) + "POST", "courses/{}/reset_content".format(self.id) ) return Course(self._requester, response.json()) @@ -321,8 +321,8 @@ def get_enrollments(self, **kwargs): return PaginatedList( Enrollment, self._requester, - 'GET', - 'courses/{}/enrollments'.format(self.id), + "GET", + "courses/{}/enrollments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -343,8 +343,8 @@ def get_assignment(self, assignment, **kwargs): assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) response = self._requester.request( - 'GET', - 'courses/{}/assignments/{}'.format(self.id, assignment_id), + "GET", + "courses/{}/assignments/{}".format(self.id, assignment_id), _kwargs=combine_kwargs(**kwargs), ) return Assignment(self._requester, response.json()) @@ -362,14 +362,14 @@ def get_assignment_overrides(self, assignment_overrides, **kwargs): """ from canvasapi.assignment import AssignmentOverride - kwargs['assignment_overrides'] = assignment_overrides + kwargs["assignment_overrides"] = assignment_overrides return PaginatedList( AssignmentOverride, self._requester, - 'GET', - 'courses/{}/assignments/overrides'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/assignments/overrides".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -388,8 +388,8 @@ def get_assignments(self, **kwargs): return PaginatedList( Assignment, self._requester, - 'GET', - 'courses/{}/assignments'.format(self.id), + "GET", + "courses/{}/assignments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -408,14 +408,14 @@ def create_assignment(self, assignment, **kwargs): """ from canvasapi.assignment import Assignment - if isinstance(assignment, dict) and 'name' in assignment: - kwargs['assignment'] = assignment + if isinstance(assignment, dict) and "name" in assignment: + kwargs["assignment"] = assignment else: raise RequiredFieldMissing("Dictionary with key 'name' is required.") response = self._requester.request( - 'POST', - 'courses/{}/assignments'.format(self.id), + "POST", + "courses/{}/assignments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -436,9 +436,9 @@ def get_quizzes(self, **kwargs): return PaginatedList( Quiz, self._requester, - 'GET', - 'courses/{}/quizzes'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/quizzes".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -459,10 +459,10 @@ def get_quiz(self, quiz): quiz_id = obj_or_id(quiz, "quiz", (Quiz,)) response = self._requester.request( - 'GET', 'courses/{}/quizzes/{}'.format(self.id, quiz_id) + "GET", "courses/{}/quizzes/{}".format(self.id, quiz_id) ) quiz_json = response.json() - quiz_json.update({'course_id': self.id}) + quiz_json.update({"course_id": self.id}) return Quiz(self._requester, quiz_json) @@ -479,18 +479,18 @@ def create_quiz(self, quiz, **kwargs): """ from canvasapi.quiz import Quiz - if isinstance(quiz, dict) and 'title' in quiz: - kwargs['quiz'] = quiz + if isinstance(quiz, dict) and "title" in quiz: + kwargs["quiz"] = quiz else: raise RequiredFieldMissing("Dictionary with key 'title' is required.") response = self._requester.request( - 'POST', - 'courses/{}/quizzes'.format(self.id), + "POST", + "courses/{}/quizzes".format(self.id), _kwargs=combine_kwargs(**kwargs), ) quiz_json = response.json() - quiz_json.update({'course_id': self.id}) + quiz_json.update({"course_id": self.id}) return Quiz(self._requester, quiz_json) @@ -509,9 +509,9 @@ def get_modules(self, **kwargs): return PaginatedList( Module, self._requester, - 'GET', - 'courses/{}/modules'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/modules".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -532,10 +532,10 @@ def get_module(self, module, **kwargs): module_id = obj_or_id(module, "module", (Module,)) response = self._requester.request( - 'GET', 'courses/{}/modules/{}'.format(self.id, module_id) + "GET", "courses/{}/modules/{}".format(self.id, module_id) ) module_json = response.json() - module_json.update({'course_id': self.id}) + module_json.update({"course_id": self.id}) return Module(self._requester, module_json) @@ -553,18 +553,18 @@ def create_module(self, module, **kwargs): """ from canvasapi.module import Module - if isinstance(module, dict) and 'name' in module: - kwargs['module'] = module + if isinstance(module, dict) and "name" in module: + kwargs["module"] = module else: raise RequiredFieldMissing("Dictionary with key 'name' is required.") response = self._requester.request( - 'POST', - 'courses/{}/modules'.format(self.id), + "POST", + "courses/{}/modules".format(self.id), _kwargs=combine_kwargs(**kwargs), ) module_json = response.json() - module_json.update({'course_id': self.id}) + module_json.update({"course_id": self.id}) return Module(self._requester, module_json) @@ -583,10 +583,10 @@ def get_external_tool(self, tool): tool_id = obj_or_id(tool, "tool", (ExternalTool,)) response = self._requester.request( - 'GET', 'courses/{}/external_tools/{}'.format(self.id, tool_id) + "GET", "courses/{}/external_tools/{}".format(self.id, tool_id) ) tool_json = response.json() - tool_json.update({'course_id': self.id}) + tool_json.update({"course_id": self.id}) return ExternalTool(self._requester, tool_json) @@ -603,9 +603,9 @@ def get_external_tools(self, **kwargs): return PaginatedList( ExternalTool, self._requester, - 'GET', - 'courses/{}/external_tools'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/external_tools".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -624,8 +624,8 @@ def get_sections(self, **kwargs): return PaginatedList( Section, self._requester, - 'GET', - 'courses/{}/sections'.format(self.id), + "GET", + "courses/{}/sections".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -646,8 +646,8 @@ def get_section(self, section, **kwargs): section_id = obj_or_id(section, "section", (Section,)) response = self._requester.request( - 'GET', - 'courses/{}/sections/{}'.format(self.id, section_id), + "GET", + "courses/{}/sections/{}".format(self.id, section_id), _kwargs=combine_kwargs(**kwargs), ) return Section(self._requester, response.json()) @@ -662,10 +662,10 @@ def show_front_page(self): :rtype: :class:`canvasapi.course.Course` """ response = self._requester.request( - 'GET', 'courses/{}/front_page'.format(self.id) + "GET", "courses/{}/front_page".format(self.id) ) page_json = response.json() - page_json.update({'course_id': self.id}) + page_json.update({"course_id": self.id}) return Page(self._requester, page_json) @@ -679,12 +679,12 @@ def edit_front_page(self, **kwargs): :rtype: :class:`canvasapi.course.Course` """ response = self._requester.request( - 'PUT', - 'courses/{}/front_page'.format(self.id), + "PUT", + "courses/{}/front_page".format(self.id), _kwargs=combine_kwargs(**kwargs), ) page_json = response.json() - page_json.update({'course_id': self.id}) + page_json.update({"course_id": self.id}) return Page(self._requester, page_json) @@ -701,9 +701,9 @@ def get_pages(self, **kwargs): return PaginatedList( Page, self._requester, - 'GET', - 'courses/{}/pages'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/pages".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -720,17 +720,17 @@ def create_page(self, wiki_page, **kwargs): :rtype: :class:`canvasapi.course.Course` """ - if isinstance(wiki_page, dict) and 'title' in wiki_page: - kwargs['wiki_page'] = wiki_page + if isinstance(wiki_page, dict) and "title" in wiki_page: + kwargs["wiki_page"] = wiki_page else: raise RequiredFieldMissing("Dictionary with key 'title' is required.") response = self._requester.request( - 'POST', 'courses/{}/pages'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "POST", "courses/{}/pages".format(self.id), _kwargs=combine_kwargs(**kwargs) ) page_json = response.json() - page_json.update({'course_id': self.id}) + page_json.update({"course_id": self.id}) return Page(self._requester, page_json) @@ -748,10 +748,10 @@ def get_page(self, url): """ response = self._requester.request( - 'GET', 'courses/{}/pages/{}'.format(self.id, url) + "GET", "courses/{}/pages/{}".format(self.id, url) ) page_json = response.json() - page_json.update({'course_id': self.id}) + page_json.update({"course_id": self.id}) return Page(self._requester, page_json) @@ -789,8 +789,8 @@ def create_course_section(self, **kwargs): from canvasapi.section import Section response = self._requester.request( - 'POST', - 'courses/{}/sections'.format(self.id), + "POST", + "courses/{}/sections".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -833,8 +833,8 @@ def get_groups(self, **kwargs): return PaginatedList( Group, self._requester, - 'GET', - 'courses/{}/groups'.format(self.id), + "GET", + "courses/{}/groups".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -852,8 +852,8 @@ def create_group_category(self, name, **kwargs): from canvasapi.group import GroupCategory response = self._requester.request( - 'POST', - 'courses/{}/group_categories'.format(self.id), + "POST", + "courses/{}/group_categories".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) @@ -896,8 +896,8 @@ def get_group_categories(self, **kwargs): return PaginatedList( GroupCategory, self._requester, - 'GET', - 'courses/{}/group_categories'.format(self.id), + "GET", + "courses/{}/group_categories".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -918,8 +918,8 @@ def get_file(self, file, **kwargs): file_id = obj_or_id(file, "file", (File,)) response = self._requester.request( - 'GET', - 'courses/{}/files/{}'.format(self.id, file_id), + "GET", + "courses/{}/files/{}".format(self.id, file_id), _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) @@ -939,11 +939,11 @@ def get_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', 'courses/{}/discussion_topics/{}'.format(self.id, topic_id) + "GET", "courses/{}/discussion_topics/{}".format(self.id, topic_id) ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return DiscussionTopic(self._requester, response_json) @@ -962,7 +962,7 @@ def get_full_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', 'courses/{}/discussion_topics/{}/view'.format(self.id, topic_id) + "GET", "courses/{}/discussion_topics/{}/view".format(self.id, topic_id) ) return response.json() @@ -979,9 +979,9 @@ def get_discussion_topics(self, **kwargs): return PaginatedList( DiscussionTopic, self._requester, - 'GET', - 'courses/{}/discussion_topics'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/discussion_topics".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1004,12 +1004,12 @@ def get_assignment_group(self, assignment_group, **kwargs): ) response = self._requester.request( - 'GET', - 'courses/{}/assignment_groups/{}'.format(self.id, assignment_group_id), + "GET", + "courses/{}/assignment_groups/{}".format(self.id, assignment_group_id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return AssignmentGroup(self._requester, response_json) @@ -1050,9 +1050,9 @@ def get_assignment_groups(self, **kwargs): return PaginatedList( AssignmentGroup, self._requester, - 'GET', - 'courses/{}/assignment_groups'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/assignment_groups".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1066,13 +1066,13 @@ def create_discussion_topic(self, **kwargs): :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` """ response = self._requester.request( - 'POST', - 'courses/{}/discussion_topics'.format(self.id), + "POST", + "courses/{}/discussion_topics".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return DiscussionTopic(self._requester, response_json) @@ -1100,10 +1100,10 @@ def reorder_pinned_topics(self, order): raise ValueError("Param `order` must be a list, tuple, or string.") response = self._requester.request( - 'POST', 'courses/{}/discussion_topics/reorder'.format(self.id), order=order + "POST", "courses/{}/discussion_topics/reorder".format(self.id), order=order ) - return response.json().get('reorder') + return response.json().get("reorder") def create_assignment_group(self, **kwargs): """ @@ -1117,12 +1117,12 @@ def create_assignment_group(self, **kwargs): from canvasapi.assignment import AssignmentGroup response = self._requester.request( - 'POST', - 'courses/{}/assignment_groups'.format(self.id), + "POST", + "courses/{}/assignment_groups".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return AssignmentGroup(self._requester, response_json) @@ -1149,8 +1149,8 @@ def create_external_tool( from canvasapi.external_tool import ExternalTool response = self._requester.request( - 'POST', - 'courses/{}/external_tools'.format(self.id), + "POST", + "courses/{}/external_tools".format(self.id), name=name, privacy_level=privacy_level, consumer_key=consumer_key, @@ -1158,7 +1158,7 @@ def create_external_tool( _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return ExternalTool(self._requester, response_json) @@ -1173,7 +1173,7 @@ def get_course_level_participation_data(self): """ response = self._requester.request( - 'GET', 'courses/{}/analytics/activity'.format(self.id) + "GET", "courses/{}/analytics/activity".format(self.id) ) return response.json() @@ -1189,8 +1189,8 @@ def get_course_level_assignment_data(self, **kwargs): """ response = self._requester.request( - 'GET', - 'courses/{}/analytics/assignments'.format(self.id), + "GET", + "courses/{}/analytics/assignments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1207,8 +1207,8 @@ def get_course_level_student_summary_data(self, **kwargs): """ response = self._requester.request( - 'GET', - 'courses/{}/analytics/student_summaries'.format(self.id), + "GET", + "courses/{}/analytics/student_summaries".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1231,7 +1231,7 @@ def get_user_in_a_course_level_participation_data(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', 'courses/{}/analytics/users/{}/activity'.format(self.id, user_id) + "GET", "courses/{}/analytics/users/{}/activity".format(self.id, user_id) ) return response.json() @@ -1253,7 +1253,7 @@ def get_user_in_a_course_level_assignment_data(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', 'courses/{}/analytics/users/{}/assignments'.format(self.id, user_id) + "GET", "courses/{}/analytics/users/{}/assignments".format(self.id, user_id) ) return response.json() @@ -1275,8 +1275,8 @@ def get_user_in_a_course_level_messaging_data(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', - 'courses/{}/analytics/users/{}/communication'.format(self.id, user_id), + "GET", + "courses/{}/analytics/users/{}/communication".format(self.id, user_id), ) return response.json() @@ -1303,15 +1303,15 @@ def submit_assignment(self, assignment, submission, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - 'Course.submit_assignment() is deprecated and will be removed in ' - 'the future. Use Assignment.submit() instead.', + "Course.submit_assignment() is deprecated and will be removed in " + "the future. Use Assignment.submit() instead.", DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, {'course_id': self.id, 'id': assignment_id} + self._requester, {"course_id": self.id, "id": assignment_id} ) return assignment.submit(submission, **kwargs) @@ -1336,15 +1336,15 @@ def list_submissions(self, assignment, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - 'Course.list_submissions() is deprecated and will be removed in ' - 'the future. Use Assignment.get_submissions() instead.', + "Course.list_submissions() is deprecated and will be removed in " + "the future. Use Assignment.get_submissions() instead.", DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, {'course_id': self.id, 'id': assignment_id} + self._requester, {"course_id": self.id, "id": assignment_id} ) return assignment.get_submissions(**kwargs) @@ -1395,9 +1395,9 @@ def get_multiple_submissions(self, **kwargs): return PaginatedList( cls, self._requester, - 'GET', - 'courses/{}/students/submissions'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/students/submissions".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1422,15 +1422,15 @@ def get_submission(self, assignment, user, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - '`Course.get_submission()` is deprecated and will be removed in a ' - 'future version. Use `Assignment.get_submission()` instead', + "`Course.get_submission()` is deprecated and will be removed in a " + "future version. Use `Assignment.get_submission()` instead", DeprecationWarning, ) - assignment_id = obj_or_id(assignment, 'assignment', (Assignment,)) + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, {'course_id': self.id, 'id': assignment_id} + self._requester, {"course_id": self.id, "id": assignment_id} ) return assignment.get_submission(user, **kwargs) @@ -1457,8 +1457,8 @@ def update_submission(self, assignment, user, **kwargs): from canvasapi.user import User warnings.warn( - '`Course.update_submission()` is deprecated and will be removed in a ' - 'future version. Use `Submission.edit()` instead', + "`Course.update_submission()` is deprecated and will be removed in a " + "future version. Use `Submission.edit()` instead", DeprecationWarning, ) @@ -1467,7 +1467,7 @@ def update_submission(self, assignment, user, **kwargs): submission = Submission( self._requester, - {'course_id': self.id, 'assignment_id': assignment_id, 'user_id': user_id}, + {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, ) return submission.edit(**kwargs) @@ -1492,15 +1492,15 @@ def list_gradeable_students(self, assignment, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - '`Course.list_gradeable_students()` is deprecated and will be ' - 'removed in a future version. Use ' - '`Assignment.get_gradeable_students()` instead.', + "`Course.list_gradeable_students()` is deprecated and will be " + "removed in a future version. Use " + "`Assignment.get_gradeable_students()` instead.", DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( - self._requester, {'id': assignment_id, 'course_id': self.id} + self._requester, {"id": assignment_id, "course_id": self.id} ) return assignment.get_gradeable_students(**kwargs) @@ -1528,8 +1528,8 @@ def mark_submission_as_read(self, assignment, user, **kwargs): from canvasapi.user import User warnings.warn( - '`Course.mark_submission_as_read()` is deprecated and will be ' - 'removed in a future version. Use `Submission.mark_read()` instead.', + "`Course.mark_submission_as_read()` is deprecated and will be " + "removed in a future version. Use `Submission.mark_read()` instead.", DeprecationWarning, ) @@ -1538,7 +1538,7 @@ def mark_submission_as_read(self, assignment, user, **kwargs): submission = Submission( self._requester, - {'course_id': self.id, 'assignment_id': assignment_id, 'user_id': user_id}, + {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, ) return submission.mark_read(**kwargs) @@ -1565,8 +1565,8 @@ def mark_submission_as_unread(self, assignment, user, **kwargs): from canvasapi.user import User warnings.warn( - '`Course.mark_submission_as_unread()` is deprecated and will be ' - 'removed in a future version. Use `Submission.mark_unread()` instead.', + "`Course.mark_submission_as_unread()` is deprecated and will be " + "removed in a future version. Use `Submission.mark_unread()` instead.", DeprecationWarning, ) @@ -1575,7 +1575,7 @@ def mark_submission_as_unread(self, assignment, user, **kwargs): submission = Submission( self._requester, - {'course_id': self.id, 'assignment_id': assignment_id, 'user_id': user_id}, + {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, ) return submission.mark_unread(**kwargs) @@ -1616,8 +1616,8 @@ def get_external_feeds(self, **kwargs): return PaginatedList( ExternalFeed, self._requester, - 'GET', - 'courses/{}/external_feeds'.format(self.id), + "GET", + "courses/{}/external_feeds".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1635,8 +1635,8 @@ def create_external_feed(self, url, **kwargs): from canvasapi.external_feed import ExternalFeed response = self._requester.request( - 'POST', - 'courses/{}/external_feeds'.format(self.id), + "POST", + "courses/{}/external_feeds".format(self.id), url=url, _kwargs=combine_kwargs(**kwargs), ) @@ -1659,7 +1659,7 @@ def delete_external_feed(self, feed): feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) response = self._requester.request( - 'DELETE', 'courses/{}/external_feeds/{}'.format(self.id, feed_id) + "DELETE", "courses/{}/external_feeds/{}".format(self.id, feed_id) ) return ExternalFeed(self._requester, response.json()) @@ -1700,8 +1700,8 @@ def get_files(self, **kwargs): return PaginatedList( File, self._requester, - 'GET', - 'courses/{}/files'.format(self.id), + "GET", + "courses/{}/files".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1720,7 +1720,7 @@ def get_folder(self, folder): folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - 'GET', 'courses/{}/folders/{}'.format(self.id, folder_id) + "GET", "courses/{}/folders/{}".format(self.id, folder_id) ) return Folder(self._requester, response.json()) @@ -1761,8 +1761,8 @@ def get_folders(self, **kwargs): return PaginatedList( Folder, self._requester, - 'GET', - 'courses/{}/folders'.format(self.id), + "GET", + "courses/{}/folders".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1778,8 +1778,8 @@ def create_folder(self, name, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'POST', - 'courses/{}/folders'.format(self.id), + "POST", + "courses/{}/folders".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) @@ -1822,9 +1822,9 @@ def get_tabs(self, **kwargs): return PaginatedList( Tab, self._requester, - 'GET', - 'courses/{}/tabs'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/tabs".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1850,7 +1850,7 @@ def update_tab(self, tab_id, **kwargs): DeprecationWarning, ) - tab = Tab(self._requester, {'course_id': self.id, 'id': tab_id}) + tab = Tab(self._requester, {"course_id": self.id, "id": tab_id}) return tab.update(**kwargs) def get_rubric(self, rubric_id, **kwargs): @@ -1865,8 +1865,8 @@ def get_rubric(self, rubric_id, **kwargs): :rtype: :class:`canvasapi.rubric.Rubric` """ response = self._requester.request( - 'GET', - 'courses/%s/rubrics/%s' % (self.id, rubric_id), + "GET", + "courses/%s/rubrics/%s" % (self.id, rubric_id), _kwargs=combine_kwargs(**kwargs), ) @@ -1907,8 +1907,8 @@ def get_rubrics(self, **kwargs): return PaginatedList( Rubric, self._requester, - 'GET', - 'courses/%s/rubrics' % (self.id), + "GET", + "courses/%s/rubrics" % (self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1925,7 +1925,7 @@ def get_root_outcome_group(self): from canvasapi.outcome import OutcomeGroup response = self._requester.request( - 'GET', 'courses/{}/root_outcome_group'.format(self.id) + "GET", "courses/{}/root_outcome_group".format(self.id) ) return OutcomeGroup(self._requester, response.json()) @@ -1947,7 +1947,7 @@ def get_outcome_group(self, group): outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,)) response = self._requester.request( - 'GET', 'courses/{}/outcome_groups/{}'.format(self.id, outcome_group_id) + "GET", "courses/{}/outcome_groups/{}".format(self.id, outcome_group_id) ) return OutcomeGroup(self._requester, response.json()) @@ -1968,8 +1968,8 @@ def get_outcome_groups_in_context(self): return PaginatedList( OutcomeGroup, self._requester, - 'GET', - 'courses/{}/outcome_groups'.format(self.id), + "GET", + "courses/{}/outcome_groups".format(self.id), ) def get_all_outcome_links_in_context(self): @@ -1988,8 +1988,8 @@ def get_all_outcome_links_in_context(self): return PaginatedList( OutcomeLink, self._requester, - 'GET', - 'courses/{}/outcome_group_links'.format(self.id), + "GET", + "courses/{}/outcome_group_links".format(self.id), ) def get_outcome_results(self, **kwargs): @@ -2003,8 +2003,8 @@ def get_outcome_results(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'GET', - 'courses/{}/outcome_results'.format(self.id), + "GET", + "courses/{}/outcome_results".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -2021,8 +2021,8 @@ def get_outcome_result_rollups(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'GET', - 'courses/{}/outcome_rollups'.format(self.id), + "GET", + "courses/{}/outcome_rollups".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -2054,8 +2054,8 @@ def add_grading_standards(self, title, grading_scheme_entry, **kwargs): kwargs["grading_scheme_entry"] = grading_scheme_entry response = self._requester.request( - 'POST', - 'courses/%s/grading_standards' % (self.id), + "POST", + "courses/%s/grading_standards" % (self.id), title=title, _kwargs=combine_kwargs(**kwargs), ) @@ -2074,8 +2074,8 @@ def get_grading_standards(self, **kwargs): return PaginatedList( GradingStandard, self._requester, - 'GET', - 'courses/%s/grading_standards' % (self.id), + "GET", + "courses/%s/grading_standards" % (self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -2092,8 +2092,8 @@ def get_single_grading_standard(self, grading_standard_id, **kwargs): """ response = self._requester.request( - 'GET', - 'courses/%s/grading_standards/%d' % (self.id, grading_standard_id), + "GET", + "courses/%s/grading_standards/%d" % (self.id, grading_standard_id), _kwargs=combine_kwargs(**kwargs), ) return GradingStandard(self._requester, response.json()) @@ -2113,20 +2113,20 @@ def create_content_migration(self, migration_type, **kwargs): from canvasapi.content_migration import ContentMigration, Migrator if isinstance(migration_type, Migrator): - kwargs['migration_type'] = migration_type.type + kwargs["migration_type"] = migration_type.type elif isinstance(migration_type, string_types): - kwargs['migration_type'] = migration_type + kwargs["migration_type"] = migration_type else: - raise TypeError('Parameter migration_type must be of type Migrator or str') + raise TypeError("Parameter migration_type must be of type Migrator or str") response = self._requester.request( - 'POST', - 'courses/{}/content_migrations'.format(self.id), + "POST", + "courses/{}/content_migrations".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return ContentMigration(self._requester, response_json) @@ -2149,13 +2149,13 @@ def get_content_migration(self, content_migration, **kwargs): ) response = self._requester.request( - 'GET', - 'courses/{}/content_migrations/{}'.format(self.id, migration_id), + "GET", + "courses/{}/content_migrations/{}".format(self.id, migration_id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return ContentMigration(self._requester, response_json) @@ -2174,9 +2174,9 @@ def get_content_migrations(self, **kwargs): return PaginatedList( ContentMigration, self._requester, - 'GET', - 'courses/{}/content_migrations'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/content_migrations".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -2195,8 +2195,8 @@ def get_migration_systems(self, **kwargs): return PaginatedList( Migrator, self._requester, - 'GET', - 'courses/{}/content_migrations/migrators'.format(self.id), + "GET", + "courses/{}/content_migrations/migrators".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -2232,24 +2232,24 @@ def set_quiz_extensions(self, quiz_extensions, **kwargs): """ if not isinstance(quiz_extensions, list) or not quiz_extensions: - raise ValueError('Param `quiz_extensions` must be a non-empty list.') + raise ValueError("Param `quiz_extensions` must be a non-empty list.") if any(not isinstance(extension, dict) for extension in quiz_extensions): - raise ValueError('Param `quiz_extensions` must only contain dictionaries') + raise ValueError("Param `quiz_extensions` must only contain dictionaries") - if any('user_id' not in extension for extension in quiz_extensions): + if any("user_id" not in extension for extension in quiz_extensions): raise RequiredFieldMissing( - 'Dictionaries in `quiz_extensions` must contain key `user_id`' + "Dictionaries in `quiz_extensions` must contain key `user_id`" ) - kwargs['quiz_extensions'] = quiz_extensions + kwargs["quiz_extensions"] = quiz_extensions response = self._requester.request( - 'POST', - 'courses/{}/quiz_extensions'.format(self.id), + "POST", + "courses/{}/quiz_extensions".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - extension_list = response.json()['quiz_extensions'] + extension_list = response.json()["quiz_extensions"] return [ QuizExtension(self._requester, extension) for extension in extension_list ] @@ -2265,13 +2265,13 @@ def submissions_bulk_update(self, **kwargs): :rtype: :class:`canvasapi.progress.Progress` """ response = self._requester.request( - 'POST', - 'courses/{}/submissions/update_grades'.format(self.id), + "POST", + "courses/{}/submissions/update_grades".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) - def get_blueprint(self, template='default', **kwargs): + def get_blueprint(self, template="default", **kwargs): """ Return the blueprint of a given ID. @@ -2285,14 +2285,14 @@ def get_blueprint(self, template='default', **kwargs): """ from canvasapi.blueprint import BlueprintTemplate - if template == 'default': + if template == "default": template_id = template else: - template_id = obj_or_id(template, 'template', (BlueprintTemplate,)) + template_id = obj_or_id(template, "template", (BlueprintTemplate,)) response = self._requester.request( - 'GET', - 'courses/{}/blueprint_templates/{}'.format(self.id, template_id), + "GET", + "courses/{}/blueprint_templates/{}".format(self.id, template_id), _kwargs=combine_kwargs(**kwargs), ) return BlueprintTemplate(self._requester, response.json()) @@ -2312,9 +2312,9 @@ def list_blueprint_subscriptions(self, **kwargs): return PaginatedList( BlueprintSubscription, self._requester, - 'GET', - 'courses/{}/blueprint_subscriptions'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/blueprint_subscriptions".format(self.id), + {"course_id": self.id}, kwargs=combine_kwargs(**kwargs), ) @@ -2394,11 +2394,11 @@ def get_epub_export(self, epub, **kwargs): :rtype: :class:`canvasapi.course_epub_export.CourseEpubExport` """ - epub_id = obj_or_id(epub, 'epub', (CourseEpubExport,)) + epub_id = obj_or_id(epub, "epub", (CourseEpubExport,)) response = self._requester.request( - 'GET', - 'courses/{}/epub_exports/{}'.format(self.id, epub_id), + "GET", + "courses/{}/epub_exports/{}".format(self.id, epub_id), _kwargs=combine_kwargs(**kwargs), ) @@ -2415,8 +2415,8 @@ def create_epub_export(self, **kwargs): """ response = self._requester.request( - 'POST', - 'courses/{}/epub_exports/'.format(self.id), + "POST", + "courses/{}/epub_exports/".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -2436,9 +2436,9 @@ def get_grading_periods(self, **kwargs): return PaginatedList( GradingPeriod, self._requester, - 'GET', - 'courses/{}/grading_periods'.format(self.id), - {'course_id': self.id}, + "GET", + "courses/{}/grading_periods".format(self.id), + {"course_id": self.id}, _root="grading_periods", kwargs=combine_kwargs(**kwargs), ) @@ -2456,13 +2456,13 @@ def get_grading_period(self, grading_period, **kwargs): """ response = self._requester.request( - 'GET', - 'courses/{}/grading_periods/{}'.format(self.id, grading_period), + "GET", + "courses/{}/grading_periods/{}".format(self.id, grading_period), _kwargs=combine_kwargs(**kwargs), ) - response_grading_period = response.json()['grading_periods'][0] - response_grading_period.update({'course_id': self.id}) + response_grading_period = response.json()["grading_periods"][0] + response_grading_period.update({"course_id": self.id}) return GradingPeriod(self._requester, response_grading_period) @@ -2481,8 +2481,8 @@ def get_content_exports(self, **kwargs): return PaginatedList( ContentExport, self._requester, - 'GET', - 'courses/{}/content_exports'.format(self.id), + "GET", + "courses/{}/content_exports".format(self.id), kwargs=combine_kwargs(**kwargs), ) @@ -2503,8 +2503,8 @@ def get_content_export(self, content_export, **kwargs): export_id = obj_or_id(content_export, "content_export", (ContentExport,)) response = self._requester.request( - 'GET', - 'courses/{}/content_exports/{}'.format(self.id, export_id), + "GET", + "courses/{}/content_exports/{}".format(self.id, export_id), _kwargs=combine_kwargs(**kwargs), ) @@ -2524,11 +2524,11 @@ def export_content(self, export_type, **kwargs): """ from canvasapi.content_export import ContentExport - kwargs['export_type'] = export_type + kwargs["export_type"] = export_type response = self._requester.request( - 'POST', - 'courses/{}/content_exports'.format(self.id), + "POST", + "courses/{}/content_exports".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -2550,6 +2550,6 @@ def remove(self): :rtype: :class:`canvasapi.course.CourseNickname` """ response = self._requester.request( - 'DELETE', 'users/self/course_nicknames/{}'.format(self.course_id) + "DELETE", "users/self/course_nicknames/{}".format(self.course_id) ) return CourseNickname(self._requester, response.json()) diff --git a/canvasapi/course_epub_export.py b/canvasapi/course_epub_export.py index 2499bb3f..4a24355f 100644 --- a/canvasapi/course_epub_export.py +++ b/canvasapi/course_epub_export.py @@ -8,9 +8,9 @@ @python_2_unicode_compatible class CourseEpubExport(CanvasObject): def __str__(self): - return '{} course_id:({}) epub_id:({}) {} '.format( + return "{} course_id:({}) epub_id:({}) {} ".format( self.name, self.id, - self.epub_export['id'], - self.epub_export['workflow_state'], + self.epub_export["id"], + self.epub_export["workflow_state"], ) diff --git a/canvasapi/current_user.py b/canvasapi/current_user.py index 4e305e34..1aee6813 100644 --- a/canvasapi/current_user.py +++ b/canvasapi/current_user.py @@ -18,7 +18,7 @@ class CurrentUser(User): def __init__(self, _requester): self._requester = _requester - response = self._requester.request('GET', 'users/self') + response = self._requester.request("GET", "users/self") super(CurrentUser, self).__init__(self._requester, response.json()) @@ -60,8 +60,8 @@ def get_groups(self, **kwargs): return PaginatedList( Group, self._requester, - 'GET', - 'users/self/groups', + "GET", + "users/self/groups", _kwargs=combine_kwargs(**kwargs), ) @@ -97,7 +97,7 @@ def get_bookmarks(self, **kwargs): :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.bookmark.Bookmark` """ - return PaginatedList(Bookmark, self._requester, 'GET', 'users/self/bookmarks') + return PaginatedList(Bookmark, self._requester, "GET", "users/self/bookmarks") def create_bookmark(self, name, url, **kwargs): """ @@ -115,8 +115,8 @@ def create_bookmark(self, name, url, **kwargs): from canvasapi.bookmark import Bookmark response = self._requester.request( - 'POST', - 'users/self/bookmarks', + "POST", + "users/self/bookmarks", name=name, url=url, _kwargs=combine_kwargs(**kwargs), @@ -141,7 +141,7 @@ def get_bookmark(self, bookmark): bookmark_id = obj_or_id(bookmark, "bookmark", (Bookmark,)) response = self._requester.request( - 'GET', 'users/self/bookmarks/{}'.format(bookmark_id) + "GET", "users/self/bookmarks/{}".format(bookmark_id) ) return Bookmark(self._requester, response.json()) @@ -161,8 +161,8 @@ def get_favorite_courses(self, **kwargs): return PaginatedList( Course, self._requester, - 'GET', - 'users/self/favorites/courses', + "GET", + "users/self/favorites/courses", _kwargs=combine_kwargs(**kwargs), ) @@ -182,8 +182,8 @@ def get_favorite_groups(self, **kwargs): return PaginatedList( Group, self._requester, - 'GET', - 'users/self/favorites/groups', + "GET", + "users/self/favorites/groups", _kwargs=combine_kwargs(**kwargs), ) @@ -206,13 +206,13 @@ def add_favorite_course(self, course, use_sis_id=False, **kwargs): """ if use_sis_id: course_id = course - uri_str = 'users/self/favorites/courses/sis_course_id:{}' + uri_str = "users/self/favorites/courses/sis_course_id:{}" else: course_id = obj_or_id(course, "course", (Course,)) - uri_str = 'users/self/favorites/courses/{}' + uri_str = "users/self/favorites/courses/{}" response = self._requester.request( - 'POST', uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) + "POST", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) ) return Favorite(self._requester, response.json()) @@ -235,13 +235,13 @@ def add_favorite_group(self, group, use_sis_id=False, **kwargs): """ if use_sis_id: group_id = group - uri_str = 'users/self/favorites/groups/sis_group_id:{}' + uri_str = "users/self/favorites/groups/sis_group_id:{}" else: group_id = obj_or_id(group, "group", (Group,)) - uri_str = 'users/self/favorites/groups/{}' + uri_str = "users/self/favorites/groups/{}" response = self._requester.request( - 'POST', uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) + "POST", uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) ) return Favorite(self._requester, response.json()) @@ -258,9 +258,9 @@ def reset_favorite_courses(self, **kwargs): """ response = self._requester.request( - 'DELETE', 'users/self/favorites/courses', _kwargs=combine_kwargs(**kwargs) + "DELETE", "users/self/favorites/courses", _kwargs=combine_kwargs(**kwargs) ) - return response.json().get('message') == 'OK' + return response.json().get("message") == "OK" def reset_favorite_groups(self, **kwargs): """ @@ -275,6 +275,6 @@ def reset_favorite_groups(self, **kwargs): """ response = self._requester.request( - 'DELETE', 'users/self/favorites/groups', _kwargs=combine_kwargs(**kwargs) + "DELETE", "users/self/favorites/groups", _kwargs=combine_kwargs(**kwargs) ) - return response.json().get('message') == 'OK' + return response.json().get("message") == "OK" diff --git a/canvasapi/discussion_topic.py b/canvasapi/discussion_topic.py index f338cc08..a1e93b0d 100644 --- a/canvasapi/discussion_topic.py +++ b/canvasapi/discussion_topic.py @@ -21,9 +21,9 @@ def _parent_id(self): :rtype: int """ - if hasattr(self, 'course_id'): + if hasattr(self, "course_id"): return self.course_id - elif hasattr(self, 'group_id'): + elif hasattr(self, "group_id"): return self.group_id else: raise ValueError("Discussion Topic does not have a course_id or group_id") @@ -35,10 +35,10 @@ def _parent_type(self): :rtype: str """ - if hasattr(self, 'course_id'): - return 'course' - elif hasattr(self, 'group_id'): - return 'group' + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "group_id"): + return "group" else: raise ValueError("Discussion Topic does not have a course_id or group_id") @@ -52,12 +52,12 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', '{}s/{}'.format(self._parent_type, self._parent_id) + "GET", "{}s/{}".format(self._parent_type, self._parent_id) ) - if self._parent_type == 'group': + if self._parent_type == "group": return Group(self._requester, response.json()) - elif self._parent_type == 'course': + elif self._parent_type == "course": return Course(self._requester, response.json()) def delete(self): @@ -74,12 +74,12 @@ def delete(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}s/{}/discussion_topics/{}'.format( + "DELETE", + "{}s/{}/discussion_topics/{}".format( self._parent_type, self._parent_id, self.id ), ) - return 'deleted_at' in response.json() + return "deleted_at" in response.json() def update(self, **kwargs): """ @@ -94,8 +94,8 @@ def update(self, **kwargs): :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` """ response = self._requester.request( - 'PUT', - '{}s/{}/discussion_topics/{}'.format( + "PUT", + "{}s/{}/discussion_topics/{}".format( self._parent_type, self._parent_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -115,8 +115,8 @@ def post_entry(self, **kwargs): :rtype: :class:`canvasapi.discussion_topic.DiscussionEntry` """ response = self._requester.request( - 'POST', - '{}s/{}/discussion_topics/{}/entries'.format( + "POST", + "{}s/{}/discussion_topics/{}/entries".format( self._parent_type, self._parent_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -124,8 +124,8 @@ def post_entry(self, **kwargs): response_json = response.json() response_json.update( { - 'discussion_id': self.id, - '{}_id'.format(self._parent_type): self._parent_id, + "discussion_id": self.id, + "{}_id".format(self._parent_type): self._parent_id, } ) return DiscussionEntry(self._requester, response_json) @@ -171,13 +171,13 @@ def get_topic_entries(self, **kwargs): return PaginatedList( DiscussionEntry, self._requester, - 'GET', - '{}s/{}/discussion_topics/{}/entries'.format( + "GET", + "{}s/{}/discussion_topics/{}/entries".format( self._parent_type, self._parent_id, self.id ), { - 'discussion_id': self.id, - '{}_id'.format(self._parent_type): self._parent_id, + "discussion_id": self.id, + "{}_id".format(self._parent_type): self._parent_id, }, _kwargs=combine_kwargs(**kwargs), ) @@ -235,13 +235,13 @@ def get_entries(self, ids, **kwargs): return PaginatedList( DiscussionEntry, self._requester, - 'GET', - '{}s/{}/discussion_topics/{}/entry_list'.format( + "GET", + "{}s/{}/discussion_topics/{}/entry_list".format( self._parent_type, self._parent_id, self.id ), { - 'discussion_id': self.id, - '{}_id'.format(self._parent_type): self._parent_id, + "discussion_id": self.id, + "{}_id".format(self._parent_type): self._parent_id, }, _kwargs=combine_kwargs(**kwargs), ) @@ -259,8 +259,8 @@ def mark_as_read(self): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/discussion_topics/{}/read'.format( + "PUT", + "{}s/{}/discussion_topics/{}/read".format( self._parent_type, self._parent_id, self.id ), ) @@ -279,8 +279,8 @@ def mark_as_unread(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}s/{}/discussion_topics/{}/read'.format( + "DELETE", + "{}s/{}/discussion_topics/{}/read".format( self._parent_type, self._parent_id, self.id ), ) @@ -299,8 +299,8 @@ def mark_entries_as_read(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/discussion_topics/{}/read_all'.format( + "PUT", + "{}s/{}/discussion_topics/{}/read_all".format( self._parent_type, self._parent_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -320,8 +320,8 @@ def mark_entries_as_unread(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}s/{}/discussion_topics/{}/read_all'.format( + "DELETE", + "{}s/{}/discussion_topics/{}/read_all".format( self._parent_type, self._parent_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -341,8 +341,8 @@ def subscribe(self): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/discussion_topics/{}/subscribed'.format( + "PUT", + "{}s/{}/discussion_topics/{}/subscribed".format( self._parent_type, self._parent_id, self.id ), ) @@ -361,8 +361,8 @@ def unsubscribe(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}s/{}/discussion_topics/{}/subscribed'.format( + "DELETE", + "{}s/{}/discussion_topics/{}/subscribed".format( self._parent_type, self._parent_id, self.id ), ) @@ -381,9 +381,9 @@ def _discussion_parent_id(self): :rtype: int """ - if hasattr(self, 'course_id'): + if hasattr(self, "course_id"): return self.course_id - elif hasattr(self, 'group_id'): + elif hasattr(self, "group_id"): return self.group_id else: raise ValueError("Discussion Topic does not have a course_id or group_id") @@ -395,10 +395,10 @@ def _discussion_parent_type(self): :rtype: str """ - if hasattr(self, 'course_id'): - return 'course' - elif hasattr(self, 'group_id'): - return 'group' + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "group_id"): + return "group" else: raise ValueError("Discussion Topic does not have a course_id or group_id") @@ -410,8 +410,8 @@ def get_discussion(self): """ response = self._requester.request( - 'GET', - '{}s/{}/discussion_topics/{}'.format( + "GET", + "{}s/{}/discussion_topics/{}".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, @@ -420,7 +420,7 @@ def get_discussion(self): response_json = response.json() response_json.update( - {'{}_id'.format(self._discussion_parent_type): self._discussion_parent_id} + {"{}_id".format(self._discussion_parent_type): self._discussion_parent_id} ) return DiscussionTopic(self._requester, response.json()) @@ -438,8 +438,8 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/discussion_topics/{}/entries/{}'.format( + "PUT", + "{}s/{}/discussion_topics/{}/entries/{}".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, @@ -448,10 +448,10 @@ def update(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - if response.json().get('updated_at'): + if response.json().get("updated_at"): super(DiscussionEntry, self).set_attributes(response.json()) - return 'updated_at' in response.json() + return "updated_at" in response.json() def delete(self, **kwargs): """ @@ -466,8 +466,8 @@ def delete(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}s/{}/discussion_topics/{}/entries/{}'.format( + "DELETE", + "{}s/{}/discussion_topics/{}/entries/{}".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, @@ -475,7 +475,7 @@ def delete(self, **kwargs): ), _kwargs=combine_kwargs(**kwargs), ) - return 'deleted_at' in response.json() + return "deleted_at" in response.json() def post_reply(self, **kwargs): """ @@ -491,8 +491,8 @@ def post_reply(self, **kwargs): :rtype: :class:`canvasapi.discussion_topic.DiscussionEntry` """ response = self._requester.request( - 'POST', - '{}s/{}/discussion_topics/{}/entries/{}/replies'.format( + "POST", + "{}s/{}/discussion_topics/{}/entries/{}/replies".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, @@ -549,16 +549,16 @@ def get_replies(self, **kwargs): return PaginatedList( DiscussionEntry, self._requester, - 'GET', - '{}s/{}/discussion_topics/{}/entries/{}/replies'.format( + "GET", + "{}s/{}/discussion_topics/{}/entries/{}/replies".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, self.id, ), { - 'discussion_id': self.discussion_id, - '{}_id'.format( + "discussion_id": self.discussion_id, + "{}_id".format( self._discussion_parent_type ): self._discussion_parent_id, }, @@ -579,8 +579,8 @@ def mark_as_read(self): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}s/{}/discussion_topics/{}/entries/{}/read'.format( + "PUT", + "{}s/{}/discussion_topics/{}/entries/{}/read".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, @@ -605,8 +605,8 @@ def mark_as_unread(self): :rtype: bool """ response = self._requester.request( - 'DELETE', - '{}s/{}/discussion_topics/{}/entries/{}/read'.format( + "DELETE", + "{}s/{}/discussion_topics/{}/entries/{}/read".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, @@ -635,8 +635,8 @@ def rate(self, rating, **kwargs): raise ValueError("`rating` must be 0 or 1.") response = self._requester.request( - 'POST', - '{}s/{}/discussion_topics/{}/entries/{}/rating'.format( + "POST", + "{}s/{}/discussion_topics/{}/entries/{}/rating".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, diff --git a/canvasapi/enrollment.py b/canvasapi/enrollment.py index 8f7daf42..c5ca34ca 100644 --- a/canvasapi/enrollment.py +++ b/canvasapi/enrollment.py @@ -24,18 +24,18 @@ def deactivate(self, task): :type task: str :rtype: :class:`canvasapi.enrollment.Enrollment` """ - ALLOWED_TASKS = ['conclude', 'delete', 'inactivate', 'deactivate'] + ALLOWED_TASKS = ["conclude", "delete", "inactivate", "deactivate"] if task not in ALLOWED_TASKS: raise ValueError( - '{} is not a valid task. Please use one of the following: {}'.format( - task, ','.join(ALLOWED_TASKS) + "{} is not a valid task. Please use one of the following: {}".format( + task, ",".join(ALLOWED_TASKS) ) ) response = self._requester.request( - 'DELETE', - 'courses/{}/enrollments/{}'.format(self.course_id, self.id), + "DELETE", + "courses/{}/enrollments/{}".format(self.course_id, self.id), task=task, ) return Enrollment(self._requester, response.json()) @@ -50,7 +50,7 @@ def reactivate(self): :rtype: :class:`canvasapi.enrollment.Enrollment` """ response = self._requester.request( - 'PUT', - 'courses/{}/enrollments/{}/reactivate'.format(self.course_id, self.id), + "PUT", + "courses/{}/enrollments/{}/reactivate".format(self.course_id, self.id), ) return Enrollment(self._requester, response.json()) diff --git a/canvasapi/enrollment_term.py b/canvasapi/enrollment_term.py index dcebcf4b..0172b234 100644 --- a/canvasapi/enrollment_term.py +++ b/canvasapi/enrollment_term.py @@ -21,7 +21,7 @@ def delete(self): :rtype: :class:`canvasapi.enrollment_term.EnrollmentTerm` """ response = self._requester.request( - 'DELETE', 'accounts/{}/terms/{}'.format(self.account_id, self.id) + "DELETE", "accounts/{}/terms/{}".format(self.account_id, self.id) ) return EnrollmentTerm(self._requester, response.json()) @@ -35,8 +35,8 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.enrollment_term.EnrollmentTerm` """ response = self._requester.request( - 'PUT', - 'accounts/{}/terms/{}'.format(self.account_id, self.id), + "PUT", + "accounts/{}/terms/{}".format(self.account_id, self.id), _kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/exceptions.py b/canvasapi/exceptions.py index f3278a6f..e68f232a 100644 --- a/canvasapi/exceptions.py +++ b/canvasapi/exceptions.py @@ -11,13 +11,13 @@ class CanvasException(Exception): # pragma: no cover def __init__(self, message): if isinstance(message, dict): - self.error_report_id = message.get('error_report_id', None) + self.error_report_id = message.get("error_report_id", None) - errors = message.get('errors', False) + errors = message.get("errors", False) if errors: self.message = errors else: - self.message = ('Something went wrong. ', message) + self.message = ("Something went wrong. ", message) else: self.message = message diff --git a/canvasapi/external_tool.py b/canvasapi/external_tool.py index e6216869..3e2fa124 100644 --- a/canvasapi/external_tool.py +++ b/canvasapi/external_tool.py @@ -19,9 +19,9 @@ def parent_id(self): :rtype: int """ - if hasattr(self, 'course_id'): + if hasattr(self, "course_id"): return self.course_id - elif hasattr(self, 'account_id'): + elif hasattr(self, "account_id"): return self.account_id else: raise ValueError("ExternalTool does not have a course_id or account_id") @@ -33,10 +33,10 @@ def parent_type(self): :rtype: str """ - if hasattr(self, 'course_id'): - return 'course' - elif hasattr(self, 'account_id'): - return 'account' + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "account_id"): + return "account" else: raise ValueError("ExternalTool does not have a course_id or account_id") @@ -50,12 +50,12 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', '{}s/{}'.format(self.parent_type, self.parent_id) + "GET", "{}s/{}".format(self.parent_type, self.parent_id) ) - if self.parent_type == 'account': + if self.parent_type == "account": return Account(self._requester, response.json()) - elif self.parent_type == 'course': + elif self.parent_type == "course": return Course(self._requester, response.json()) def delete(self): @@ -70,8 +70,8 @@ def delete(self): :rtype: :class:`canvasapi.external_tool.ExternalTool` """ response = self._requester.request( - 'DELETE', - '{}s/{}/external_tools/{}'.format( + "DELETE", + "{}s/{}/external_tools/{}".format( self.parent_type, self.parent_id, self.id ), ) @@ -90,15 +90,15 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.external_tool.ExternalTool` """ response = self._requester.request( - 'PUT', - '{}s/{}/external_tools/{}'.format( + "PUT", + "{}s/{}/external_tools/{}".format( self.parent_type, self.parent_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - if 'name' in response_json: + if "name" in response_json: super(ExternalTool, self).set_attributes(response_json) return ExternalTool(self._requester, response_json) @@ -114,15 +114,15 @@ def get_sessionless_launch_url(self, **kwargs): :rtype: str """ - kwargs['id'] = self.id + kwargs["id"] = self.id response = self._requester.request( - 'GET', - '{}s/{}/external_tools/sessionless_launch'.format( + "GET", + "{}s/{}/external_tools/sessionless_launch".format( self.parent_type, self.parent_id ), _kwargs=combine_kwargs(**kwargs), ) try: - return response.json()['url'] + return response.json()["url"] except KeyError: - raise CanvasException('Canvas did not respond with a valid URL') + raise CanvasException("Canvas did not respond with a valid URL") diff --git a/canvasapi/favorite.py b/canvasapi/favorite.py index ffd19278..6688c557 100644 --- a/canvasapi/favorite.py +++ b/canvasapi/favorite.py @@ -24,13 +24,13 @@ def remove(self, **kwargs): """ if self.context_type == "course": id = self.context_id - uri_str = 'users/self/favorites/courses/{}' + uri_str = "users/self/favorites/courses/{}" elif self.context_type == "group": id = self.context_id - uri_str = 'users/self/favorites/groups/{}' + uri_str = "users/self/favorites/groups/{}" response = self._requester.request( - 'DELETE', uri_str.format(id), _kwargs=combine_kwargs(**kwargs) + "DELETE", uri_str.format(id), _kwargs=combine_kwargs(**kwargs) ) return Favorite(self._requester, response.json()) diff --git a/canvasapi/file.py b/canvasapi/file.py index 63597168..04b3356b 100644 --- a/canvasapi/file.py +++ b/canvasapi/file.py @@ -19,7 +19,7 @@ def delete(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request('DELETE', 'files/{}'.format(self.id)) + response = self._requester.request("DELETE", "files/{}".format(self.id)) return File(self._requester, response.json()) def get_contents(self): @@ -28,7 +28,7 @@ def get_contents(self): :rtype: str """ - response = self._requester.request('GET', _url=self.url) + response = self._requester.request("GET", _url=self.url) return response.text def download(self, location): @@ -38,7 +38,7 @@ def download(self, location): :param location: The path to download to. :type location: str """ - response = self._requester.request('GET', _url=self.url) + response = self._requester.request("GET", _url=self.url) - with open(location, 'wb') as file_out: + with open(location, "wb") as file_out: file_out.write(response.content) diff --git a/canvasapi/folder.py b/canvasapi/folder.py index 614a1ab5..2b4412c9 100644 --- a/canvasapi/folder.py +++ b/canvasapi/folder.py @@ -52,8 +52,8 @@ def get_files(self, **kwargs): return PaginatedList( File, self._requester, - 'GET', - 'folders/{}/files'.format(self.id), + "GET", + "folders/{}/files".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -68,7 +68,7 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'DELETE', 'folders/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "DELETE", "folders/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) return Folder(self._requester, response.json()) @@ -105,7 +105,7 @@ def get_folders(self, **kwargs): :class:`canvasapi.folder.Folder` """ return PaginatedList( - Folder, self._requester, 'GET', 'folders/{}/folders'.format(self.id) + Folder, self._requester, "GET", "folders/{}/folders".format(self.id) ) def create_folder(self, name, **kwargs): @@ -120,8 +120,8 @@ def create_folder(self, name, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'POST', - 'folders/{}/folders'.format(self.id), + "POST", + "folders/{}/folders".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) @@ -140,7 +140,7 @@ def upload(self, file, **kwargs): and the JSON response from the API. :rtype: tuple """ - my_path = 'folders/{}/files'.format(self.id) + my_path = "folders/{}/files".format(self.id) return Uploader(self._requester, my_path, file, **kwargs).start() def update(self, **kwargs): @@ -153,10 +153,10 @@ def update(self, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'PUT', 'folders/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "folders/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - if 'name' in response.json(): + if "name" in response.json(): super(Folder, self).set_attributes(response.json()) return Folder(self._requester, response.json()) @@ -176,11 +176,11 @@ def copy_file(self, source_file, **kwargs): from canvasapi.file import File file_id = obj_or_id(source_file, "source_file", (File,)) - kwargs['source_file_id'] = file_id + kwargs["source_file_id"] = file_id response = self._requester.request( - 'POST', - 'folders/{}/copy_file'.format(self.id), + "POST", + "folders/{}/copy_file".format(self.id), _kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/grading_period.py b/canvasapi/grading_period.py index 9108aa99..c43d91c3 100644 --- a/canvasapi/grading_period.py +++ b/canvasapi/grading_period.py @@ -10,7 +10,7 @@ @python_2_unicode_compatible class GradingPeriod(CanvasObject): def __str__(self): - return '{} ({})'.format(self.title, self.id) + return "{} ({})".format(self.title, self.id) def update(self, grading_period, **kwargs): """ @@ -25,25 +25,25 @@ def update(self, grading_period, **kwargs): :rtype: :class:`canvasapi.grading_period.GradingPeriod` """ if isinstance(grading_period, list): - kwargs['grading_periods'] = grading_period + kwargs["grading_periods"] = grading_period else: raise RequiredFieldMissing("List is required") - if 'start_date' not in kwargs['grading_periods'][0]: + if "start_date" not in kwargs["grading_periods"][0]: raise RequiredFieldMissing("start_date is missing") - if 'end_date' not in kwargs['grading_periods'][0]: + if "end_date" not in kwargs["grading_periods"][0]: raise RequiredFieldMissing("end_date is missing") response = self._requester.request( - 'PUT', - 'courses/{}/grading_periods/{}'.format(self.course_id, self.id), + "PUT", + "courses/{}/grading_periods/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - grading_period = response_json['grading_periods'][0] - grading_period.update({'course_id': self.course_id}) + grading_period = response_json["grading_periods"][0] + grading_period.update({"course_id": self.course_id}) return GradingPeriod(self._requester, grading_period) @@ -58,8 +58,8 @@ def delete(self, **kwargs): :rtype: int """ response = self._requester.request( - 'DELETE', - 'courses/{}/grading_periods/{}'.format(self.course_id, self.id), + "DELETE", + "courses/{}/grading_periods/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/group.py b/canvasapi/group.py index 99dc880e..f51a9db6 100644 --- a/canvasapi/group.py +++ b/canvasapi/group.py @@ -32,17 +32,17 @@ def create_page(self, wiki_page, **kwargs): """ from canvasapi.course import Page - if isinstance(wiki_page, dict) and 'title' in wiki_page: - kwargs['wiki_page'] = wiki_page + if isinstance(wiki_page, dict) and "title" in wiki_page: + kwargs["wiki_page"] = wiki_page else: raise RequiredFieldMissing("Dictionary with key 'title' is required.") response = self._requester.request( - 'POST', 'groups/{}/pages'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "POST", "groups/{}/pages".format(self.id), _kwargs=combine_kwargs(**kwargs) ) page_json = response.json() - page_json.update({'group_id': self.id}) + page_json.update({"group_id": self.id}) return Page(self._requester, page_json) @@ -58,12 +58,12 @@ def edit_front_page(self, **kwargs): from canvasapi.course import Page response = self._requester.request( - 'PUT', - 'groups/{}/front_page'.format(self.id), + "PUT", + "groups/{}/front_page".format(self.id), _kwargs=combine_kwargs(**kwargs), ) page_json = response.json() - page_json.update({'group_id': self.id}) + page_json.update({"group_id": self.id}) return Page(self._requester, page_json) @@ -79,10 +79,10 @@ def show_front_page(self): from canvasapi.course import Page response = self._requester.request( - 'GET', 'groups/{}/front_page'.format(self.id) + "GET", "groups/{}/front_page".format(self.id) ) page_json = response.json() - page_json.update({'group_id': self.id}) + page_json.update({"group_id": self.id}) return Page(self._requester, page_json) @@ -101,10 +101,10 @@ def get_page(self, url): from canvasapi.course import Page response = self._requester.request( - 'GET', 'groups/{}/pages/{}'.format(self.id, url) + "GET", "groups/{}/pages/{}".format(self.id, url) ) page_json = response.json() - page_json.update({'group_id': self.id}) + page_json.update({"group_id": self.id}) return Page(self._requester, page_json) @@ -123,9 +123,9 @@ def get_pages(self, **kwargs): return PaginatedList( Page, self._requester, - 'GET', - 'groups/{}/pages'.format(self.id), - {'group_id': self.id}, + "GET", + "groups/{}/pages".format(self.id), + {"group_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -139,7 +139,7 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.group.Group` """ response = self._requester.request( - 'PUT', 'groups/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "groups/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) return Group(self._requester, response.json()) @@ -152,7 +152,7 @@ def delete(self): :rtype: :class:`canvasapi.group.Group` """ - response = self._requester.request('DELETE', 'groups/{}'.format(self.id)) + response = self._requester.request("DELETE", "groups/{}".format(self.id)) return Group(self._requester, response.json()) def invite(self, invitees): @@ -171,8 +171,8 @@ def invite(self, invitees): return PaginatedList( GroupMembership, self._requester, - 'POST', - 'groups/{}/invite'.format(self.id), + "POST", + "groups/{}/invite".format(self.id), invitees=invitees, ) @@ -213,8 +213,8 @@ def get_users(self, **kwargs): return PaginatedList( User, self._requester, - 'GET', - 'groups/{}/users'.format(self.id), + "GET", + "groups/{}/users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -235,7 +235,7 @@ def remove_user(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'DELETE', 'groups/{}/users/{}'.format(self.id, user_id) + "DELETE", "groups/{}/users/{}".format(self.id, user_id) ) return User(self._requester, response.json()) @@ -259,7 +259,7 @@ def upload(self, file, **kwargs): from canvasapi.upload import Uploader return Uploader( - self._requester, 'groups/{}/files'.format(self.id), file, **kwargs + self._requester, "groups/{}/files".format(self.id), file, **kwargs ).start() def preview_html(self, html): @@ -274,9 +274,9 @@ def preview_html(self, html): :rtype: str """ response = self._requester.request( - 'POST', 'groups/{}/preview_html'.format(self.id), html=html + "POST", "groups/{}/preview_html".format(self.id), html=html ) - return response.json().get('html', '') + return response.json().get("html", "") def get_activity_stream_summary(self): """ @@ -288,7 +288,7 @@ def get_activity_stream_summary(self): :rtype: dict """ response = self._requester.request( - 'GET', 'groups/{}/activity_stream/summary'.format(self.id) + "GET", "groups/{}/activity_stream/summary".format(self.id) ) return response.json() @@ -327,8 +327,8 @@ def get_memberships(self, **kwargs): return PaginatedList( GroupMembership, self._requester, - 'GET', - 'groups/{}/memberships'.format(self.id), + "GET", + "groups/{}/memberships".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -352,7 +352,7 @@ def get_membership(self, user, membership_type): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'GET', 'groups/{}/{}/{}'.format(self.id, membership_type, user_id) + "GET", "groups/{}/{}/{}".format(self.id, membership_type, user_id) ) return GroupMembership(self._requester, response.json()) @@ -374,8 +374,8 @@ def create_membership(self, user, **kwargs): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'POST', - 'groups/{}/memberships'.format(self.id), + "POST", + "groups/{}/memberships".format(self.id), user_id=user_id, _kwargs=combine_kwargs(**kwargs), ) @@ -398,8 +398,8 @@ def update_membership(self, user, **kwargs): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'PUT', - 'groups/{}/users/{}'.format(self.id, user_id), + "PUT", + "groups/{}/users/{}".format(self.id, user_id), _kwargs=combine_kwargs(**kwargs), ) return GroupMembership(self._requester, response.json()) @@ -419,11 +419,11 @@ def get_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', 'groups/{}/discussion_topics/{}'.format(self.id, topic_id) + "GET", "groups/{}/discussion_topics/{}".format(self.id, topic_id) ) response_json = response.json() - response_json.update({'group_id': self.id}) + response_json.update({"group_id": self.id}) return DiscussionTopic(self._requester, response_json) @@ -444,8 +444,8 @@ def get_file(self, file, **kwargs): file_id = obj_or_id(file, "file", (File,)) response = self._requester.request( - 'GET', - 'groups/{}/files/{}'.format(self.id, file_id), + "GET", + "groups/{}/files/{}".format(self.id, file_id), _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) @@ -465,7 +465,7 @@ def get_full_discussion_topic(self, topic): topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - 'GET', 'groups/{}/discussion_topics/{}/view'.format(self.id, topic_id) + "GET", "groups/{}/discussion_topics/{}/view".format(self.id, topic_id) ) return response.json() @@ -483,9 +483,9 @@ def get_discussion_topics(self, **kwargs): return PaginatedList( DiscussionTopic, self._requester, - 'GET', - 'groups/{}/discussion_topics'.format(self.id), - {'group_id': self.id}, + "GET", + "groups/{}/discussion_topics".format(self.id), + {"group_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -499,13 +499,13 @@ def create_discussion_topic(self, **kwargs): :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` """ response = self._requester.request( - 'POST', - 'groups/{}/discussion_topics'.format(self.id), + "POST", + "groups/{}/discussion_topics".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'group_id': self.id}) + response_json.update({"group_id": self.id}) return DiscussionTopic(self._requester, response_json) @@ -533,10 +533,10 @@ def reorder_pinned_topics(self, order): raise ValueError("Param `order` must be a list, tuple, or string.") response = self._requester.request( - 'POST', 'groups/{}/discussion_topics/reorder'.format(self.id), order=order + "POST", "groups/{}/discussion_topics/reorder".format(self.id), order=order ) - return response.json().get('reorder') + return response.json().get("reorder") def list_external_feeds(self, **kwargs): """ @@ -575,8 +575,8 @@ def get_external_feeds(self, **kwargs): return PaginatedList( ExternalFeed, self._requester, - 'GET', - 'groups/{}/external_feeds'.format(self.id), + "GET", + "groups/{}/external_feeds".format(self.id), ) def create_external_feed(self, url, **kwargs): @@ -593,8 +593,8 @@ def create_external_feed(self, url, **kwargs): from canvasapi.external_feed import ExternalFeed response = self._requester.request( - 'POST', - 'groups/{}/external_feeds'.format(self.id), + "POST", + "groups/{}/external_feeds".format(self.id), url=url, _kwargs=combine_kwargs(**kwargs), ) @@ -617,7 +617,7 @@ def delete_external_feed(self, feed): feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) response = self._requester.request( - 'DELETE', 'groups/{}/external_feeds/{}'.format(self.id, feed_id) + "DELETE", "groups/{}/external_feeds/{}".format(self.id, feed_id) ) return ExternalFeed(self._requester, response.json()) @@ -658,8 +658,8 @@ def get_files(self, **kwargs): return PaginatedList( File, self._requester, - 'GET', - 'groups/{}/files'.format(self.id), + "GET", + "groups/{}/files".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -678,7 +678,7 @@ def get_folder(self, folder): folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - 'GET', 'groups/{}/folders/{}'.format(self.id, folder_id) + "GET", "groups/{}/folders/{}".format(self.id, folder_id) ) return Folder(self._requester, response.json()) @@ -717,7 +717,7 @@ def get_folders(self, **kwargs): :class:`canvasapi.folder.Folder` """ return PaginatedList( - Folder, self._requester, 'GET', 'groups/{}/folders'.format(self.id) + Folder, self._requester, "GET", "groups/{}/folders".format(self.id) ) def create_folder(self, name, **kwargs): @@ -732,8 +732,8 @@ def create_folder(self, name, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'POST', - 'groups/{}/folders'.format(self.id), + "POST", + "groups/{}/folders".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) @@ -776,9 +776,9 @@ def get_tabs(self, **kwargs): return PaginatedList( Tab, self._requester, - 'GET', - 'groups/{}/tabs'.format(self.id), - {'group_id': self.id}, + "GET", + "groups/{}/tabs".format(self.id), + {"group_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -797,20 +797,20 @@ def create_content_migration(self, migration_type, **kwargs): from canvasapi.content_migration import ContentMigration, Migrator if isinstance(migration_type, Migrator): - kwargs['migration_type'] = migration_type.type + kwargs["migration_type"] = migration_type.type elif isinstance(migration_type, string_types): - kwargs['migration_type'] = migration_type + kwargs["migration_type"] = migration_type else: - raise TypeError('Parameter migration_type must be of type Migrator or str') + raise TypeError("Parameter migration_type must be of type Migrator or str") response = self._requester.request( - 'POST', - 'groups/{}/content_migrations'.format(self.id), + "POST", + "groups/{}/content_migrations".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'group_id': self.id}) + response_json.update({"group_id": self.id}) return ContentMigration(self._requester, response_json) @@ -833,13 +833,13 @@ def get_content_migration(self, content_migration, **kwargs): ) response = self._requester.request( - 'GET', - 'groups/{}/content_migrations/{}'.format(self.id, migration_id), + "GET", + "groups/{}/content_migrations/{}".format(self.id, migration_id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'group_id': self.id}) + response_json.update({"group_id": self.id}) return ContentMigration(self._requester, response_json) @@ -858,9 +858,9 @@ def get_content_migrations(self, **kwargs): return PaginatedList( ContentMigration, self._requester, - 'GET', - 'groups/{}/content_migrations'.format(self.id), - {'group_id': self.id}, + "GET", + "groups/{}/content_migrations".format(self.id), + {"group_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -879,8 +879,8 @@ def get_migration_systems(self, **kwargs): return PaginatedList( Migrator, self._requester, - 'GET', - 'groups/{}/content_migrations/migrators'.format(self.id), + "GET", + "groups/{}/content_migrations/migrators".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -901,10 +901,10 @@ def get_assignment_override(self, assignment, **kwargs): assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) response = self._requester.request( - 'GET', 'groups/{}/assignments/{}/override'.format(self.id, assignment_id) + "GET", "groups/{}/assignments/{}/override".format(self.id, assignment_id) ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return AssignmentOverride(self._requester, response_json) @@ -923,8 +923,8 @@ def get_content_exports(self, **kwargs): return PaginatedList( ContentExport, self._requester, - 'GET', - 'groups/{}/content_exports'.format(self.id), + "GET", + "groups/{}/content_exports".format(self.id), kwargs=combine_kwargs(**kwargs), ) @@ -945,8 +945,8 @@ def get_content_export(self, content_export, **kwargs): export_id = obj_or_id(content_export, "content_export", (ContentExport,)) response = self._requester.request( - 'GET', - 'groups/{}/content_exports/{}'.format(self.id, export_id), + "GET", + "groups/{}/content_exports/{}".format(self.id, export_id), _kwargs=combine_kwargs(**kwargs), ) @@ -966,11 +966,11 @@ def export_content(self, export_type, **kwargs): """ from canvasapi.content_export import ContentExport - kwargs['export_type'] = export_type + kwargs["export_type"] = export_type response = self._requester.request( - 'POST', - 'groups/{}/content_exports'.format(self.id), + "POST", + "groups/{}/content_exports".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -992,8 +992,8 @@ def update(self, **kwargs): """ response = self._requester.request( - 'PUT', - 'groups/{}/memberships/{}'.format(self.group_id, self.id), + "PUT", + "groups/{}/memberships/{}".format(self.group_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return GroupMembership(self._requester, response.json()) @@ -1016,7 +1016,7 @@ def remove_user(self, user): user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - 'DELETE', 'groups/{}/users/{}'.format(self.id, user_id) + "DELETE", "groups/{}/users/{}".format(self.id, user_id) ) return response.json() @@ -1031,7 +1031,7 @@ def remove_self(self): :rtype: dict """ response = self._requester.request( - 'DELETE', 'groups/{}/memberships/self'.format(self.id) + "DELETE", "groups/{}/memberships/self".format(self.id) ) return response.json() @@ -1051,8 +1051,8 @@ def create_group(self, **kwargs): :rtype: :class:`canvasapi.group.Group` """ response = self._requester.request( - 'POST', - 'group_categories/{}/groups'.format(self.id), + "POST", + "group_categories/{}/groups".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Group(self._requester, response.json()) @@ -1067,8 +1067,8 @@ def update(self, **kwargs): :rtype: :class:`canvasapi.group.GroupCategory` """ response = self._requester.request( - 'PUT', - 'group_categories/{}'.format(self.id), + "PUT", + "group_categories/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return GroupCategory(self._requester, response.json()) @@ -1083,7 +1083,7 @@ def delete(self): :rtype: empty dict """ response = self._requester.request( - 'DELETE', 'group_categories/{}'.format(self.id) + "DELETE", "group_categories/{}".format(self.id) ) return response.json() @@ -1120,7 +1120,7 @@ def get_groups(self, **kwargs): :class:`canvasapi.group.Group` """ return PaginatedList( - Group, self._requester, 'GET', 'group_categories/{}/groups'.format(self.id) + Group, self._requester, "GET", "group_categories/{}/groups".format(self.id) ) def list_users(self, **kwargs): @@ -1160,8 +1160,8 @@ def get_users(self, **kwargs): return PaginatedList( User, self._requester, - 'GET', - 'group_categories/{}/users'.format(self.id), + "GET", + "group_categories/{}/users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -1182,11 +1182,11 @@ def assign_members(self, sync=False): return PaginatedList( User, self._requester, - 'POST', - 'group_categories/{}/assign_unassigned_members'.format(self.id), + "POST", + "group_categories/{}/assign_unassigned_members".format(self.id), ) else: response = self._requester.request( - 'POST', 'group_categories/{}/assign_unassigned_members'.format(self.id) + "POST", "group_categories/{}/assign_unassigned_members".format(self.id) ) return Progress(self._requester, response.json()) diff --git a/canvasapi/login.py b/canvasapi/login.py index d1948208..e43659e4 100644 --- a/canvasapi/login.py +++ b/canvasapi/login.py @@ -21,7 +21,7 @@ def delete(self): :rtype: :class:`canvasapi.login.Login` """ response = self._requester.request( - 'DELETE', 'users/{}/logins/{}'.format(self.user_id, self.id) + "DELETE", "users/{}/logins/{}".format(self.user_id, self.id) ) return Login(self._requester, response.json()) @@ -35,8 +35,8 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.login.Login` """ response = self._requester.request( - 'PUT', - 'accounts/{}/logins/{}'.format(self.account_id, self.id), + "PUT", + "accounts/{}/logins/{}".format(self.account_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return Login(self._requester, response.json()) diff --git a/canvasapi/module.py b/canvasapi/module.py index 6d526ce6..fe05a735 100644 --- a/canvasapi/module.py +++ b/canvasapi/module.py @@ -24,12 +24,12 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.module.Module` """ response = self._requester.request( - 'PUT', - 'courses/{}/modules/{}'.format(self.course_id, self.id), + "PUT", + "courses/{}/modules/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) module_json = response.json() - module_json.update({'course_id': self.course_id}) + module_json.update({"course_id": self.course_id}) return Module(self._requester, module_json) @@ -43,10 +43,10 @@ def delete(self): :rtype: :class:`canvasapi.module.Module` """ response = self._requester.request( - 'DELETE', 'courses/{}/modules/{}'.format(self.course_id, self.id) + "DELETE", "courses/{}/modules/{}".format(self.course_id, self.id) ) module_json = response.json() - module_json.update({'course_id': self.course_id}) + module_json.update({"course_id": self.course_id}) return Module(self._requester, module_json) @@ -64,10 +64,10 @@ def relock(self): :rtype: :class:`canvasapi.module.Module` """ response = self._requester.request( - 'PUT', 'courses/{}/modules/{}/relock'.format(self.course_id, self.id) + "PUT", "courses/{}/modules/{}/relock".format(self.course_id, self.id) ) module_json = response.json() - module_json.update({'course_id': self.course_id}) + module_json.update({"course_id": self.course_id}) return Module(self._requester, module_json) @@ -106,9 +106,9 @@ def get_module_items(self, **kwargs): return PaginatedList( ModuleItem, self._requester, - 'GET', - 'courses/{}/modules/{}/items'.format(self.course_id, self.id), - {'course_id': self.course_id}, + "GET", + "courses/{}/modules/{}/items".format(self.course_id, self.id), + {"course_id": self.course_id}, _kwargs=combine_kwargs(**kwargs), ) @@ -127,14 +127,14 @@ def get_module_item(self, module_item, **kwargs): module_item_id = obj_or_id(module_item, "module_item", (ModuleItem,)) response = self._requester.request( - 'GET', - 'courses/{}/modules/{}/items/{}'.format( + "GET", + "courses/{}/modules/{}/items/{}".format( self.course_id, self.id, module_item_id ), _kwargs=combine_kwargs(**kwargs), ) module_item_json = response.json() - module_item_json.update({'course_id': self.course_id}) + module_item_json.update({"course_id": self.course_id}) return ModuleItem(self._requester, module_item_json) @@ -150,9 +150,9 @@ def create_module_item(self, module_item, **kwargs): :returns: The created module item. :rtype: :class:`canvasapi.module.ModuleItem` """ - if isinstance(module_item, dict) and 'type' in module_item: - if 'content_id' in module_item: - kwargs['module_item'] = module_item + if isinstance(module_item, dict) and "type" in module_item: + if "content_id" in module_item: + kwargs["module_item"] = module_item else: raise RequiredFieldMissing( "Dictionary with key 'content_id' is required." @@ -161,12 +161,12 @@ def create_module_item(self, module_item, **kwargs): raise RequiredFieldMissing("Dictionary with key 'type' is required.") response = self._requester.request( - 'POST', - 'courses/{}/modules/{}/items'.format(self.course_id, self.id), + "POST", + "courses/{}/modules/{}/items".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) module_item_json = response.json() - module_item_json.update({'course_id': self.course_id}) + module_item_json.update({"course_id": self.course_id}) return ModuleItem(self._requester, module_item_json) @@ -187,14 +187,14 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.module.ModuleItem` """ response = self._requester.request( - 'PUT', - 'courses/{}/modules/{}/items/{}'.format( + "PUT", + "courses/{}/modules/{}/items/{}".format( self.course_id, self.module_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) module_item_json = response.json() - module_item_json.update({'course_id': self.course_id}) + module_item_json.update({"course_id": self.course_id}) return ModuleItem(self._requester, module_item_json) @@ -208,13 +208,13 @@ def delete(self): :rtype: :class:`canvasapi.module.ModuleItem` """ response = self._requester.request( - 'DELETE', - 'courses/{}/modules/{}/items/{}'.format( + "DELETE", + "courses/{}/modules/{}/items/{}".format( self.course_id, self.module_id, self.id ), ) module_item_json = response.json() - module_item_json.update({'course_id': self.course_id}) + module_item_json.update({"course_id": self.course_id}) return ModuleItem(self._requester, module_item_json) @@ -228,13 +228,13 @@ def complete(self): :rtype: :class:`canvasapi.module.ModuleItem` """ response = self._requester.request( - 'PUT', - 'courses/{}/modules/{}/items/{}/done'.format( + "PUT", + "courses/{}/modules/{}/items/{}/done".format( self.course_id, self.module_id, self.id ), ) module_item_json = response.json() - module_item_json.update({'course_id': self.course_id}) + module_item_json.update({"course_id": self.course_id}) return ModuleItem(self._requester, module_item_json) @@ -248,12 +248,12 @@ def uncomplete(self): :rtype: :class:`canvasapi.module.ModuleItem` """ response = self._requester.request( - 'DELETE', - 'courses/{}/modules/{}/items/{}/done'.format( + "DELETE", + "courses/{}/modules/{}/items/{}/done".format( self.course_id, self.module_id, self.id ), ) module_item_json = response.json() - module_item_json.update({'course_id': self.course_id}) + module_item_json.update({"course_id": self.course_id}) return ModuleItem(self._requester, module_item_json) diff --git a/canvasapi/outcome.py b/canvasapi/outcome.py index b766efb0..451ce5bc 100644 --- a/canvasapi/outcome.py +++ b/canvasapi/outcome.py @@ -24,13 +24,13 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', 'outcomes/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "outcomes/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - if 'id' in response.json(): + if "id" in response.json(): super(Outcome, self).set_attributes(response.json()) - return 'id' in response.json() + return "id" in response.json() @python_2_unicode_compatible @@ -41,10 +41,10 @@ def __str__(self): ) def context_ref(self): - if self.context_type == 'Course': - return 'courses/{}'.format(self.context_id) - elif self.context_type == 'Account': - return 'accounts/{}'.format(self.context_id) + if self.context_type == "Course": + return "courses/{}".format(self.context_id) + elif self.context_type == "Account": + return "accounts/{}".format(self.context_id) def get_outcome(self): """ @@ -56,8 +56,8 @@ def get_outcome(self): :returns: Outcome object that was in the OutcomeLink :rtype: :class:`canvasapi.outcome.Outcome` """ - oid = self.outcome['id'] - response = self._requester.request('GET', 'outcomes/{}'.format(oid)) + oid = self.outcome["id"] + response = self._requester.request("GET", "outcomes/{}".format(oid)) return Outcome(self._requester, response.json()) @@ -75,9 +75,9 @@ def get_outcome_group(self): :returns: Linked outcome group object. :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ - ogid = self.outcome_group['id'] + ogid = self.outcome_group["id"] response = self._requester.request( - 'GET', '{}/outcome_groups/{}'.format(self.context_ref(), ogid) + "GET", "{}/outcome_groups/{}".format(self.context_ref(), ogid) ) return OutcomeGroup(self._requester, response.json()) @@ -89,12 +89,12 @@ def __str__(self): return "{} ({})".format(self.title, self.url) def context_ref(self): - if self.context_type == 'Course': - return 'courses/{}'.format(self.context_id) - elif self.context_type == 'Account': - return 'accounts/{}'.format(self.context_id) + if self.context_type == "Course": + return "courses/{}".format(self.context_id) + elif self.context_type == "Account": + return "accounts/{}".format(self.context_id) elif self.context_type is None: - return 'global' + return "global" def update(self, **kwargs): """ @@ -111,15 +111,15 @@ def update(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - '{}/outcome_groups/{}'.format(self.context_ref(), self.id), + "PUT", + "{}/outcome_groups/{}".format(self.context_ref(), self.id), _kwargs=combine_kwargs(**kwargs), ) - if 'id' in response.json(): + if "id" in response.json(): super(OutcomeGroup, self).set_attributes(response.json()) - return 'id' in response.json() + return "id" in response.json() def delete(self): """ @@ -136,13 +136,13 @@ def delete(self): :rtype: bool """ response = self._requester.request( - 'DELETE', '{}/outcome_groups/{}'.format(self.context_ref(), self.id) + "DELETE", "{}/outcome_groups/{}".format(self.context_ref(), self.id) ) - if 'id' in response.json(): + if "id" in response.json(): super(OutcomeGroup, self).set_attributes(response.json()) - return 'id' in response.json() + return "id" in response.json() def list_linked_outcomes(self, **kwargs): """ @@ -189,8 +189,8 @@ def get_linked_outcomes(self, **kwargs): return PaginatedList( OutcomeLink, self._requester, - 'GET', - '{}/outcome_groups/{}/outcomes'.format(self.context_ref(), self.id), + "GET", + "{}/outcome_groups/{}/outcomes".format(self.context_ref(), self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -214,8 +214,8 @@ def link_existing(self, outcome): outcome_id = obj_or_id(outcome, "outcome", (Outcome,)) response = self._requester.request( - 'PUT', - '{}/outcome_groups/{}/outcomes/{}'.format( + "PUT", + "{}/outcome_groups/{}/outcomes/{}".format( self.context_ref(), self.id, outcome_id ), ) @@ -240,8 +240,8 @@ def link_new(self, title, **kwargs): :rtype: :class:`canvasapi.outcome.OutcomeLink` """ response = self._requester.request( - 'POST', - '{}/outcome_groups/{}/outcomes'.format(self.context_ref(), self.id), + "POST", + "{}/outcome_groups/{}/outcomes".format(self.context_ref(), self.id), title=title, _kwargs=combine_kwargs(**kwargs), ) @@ -268,16 +268,16 @@ def unlink_outcome(self, outcome): outcome_id = obj_or_id(outcome, "outcome", (Outcome,)) response = self._requester.request( - 'DELETE', - '{}/outcome_groups/{}/outcomes/{}'.format( + "DELETE", + "{}/outcome_groups/{}/outcomes/{}".format( self.context_ref(), self.id, outcome_id ), ) - if 'context_id' in response.json(): + if "context_id" in response.json(): super(OutcomeGroup, self).set_attributes(response.json()) - return 'context_id' in response.json() + return "context_id" in response.json() def list_subgroups(self, **kwargs): """ @@ -324,9 +324,9 @@ def get_subgroups(self, **kwargs): return PaginatedList( OutcomeGroup, self._requester, - 'GET', - '{}/outcome_groups/{}/subgroups'.format(self.context_ref(), self.id), - {'context_type': self.context_type, 'context_id': self.context_id}, + "GET", + "{}/outcome_groups/{}/subgroups".format(self.context_ref(), self.id), + {"context_type": self.context_type, "context_id": self.context_id}, _kwargs=combine_kwargs(**kwargs), ) @@ -348,8 +348,8 @@ def create_subgroup(self, title, **kwargs): :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ response = self._requester.request( - 'POST', - '{}/outcome_groups/{}/subgroups'.format(self.context_ref(), self.id), + "POST", + "{}/outcome_groups/{}/subgroups".format(self.context_ref(), self.id), title=title, _kwargs=combine_kwargs(**kwargs), ) @@ -378,8 +378,8 @@ def import_outcome_group(self, outcome_group): ) response = self._requester.request( - 'POST', - '{}/outcome_groups/{}/import'.format(self.context_ref(), self.id), + "POST", + "{}/outcome_groups/{}/import".format(self.context_ref(), self.id), source_outcome_group_id=source_outcome_group_id, ) diff --git a/canvasapi/page.py b/canvasapi/page.py index 1b0b7424..3e523589 100644 --- a/canvasapi/page.py +++ b/canvasapi/page.py @@ -24,13 +24,13 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.page.Page` """ response = self._requester.request( - 'PUT', - '{}s/{}/pages/{}'.format(self.parent_type, self.parent_id, self.url), + "PUT", + "{}s/{}/pages/{}".format(self.parent_type, self.parent_id, self.url), _kwargs=combine_kwargs(**kwargs), ) page_json = response.json() - page_json.update({'course_id': self.course_id}) + page_json.update({"course_id": self.course_id}) super(Page, self).set_attributes(page_json) return self @@ -45,7 +45,7 @@ def delete(self): :rtype: :class:`canvasapi.page.Page` """ response = self._requester.request( - 'DELETE', 'courses/{}/pages/{}'.format(self.course_id, self.url) + "DELETE", "courses/{}/pages/{}".format(self.course_id, self.url) ) return Page(self._requester, response.json()) @@ -56,9 +56,9 @@ def parent_id(self): :rtype: int """ - if hasattr(self, 'course_id'): + if hasattr(self, "course_id"): return self.course_id - elif hasattr(self, 'group_id'): + elif hasattr(self, "group_id"): return self.group_id else: raise ValueError("Page does not have a course_id or group_id") @@ -70,10 +70,10 @@ def parent_type(self): :rtype: str """ - if hasattr(self, 'course_id'): - return 'course' - elif hasattr(self, 'group_id'): - return 'group' + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "group_id"): + return "group" else: raise ValueError("ExternalTool does not have a course_id or group_id") @@ -92,12 +92,12 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', '{}s/{}'.format(self.parent_type, self.parent_id) + "GET", "{}s/{}".format(self.parent_type, self.parent_id) ) - if self.parent_type == 'group': + if self.parent_type == "group": return Group(self._requester, response.json()) - elif self.parent_type == 'course': + elif self.parent_type == "course": return Course(self._requester, response.json()) def show_latest_revision(self, **kwargs): @@ -110,8 +110,8 @@ def show_latest_revision(self, **kwargs): :rtype: :class:`canvasapi.pagerevision.PageRevision` """ response = self._requester.request( - 'GET', - '{}s/{}/pages/{}/revisions/latest'.format( + "GET", + "{}s/{}/pages/{}/revisions/latest".format( self.parent_type, self.parent_id, self.url ), _kwargs=combine_kwargs(**kwargs), @@ -134,17 +134,17 @@ def get_revision_by_id(self, revision, **kwargs): revision_id = obj_or_id(revision, "revision", (PageRevision,)) response = self._requester.request( - 'GET', - '{}s/{}/pages/{}/revisions/{}'.format( + "GET", + "{}s/{}/pages/{}/revisions/{}".format( self.parent_type, self.parent_id, self.url, revision_id ), _kwargs=combine_kwargs(**kwargs), ) pagerev_json = response.json() if self.parent_type == "group": - pagerev_json.update({'group_id': self.id}) + pagerev_json.update({"group_id": self.id}) elif self.parent_type == "course": - pagerev_json.update({'course_id': self.id}) + pagerev_json.update({"course_id": self.id}) return PageRevision(self._requester, pagerev_json) @@ -183,8 +183,8 @@ def get_revisions(self, **kwargs): return PaginatedList( PageRevision, self._requester, - 'GET', - '{}s/{}/pages/{}/revisions'.format( + "GET", + "{}s/{}/pages/{}/revisions".format( self.parent_type, self.parent_id, self.url ), _kwargs=combine_kwargs(**kwargs), @@ -205,16 +205,16 @@ def revert_to_revision(self, revision): """ revision_id = obj_or_id(revision, "revision", (PageRevision,)) response = self._requester.request( - 'POST', - '{}s/{}/pages/{}/revisions/{}'.format( + "POST", + "{}s/{}/pages/{}/revisions/{}".format( self.parent_type, self.parent_id, self.url, revision_id ), ) pagerev_json = response.json() if self.parent_type == "group": - pagerev_json.update({'group_id': self.id}) + pagerev_json.update({"group_id": self.id}) elif self.parent_type == "course": - pagerev_json.update({'group_id': self.id}) + pagerev_json.update({"group_id": self.id}) return PageRevision(self._requester, pagerev_json) @@ -231,9 +231,9 @@ def parent_id(self): :rtype: int """ - if hasattr(self, 'course_id'): + if hasattr(self, "course_id"): return self.course_id - elif hasattr(self, 'group_id'): + elif hasattr(self, "group_id"): return self.group_id else: raise ValueError("Page does not have a course_id or group_id") @@ -245,10 +245,10 @@ def parent_type(self): :rtype: str """ - if hasattr(self, 'course_id'): - return 'course' - elif hasattr(self, 'group_id'): - return 'group' + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "group_id"): + return "group" else: raise ValueError("ExternalTool does not have a course_id or group_id") @@ -267,10 +267,10 @@ def get_parent(self): from canvasapi.course import Course response = self._requester.request( - 'GET', '{}s/{}'.format(self.parent_type, self.parent_id) + "GET", "{}s/{}".format(self.parent_type, self.parent_id) ) - if self.parent_type == 'group': + if self.parent_type == "group": return Group(self._requester, response.json()) - elif self.parent_type == 'course': + elif self.parent_type == "course": return Course(self._requester, response.json()) diff --git a/canvasapi/paginated_list.py b/canvasapi/paginated_list.py index 58ab6782..1b4c9391 100644 --- a/canvasapi/paginated_list.py +++ b/canvasapi/paginated_list.py @@ -25,7 +25,7 @@ def __init__( self._content_class = content_class self._first_url = first_url self._first_params = kwargs or {} - self._first_params['per_page'] = kwargs.get('per_page', 100) + self._first_params["per_page"] = kwargs.get("per_page", 100) self._next_url = first_url self._next_params = self._first_params self._extra_attribs = extra_attribs or {} @@ -73,11 +73,11 @@ def _get_next_page(self): data = response.json() self._next_url = None - next_link = response.links.get('next') - regex = r'{}(.*)'.format(re.escape(self._requester.base_url)) + next_link = response.links.get("next") + regex = r"{}(.*)".format(re.escape(self._requester.base_url)) self._next_url = ( - re.search(regex, next_link['url']).group(1) if next_link else None + re.search(regex, next_link["url"]).group(1) if next_link else None ) self._next_params = {} diff --git a/canvasapi/planner.py b/canvasapi/planner.py index e8689d53..e4829ff4 100644 --- a/canvasapi/planner.py +++ b/canvasapi/planner.py @@ -22,7 +22,7 @@ def update(self, **kwargs): """ response = self._requester.request( - 'PUT', 'planner_notes/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "planner_notes/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) return PlannerNote(self._requester, response.json()) @@ -36,8 +36,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.planner.PlannerNote` """ response = self._requester.request( - 'DELETE', - 'planner_notes/{}'.format(self.id), + "DELETE", + "planner_notes/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -60,8 +60,8 @@ def update(self, **kwargs): """ response = self._requester.request( - 'PUT', - 'planner/overrides/{}'.format(self.id), + "PUT", + "planner/overrides/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return PlannerOverride(self._requester, response.json()) @@ -76,8 +76,8 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.planner.PlannerOverride` """ response = self._requester.request( - 'DELETE', - 'planner/overrides/{}'.format(self.id), + "DELETE", + "planner/overrides/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/poll.py b/canvasapi/poll.py index d2370d08..6cfeca2d 100644 --- a/canvasapi/poll.py +++ b/canvasapi/poll.py @@ -29,16 +29,16 @@ def update(self, poll, **kwargs): if ( isinstance(poll, list) and isinstance(poll[0], dict) - and 'question' in poll[0] + and "question" in poll[0] ): - kwargs['poll'] = poll + kwargs["poll"] = poll else: raise RequiredFieldMissing("Dictionary with key 'question' is required.") response = self._requester.request( - 'PUT', 'polls/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "polls/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - return Poll(self._requester, response.json()['polls'][0]) + return Poll(self._requester, response.json()["polls"][0]) def delete(self, **kwargs): """ @@ -52,7 +52,7 @@ def delete(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', 'polls/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "DELETE", "polls/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) return response.status_code == 204 @@ -69,9 +69,9 @@ def get_choices(self, **kwargs): return PaginatedList( PollChoice, self._requester, - 'GET', - 'polls/{}/poll_choices'.format(self.id), - _root='poll_choices', + "GET", + "polls/{}/poll_choices".format(self.id), + _root="poll_choices", _kwargs=combine_kwargs(**kwargs), ) @@ -87,11 +87,11 @@ def get_choice(self, poll_choice, **kwargs): poll_choice_id = obj_or_id(poll_choice, "poll_choice", (PollChoice,)) response = self._requester.request( - 'GET', - 'polls/{}/poll_choices/{}'.format(self.id, poll_choice_id), + "GET", + "polls/{}/poll_choices/{}".format(self.id, poll_choice_id), _kwargs=combine_kwargs(**kwargs), ) - return PollChoice(self._requester, response.json()['poll_choices'][0]) + return PollChoice(self._requester, response.json()["poll_choices"][0]) def create_choice(self, poll_choice, **kwargs): """ @@ -107,18 +107,18 @@ def create_choice(self, poll_choice, **kwargs): if ( isinstance(poll_choice, list) and isinstance(poll_choice[0], dict) - and 'text' in poll_choice[0] + and "text" in poll_choice[0] ): - kwargs['poll_choice'] = poll_choice + kwargs["poll_choice"] = poll_choice else: raise RequiredFieldMissing("Dictionary with key 'text' is required.") response = self._requester.request( - 'POST', - 'polls/{}/poll_choices'.format(self.id), + "POST", + "polls/{}/poll_choices".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollChoice(self._requester, response.json()['poll_choices'][0]) + return PollChoice(self._requester, response.json()["poll_choices"][0]) def get_sessions(self, **kwargs): """ @@ -133,9 +133,9 @@ def get_sessions(self, **kwargs): return PaginatedList( PollSession, self._requester, - 'GET', - 'polls/{}/poll_sessions'.format(self.id), - _root='poll_sessions', + "GET", + "polls/{}/poll_sessions".format(self.id), + _root="poll_sessions", _kwargs=combine_kwargs(**kwargs), ) @@ -154,11 +154,11 @@ def get_session(self, poll_session, **kwargs): poll_session_id = obj_or_id(poll_session, "poll_session", (PollSession,)) response = self._requester.request( - 'GET', - 'polls/{}/poll_sessions/{}'.format(self.id, poll_session_id), + "GET", + "polls/{}/poll_sessions/{}".format(self.id, poll_session_id), _kwargs=combine_kwargs(**kwargs), ) - return PollSession(self._requester, response.json()['poll_sessions'][0]) + return PollSession(self._requester, response.json()["poll_sessions"][0]) def create_session(self, poll_session, **kwargs): """ @@ -177,15 +177,15 @@ def create_session(self, poll_session, **kwargs): if ( isinstance(poll_session, list) and isinstance(poll_session[0], dict) - and 'course_id' in poll_session[0] + and "course_id" in poll_session[0] ): - kwargs['poll_session'] = poll_session + kwargs["poll_session"] = poll_session else: raise RequiredFieldMissing("Dictionary with key 'course_id' is required.") response = self._requester.request( - 'POST', - 'polls/{}/poll_sessions'.format(self.id), + "POST", + "polls/{}/poll_sessions".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollSession(self._requester, response.json()['poll_sessions'][0]) + return PollSession(self._requester, response.json()["poll_sessions"][0]) diff --git a/canvasapi/poll_choice.py b/canvasapi/poll_choice.py index d934b043..5473f5a7 100644 --- a/canvasapi/poll_choice.py +++ b/canvasapi/poll_choice.py @@ -27,18 +27,18 @@ def update(self, poll_choice, **kwargs): if ( isinstance(poll_choice, list) and isinstance(poll_choice[0], dict) - and 'text' in poll_choice[0] + and "text" in poll_choice[0] ): - kwargs['poll_choice'] = poll_choice + kwargs["poll_choice"] = poll_choice else: raise RequiredFieldMissing("Dictionary with key 'text' is required.") response = self._requester.request( - 'PUT', - 'polls/{}/poll_choices/{}'.format(self.poll_id, self.id), + "PUT", + "polls/{}/poll_choices/{}".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollChoice(self._requester, response.json()['poll_choices'][0]) + return PollChoice(self._requester, response.json()["poll_choices"][0]) def delete(self, **kwargs): """ @@ -52,8 +52,8 @@ def delete(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'polls/{}/poll_choices/{}'.format(self.poll_id, self.id), + "DELETE", + "polls/{}/poll_choices/{}".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 diff --git a/canvasapi/poll_session.py b/canvasapi/poll_session.py index 3ece0d63..6b4d172e 100644 --- a/canvasapi/poll_session.py +++ b/canvasapi/poll_session.py @@ -30,18 +30,18 @@ def update(self, poll_session, **kwargs): if ( isinstance(poll_session, list) and isinstance(poll_session[0], dict) - and 'course_id' in poll_session[0] + and "course_id" in poll_session[0] ): - kwargs['poll_session'] = poll_session + kwargs["poll_session"] = poll_session else: raise RequiredFieldMissing("Dictionary with key 'course_id' is required.") response = self._requester.request( - 'PUT', - 'polls/{}/poll_sessions/{}'.format(self.poll_id, self.id), + "PUT", + "polls/{}/poll_sessions/{}".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollSession(self._requester, response.json()['poll_sessions'][0]) + return PollSession(self._requester, response.json()["poll_sessions"][0]) def delete(self, **kwargs): """ @@ -55,8 +55,8 @@ def delete(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'polls/{}/poll_sessions/{}'.format(self.poll_id, self.id), + "DELETE", + "polls/{}/poll_sessions/{}".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 @@ -71,11 +71,11 @@ def open(self, **kwargs): :returns: :class:`canvasapi.poll_session.PollSession` """ response = self._requester.request( - 'GET', - 'polls/{}/poll_sessions/{}/open'.format(self.poll_id, self.id), + "GET", + "polls/{}/poll_sessions/{}/open".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollSession(self._requester, response.json()['poll_sessions'][0]) + return PollSession(self._requester, response.json()["poll_sessions"][0]) def close(self, **kwargs): """ @@ -87,11 +87,11 @@ def close(self, **kwargs): :returns: :class:`canvasapi.poll_session.PollSession` """ response = self._requester.request( - 'GET', - 'polls/{}/poll_sessions/{}/close'.format(self.poll_id, self.id), + "GET", + "polls/{}/poll_sessions/{}/close".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollSession(self._requester, response.json()['poll_sessions'][0]) + return PollSession(self._requester, response.json()["poll_sessions"][0]) def get_submission(self, poll_submission, **kwargs): """ @@ -110,13 +110,13 @@ def get_submission(self, poll_submission, **kwargs): ) response = self._requester.request( - 'GET', - 'polls/{}/poll_sessions/{}/poll_submissions/{}'.format( + "GET", + "polls/{}/poll_sessions/{}/poll_submissions/{}".format( self.poll_id, self.id, poll_submission_id ), _kwargs=combine_kwargs(**kwargs), ) - return PollSubmission(self._requester, response.json()['poll_submissions'][0]) + return PollSubmission(self._requester, response.json()["poll_submissions"][0]) def create_submission(self, poll_submissions, **kwargs): """ @@ -134,17 +134,17 @@ def create_submission(self, poll_submissions, **kwargs): if ( isinstance(poll_submissions, list) and isinstance(poll_submissions[0], dict) - and 'poll_choice_id' in poll_submissions[0] + and "poll_choice_id" in poll_submissions[0] ): - kwargs['poll_submissions'] = poll_submissions + kwargs["poll_submissions"] = poll_submissions else: raise RequiredFieldMissing( "Dictionary with key 'poll_choice_id is required." ) response = self._requester.request( - 'POST', - 'polls/{}/poll_sessions/{}/poll_submissions'.format(self.poll_id, self.id), + "POST", + "polls/{}/poll_sessions/{}/poll_submissions".format(self.poll_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - return PollSubmission(self._requester, response.json()['poll_submissions'][0]) + return PollSubmission(self._requester, response.json()["poll_submissions"][0]) diff --git a/canvasapi/progress.py b/canvasapi/progress.py index e4d07873..3d1f0fd4 100644 --- a/canvasapi/progress.py +++ b/canvasapi/progress.py @@ -19,7 +19,7 @@ def query(self): :rtype: :class:`canvasapi.progress.Progress` """ - response = self._requester.request('GET', 'progress/{}'.format(self.id)) + response = self._requester.request("GET", "progress/{}".format(self.id)) response_json = response.json() super(Progress, self).set_attributes(response_json) diff --git a/canvasapi/quiz.py b/canvasapi/quiz.py index 512e28b8..cbd9768c 100644 --- a/canvasapi/quiz.py +++ b/canvasapi/quiz.py @@ -27,12 +27,12 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.quiz.Quiz` """ response = self._requester.request( - 'PUT', - 'courses/{}/quizzes/{}'.format(self.course_id, self.id), + "PUT", + "courses/{}/quizzes/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) quiz_json = response.json() - quiz_json.update({'course_id': self.course_id}) + quiz_json.update({"course_id": self.course_id}) return Quiz(self._requester, quiz_json) @@ -46,12 +46,12 @@ def delete(self, **kwargs): :rtype: :class:`canvasapi.quiz.Quiz` """ response = self._requester.request( - 'DELETE', - 'courses/{}/quizzes/{}'.format(self.course_id, self.id), + "DELETE", + "courses/{}/quizzes/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) quiz_json = response.json() - quiz_json.update({'course_id': self.course_id}) + quiz_json.update({"course_id": self.course_id}) return Quiz(self._requester, quiz_json) @@ -69,13 +69,13 @@ def get_quiz_group(self, id, **kwargs): :rtype: :class:`canvasapi.quiz_group.QuizGroup` """ response = self._requester.request( - 'GET', - 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.id, id), + "GET", + "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.id, id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.id}) + response_json.update({"course_id": self.id}) return QuizGroup(self._requester, response_json) @@ -104,10 +104,10 @@ def create_question_group(self, quiz_groups, **kwargs): raise ValueError("Param `quiz_groups must contain a dictionary") param_list = [ - 'name', - 'pick_count', - 'question_points', - 'assessment_question_bank_id', + "name", + "pick_count", + "question_points", + "assessment_question_bank_id", ] if not any(param in quiz_groups[0] for param in param_list): raise RequiredFieldMissing("quiz_groups must contain at least 1 parameter.") @@ -115,15 +115,15 @@ def create_question_group(self, quiz_groups, **kwargs): kwargs["quiz_groups"] = quiz_groups response = self._requester.request( - 'POST', - 'courses/{}/quizzes/{}/groups'.format(self.course_id, self.id), + "POST", + "courses/{}/quizzes/{}/groups".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json['quiz_groups'][0].update({'course_id': self.id}) + response_json["quiz_groups"][0].update({"course_id": self.id}) - return QuizGroup(self._requester, response_json.get('quiz_groups')[0]) + return QuizGroup(self._requester, response_json.get("quiz_groups")[0]) def create_question(self, **kwargs): """ @@ -136,12 +136,12 @@ def create_question(self, **kwargs): """ response = self._requester.request( - 'POST', - 'courses/{}/quizzes/{}/questions'.format(self.course_id, self.id), + "POST", + "courses/{}/quizzes/{}/questions".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return QuizQuestion(self._requester, response_json) @@ -160,14 +160,14 @@ def get_question(self, question, **kwargs): question_id = obj_or_id(question, "question", (QuizQuestion,)) response = self._requester.request( - 'GET', - 'courses/{}/quizzes/{}/questions/{}'.format( + "GET", + "courses/{}/quizzes/{}/questions/{}".format( self.course_id, self.id, question_id ), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return QuizQuestion(self._requester, response_json) @@ -184,9 +184,9 @@ def get_questions(self, **kwargs): return PaginatedList( QuizQuestion, self._requester, - 'GET', - 'courses/{}/quizzes/{}/questions'.format(self.course_id, self.id), - {'course_id': self.course_id}, + "GET", + "courses/{}/quizzes/{}/questions".format(self.course_id, self.id), + {"course_id": self.course_id}, _kwargs=combine_kwargs(**kwargs), ) @@ -222,24 +222,24 @@ def set_extensions(self, quiz_extensions, **kwargs): """ if not isinstance(quiz_extensions, list) or not quiz_extensions: - raise ValueError('Param `quiz_extensions` must be a non-empty list.') + raise ValueError("Param `quiz_extensions` must be a non-empty list.") if any(not isinstance(extension, dict) for extension in quiz_extensions): - raise ValueError('Param `quiz_extensions` must only contain dictionaries') + raise ValueError("Param `quiz_extensions` must only contain dictionaries") - if any('user_id' not in extension for extension in quiz_extensions): + if any("user_id" not in extension for extension in quiz_extensions): raise RequiredFieldMissing( - 'Dictionaries in `quiz_extensions` must contain key `user_id`' + "Dictionaries in `quiz_extensions` must contain key `user_id`" ) - kwargs['quiz_extensions'] = quiz_extensions + kwargs["quiz_extensions"] = quiz_extensions response = self._requester.request( - 'POST', - 'courses/{}/quizzes/{}/extensions'.format(self.course_id, self.id), + "POST", + "courses/{}/quizzes/{}/extensions".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - extension_list = response.json()['quiz_extensions'] + extension_list = response.json()["quiz_extensions"] return [ QuizExtension(self._requester, extension) for extension in extension_list ] @@ -278,9 +278,9 @@ def get_submissions(self, **kwargs): return PaginatedList( QuizSubmission, self._requester, - 'GET', - 'courses/{}/quizzes/{}/submissions'.format(self.course_id, self.id), - _root='quiz_submissions', + "GET", + "courses/{}/quizzes/{}/submissions".format(self.course_id, self.id), + _root="quiz_submissions", _kwargs=combine_kwargs(**kwargs), ) @@ -301,15 +301,15 @@ def get_quiz_submission(self, quiz_submission, **kwargs): ) response = self._requester.request( - 'GET', - 'courses/{}/quizzes/{}/submissions/{}'.format( + "GET", + "courses/{}/quizzes/{}/submissions/{}".format( self.course_id, self.id, quiz_submission_id ), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json()["quiz_submissions"][0] - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return QuizSubmission(self._requester, response_json) @@ -324,13 +324,13 @@ def create_submission(self, **kwargs): :rtype: :class:`canvasapi.quiz.QuizSubmission` """ response = self._requester.request( - 'POST', - 'courses/{}/quizzes/{}/submissions'.format(self.course_id, self.id), + "POST", + "courses/{}/quizzes/{}/submissions".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json()["quiz_submissions"][0] - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return QuizSubmission(self._requester, response_json) @@ -355,7 +355,7 @@ def complete(self, validation_token=None, **kwargs): :rtype: :class:`canvasapi.quiz.QuizSubmission` """ try: - kwargs['validation_token'] = validation_token or self.validation_token + kwargs["validation_token"] = validation_token or self.validation_token except AttributeError: raise RequiredFieldMissing( "`validation_token` not set on this QuizSubmission, must be passed" @@ -365,11 +365,11 @@ def complete(self, validation_token=None, **kwargs): # Only the latest attempt for a quiz submission can be updated, and Canvas # automatically returns the latest attempt with every quiz submission response, # so we can just use that. - kwargs['attempt'] = self.attempt + kwargs["attempt"] = self.attempt response = self._requester.request( - 'POST', - 'courses/{}/quizzes/{}/submissions/{}/complete'.format( + "POST", + "courses/{}/quizzes/{}/submissions/{}/complete".format( self.course_id, self.quiz_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -389,8 +389,8 @@ def get_times(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'GET', - 'courses/{}/quizzes/{}/submissions/{}/time'.format( + "GET", + "courses/{}/quizzes/{}/submissions/{}/time".format( self.course_id, self.quiz_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -411,8 +411,8 @@ def update_score_and_comments(self, **kwargs): :rtype: :class:`canvasapi.quiz.QuizSubmission` """ response = self._requester.request( - 'PUT', - 'courses/{}/quizzes/{}/submissions/{}'.format( + "PUT", + "courses/{}/quizzes/{}/submissions/{}".format( self.course_id, self.quiz_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -439,7 +439,7 @@ def get_submission_questions(self, **kwargs): questions = list() for question in response.json().get("quiz_submission_questions", []): - question.update({'quiz_submission_id': self.id, 'attempt': self.attempt}) + question.update({"quiz_submission_id": self.id, "attempt": self.attempt}) questions.append(QuizSubmissionQuestion(self._requester, question)) return questions @@ -458,7 +458,7 @@ def answer_submission_questions(self, validation_token=None, **kwargs): :rtype: list of :class:`canvasapi.quiz.QuizSubmissionQuestion` """ try: - kwargs['validation_token'] = validation_token or self.validation_token + kwargs["validation_token"] = validation_token or self.validation_token except AttributeError: raise RequiredFieldMissing( "`validation_token` not set on this QuizSubmission, must be passed" @@ -468,21 +468,21 @@ def answer_submission_questions(self, validation_token=None, **kwargs): # Only the latest attempt for a quiz submission can be updated, and Canvas # automatically returns the latest attempt with every quiz submission response, # so we can just use that. - kwargs['attempt'] = self.attempt + kwargs["attempt"] = self.attempt response = self._requester.request( - 'POST', - 'quiz_submissions/{}/questions'.format(self.id), + "POST", + "quiz_submissions/{}/questions".format(self.id), _kwargs=combine_kwargs(**kwargs), ) questions = list() - for question in response.json().get('quiz_submission_questions', []): + for question in response.json().get("quiz_submission_questions", []): question.update( { - 'quiz_submission_id': self.id, - 'validation_token': kwargs['validation_token'], - 'attempt': self.attempt, + "quiz_submission_id": self.id, + "validation_token": kwargs["validation_token"], + "attempt": self.attempt, } ) questions.append(QuizSubmissionQuestion(self._requester, question)) @@ -512,8 +512,8 @@ def delete(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'courses/{}/quizzes/{}/questions/{}'.format( + "DELETE", + "courses/{}/quizzes/{}/questions/{}".format( self.course_id, self.quiz_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -531,14 +531,14 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.quiz.QuizQuestion` """ response = self._requester.request( - 'PUT', - 'courses/{}/quizzes/{}/questions/{}'.format( + "PUT", + "courses/{}/quizzes/{}/questions/{}".format( self.course_id, self.quiz_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) super(QuizQuestion, self).set_attributes(response_json) return self @@ -563,7 +563,7 @@ def flag(self, validation_token=None, **kwargs): :rtype: bool """ try: - kwargs['validation_token'] = validation_token or self.validation_token + kwargs["validation_token"] = validation_token or self.validation_token except AttributeError: raise RequiredFieldMissing( "`validation_token` not set on this QuizSubmissionQuestion, must be passed" @@ -573,21 +573,21 @@ def flag(self, validation_token=None, **kwargs): # Only the latest attempt for a quiz submission can be updated, and Canvas # automatically returns the latest attempt with every quiz submission response, # so we can just use that. - kwargs['attempt'] = self.attempt + kwargs["attempt"] = self.attempt response = self._requester.request( - 'PUT', - 'quiz_submissions/{}/questions/{}/flag'.format( + "PUT", + "quiz_submissions/{}/questions/{}/flag".format( self.quiz_submission_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - question = response.json()['quiz_submission_questions'][0] + question = response.json()["quiz_submission_questions"][0] question.update( { - 'validation_token': kwargs['validation_token'], - 'quiz_submission_id': self.quiz_submission_id, + "validation_token": kwargs["validation_token"], + "quiz_submission_id": self.quiz_submission_id, } ) super(QuizSubmissionQuestion, self).set_attributes(question) @@ -608,7 +608,7 @@ def unflag(self, validation_token=None, **kwargs): :rtype: bool """ try: - kwargs['validation_token'] = validation_token or self.validation_token + kwargs["validation_token"] = validation_token or self.validation_token except AttributeError: raise RequiredFieldMissing( "`validation_token` not set on this QuizSubmissionQuestion, must be passed" @@ -618,21 +618,21 @@ def unflag(self, validation_token=None, **kwargs): # Only the latest attempt for a quiz submission can be updated, and Canvas # automatically returns the latest attempt with every quiz submission response, # so we can just use that. - kwargs['attempt'] = self.attempt + kwargs["attempt"] = self.attempt response = self._requester.request( - 'PUT', - 'quiz_submissions/{}/questions/{}/unflag'.format( + "PUT", + "quiz_submissions/{}/questions/{}/unflag".format( self.quiz_submission_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - question = response.json()['quiz_submission_questions'][0] + question = response.json()["quiz_submission_questions"][0] question.update( { - 'validation_token': kwargs['validation_token'], - 'quiz_submission_id': self.quiz_submission_id, + "validation_token": kwargs["validation_token"], + "quiz_submission_id": self.quiz_submission_id, } ) super(QuizSubmissionQuestion, self).set_attributes(question) diff --git a/canvasapi/quiz_group.py b/canvasapi/quiz_group.py index 9a4fb15d..ccb78d28 100644 --- a/canvasapi/quiz_group.py +++ b/canvasapi/quiz_group.py @@ -36,21 +36,21 @@ def update(self, id, quiz_groups, **kwargs): if not isinstance(quiz_groups[0], dict): raise ValueError("Param `quiz_groups` must contain a dictionary") - param_list = ['name', 'pick_count', 'question_points'] + param_list = ["name", "pick_count", "question_points"] if not any(param in quiz_groups[0] for param in param_list): raise RequiredFieldMissing("quiz_groups must contain at least 1 parameter.") kwargs["quiz_groups"] = quiz_groups response = self._requester.request( - 'PUT', - 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.quiz_id, id), + "PUT", + "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.quiz_id, id), _kwargs=combine_kwargs(**kwargs), ) - successful = 'name' in response.json().get('quiz_groups')[0] + successful = "name" in response.json().get("quiz_groups")[0] if successful: - super(QuizGroup, self).set_attributes(response.json().get('quiz_groups')[0]) + super(QuizGroup, self).set_attributes(response.json().get("quiz_groups")[0]) return successful @@ -68,8 +68,8 @@ def delete(self, id): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'courses/{}/quizzes/{}/groups/{}'.format(self.course_id, self.quiz_id, id), + "DELETE", + "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.quiz_id, id), ) return response.status_code == 204 @@ -105,8 +105,8 @@ def reorder_question_group(self, id, order, **kwargs): kwargs["order"] = order response = self._requester.request( - 'POST', - 'courses/{}/quizzes/{}/groups/{}/reorder'.format( + "POST", + "courses/{}/quizzes/{}/groups/{}/reorder".format( self.course_id, self.quiz_id, id ), _kwargs=combine_kwargs(**kwargs), diff --git a/canvasapi/section.py b/canvasapi/section.py index 5b2ca655..fb358dc8 100644 --- a/canvasapi/section.py +++ b/canvasapi/section.py @@ -9,13 +9,13 @@ from canvasapi.submission import GroupedSubmission, Submission from canvasapi.util import combine_kwargs, obj_or_id, normalize_bool -warnings.simplefilter('always', DeprecationWarning) +warnings.simplefilter("always", DeprecationWarning) @python_2_unicode_compatible class Section(CanvasObject): def __str__(self): - return '{} - {} ({})'.format(self.name, self.course_id, self.id) + return "{} - {} ({})".format(self.name, self.course_id, self.id) def get_assignment_override(self, assignment, **kwargs): """ @@ -34,10 +34,10 @@ def get_assignment_override(self, assignment, **kwargs): assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) response = self._requester.request( - 'GET', 'sections/{}/assignments/{}/override'.format(self.id, assignment_id) + "GET", "sections/{}/assignments/{}/override".format(self.id, assignment_id) ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) return AssignmentOverride(self._requester, response_json) @@ -56,8 +56,8 @@ def get_enrollments(self, **kwargs): return PaginatedList( Enrollment, self._requester, - 'GET', - 'sections/{}/enrollments'.format(self.id), + "GET", + "sections/{}/enrollments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -78,7 +78,7 @@ def cross_list_section(self, new_course): new_course_id = obj_or_id(new_course, "new_course", (Course,)) response = self._requester.request( - 'POST', 'sections/{}/crosslist/{}'.format(self.id, new_course_id) + "POST", "sections/{}/crosslist/{}".format(self.id, new_course_id) ) return Section(self._requester, response.json()) @@ -92,7 +92,7 @@ def decross_list_section(self): :rtype: :class:`canvasapi.section.Section` """ response = self._requester.request( - 'DELETE', 'sections/{}/crosslist'.format(self.id) + "DELETE", "sections/{}/crosslist".format(self.id) ) return Section(self._requester, response.json()) @@ -106,10 +106,10 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.section.Section` """ response = self._requester.request( - 'PUT', 'sections/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "sections/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - if 'name' in response.json(): + if "name" in response.json(): super(Section, self).set_attributes(response.json()) return self @@ -123,7 +123,7 @@ def delete(self): :rtype: :class:`canvasapi.section.Section` """ - response = self._requester.request('DELETE', 'sections/{}'.format(self.id)) + response = self._requester.request("DELETE", "sections/{}".format(self.id)) return Section(self._requester, response.json()) def submit_assignment(self, assignment, submission, **kwargs): @@ -147,15 +147,15 @@ def submit_assignment(self, assignment, submission, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - 'Section.submit_assignment() is deprecated and will be removed ' - 'in the future. Use Assignment.submit() instead.', + "Section.submit_assignment() is deprecated and will be removed " + "in the future. Use Assignment.submit() instead.", DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( self._requester, - {'course_id': self.course_id, 'section_id': self.id, 'id': assignment_id}, + {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, ) return assignment.submit(submission, **kwargs) @@ -179,15 +179,15 @@ def list_submissions(self, assignment, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - 'Section.list_submissions() is deprecated and will be removed ' - 'in the future. Use Assignment.get_submissions() instead.', + "Section.list_submissions() is deprecated and will be removed " + "in the future. Use Assignment.get_submissions() instead.", DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) assignment = Assignment( self._requester, - {'course_id': self.course_id, 'section_id': self.id, 'id': assignment_id}, + {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, ) return assignment.get_submissions(**kwargs) @@ -237,9 +237,9 @@ def get_multiple_submissions(self, **kwargs): return PaginatedList( cls, self._requester, - 'GET', - 'sections/{}/students/submissions'.format(self.id), - {'section_id': self.id}, + "GET", + "sections/{}/students/submissions".format(self.id), + {"section_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -264,8 +264,8 @@ def get_submission(self, assignment, user, **kwargs): from canvasapi.assignment import Assignment warnings.warn( - 'Section.get_submission() is deprecated and will be removed ' - 'in the future. Use Assignment.get_submission() instead.', + "Section.get_submission() is deprecated and will be removed " + "in the future. Use Assignment.get_submission() instead.", DeprecationWarning, ) @@ -273,7 +273,7 @@ def get_submission(self, assignment, user, **kwargs): assignment = Assignment( self._requester, - {'course_id': self.course_id, 'section_id': self.id, 'id': assignment_id}, + {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, ) return assignment.get_submission(user, **kwargs) @@ -300,8 +300,8 @@ def update_submission(self, assignment, user, **kwargs): from canvasapi.user import User warnings.warn( - 'Section.update_submission() is deprecated and will be removed ' - 'in the future. Use Submission.edit() instead.', + "Section.update_submission() is deprecated and will be removed " + "in the future. Use Submission.edit() instead.", DeprecationWarning, ) @@ -311,9 +311,9 @@ def update_submission(self, assignment, user, **kwargs): submission = Submission( self._requester, { - 'course_id': self.course_id, - 'assignment_id': assignment_id, - 'user_id': user_id, + "course_id": self.course_id, + "assignment_id": assignment_id, + "user_id": user_id, }, ) @@ -342,8 +342,8 @@ def mark_submission_as_read(self, assignment, user, **kwargs): from canvasapi.user import User warnings.warn( - 'Section.mark_submission_as_read() is deprecated and will be ' - 'removed in the future. Use Submission.mark_read() instead.', + "Section.mark_submission_as_read() is deprecated and will be " + "removed in the future. Use Submission.mark_read() instead.", DeprecationWarning, ) @@ -353,9 +353,9 @@ def mark_submission_as_read(self, assignment, user, **kwargs): submission = Submission( self._requester, { - 'course_id': self.course_id, - 'assignment_id': assignment_id, - 'user_id': user_id, + "course_id": self.course_id, + "assignment_id": assignment_id, + "user_id": user_id, }, ) return submission.mark_read(**kwargs) @@ -383,8 +383,8 @@ def mark_submission_as_unread(self, assignment, user, **kwargs): from canvasapi.user import User warnings.warn( - 'Section.mark_submission_as_unread() is deprecated and will be ' - 'removed in the future. Use Submission.mark_unread() instead.', + "Section.mark_submission_as_unread() is deprecated and will be " + "removed in the future. Use Submission.mark_unread() instead.", DeprecationWarning, ) @@ -394,9 +394,9 @@ def mark_submission_as_unread(self, assignment, user, **kwargs): submission = Submission( self._requester, { - 'course_id': self.course_id, - 'assignment_id': assignment_id, - 'user_id': user_id, + "course_id": self.course_id, + "assignment_id": assignment_id, + "user_id": user_id, }, ) return submission.mark_unread(**kwargs) @@ -412,8 +412,8 @@ def submissions_bulk_update(self, **kwargs): :rtype: :class:`canvasapi.progress.Progress` """ response = self._requester.request( - 'POST', - 'sections/{}/submissions/update_grades'.format(self.id), + "POST", + "sections/{}/submissions/update_grades".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) diff --git a/canvasapi/sis_import.py b/canvasapi/sis_import.py index 2bb4e6e5..3c4d43bd 100644 --- a/canvasapi/sis_import.py +++ b/canvasapi/sis_import.py @@ -22,8 +22,8 @@ def abort(self, **kwargs): :rtype: :class:`canvasapi.sis_import.SisImport` """ response = self._requester.request( - 'PUT', - 'accounts/{}/sis_imports/{}/abort'.format(self.account_id, self.id), + "PUT", + "accounts/{}/sis_imports/{}/abort".format(self.account_id, self.id), _kwargs=combine_kwargs(**kwargs), ) return SisImport(self._requester, response.json()) @@ -38,8 +38,8 @@ def restore_states(self, **kwargs): :rtype: :class:`canvasapi.progress.Progress` """ response = self._requester.request( - 'PUT', - 'accounts/{}/sis_imports/{}/restore_states'.format( + "PUT", + "accounts/{}/sis_imports/{}/restore_states".format( self.account_id, self.id ), _kwargs=combine_kwargs(**kwargs), diff --git a/canvasapi/submission.py b/canvasapi/submission.py index 7fa5c2b6..f4d87a0f 100644 --- a/canvasapi/submission.py +++ b/canvasapi/submission.py @@ -12,7 +12,7 @@ @python_2_unicode_compatible class Submission(CanvasObject): def __str__(self): - return '{}-{}'.format(self.assignment_id, self.user_id) + return "{}-{}".format(self.assignment_id, self.user_id) def create_submission_peer_review(self, user, **kwargs): """ @@ -30,10 +30,10 @@ def create_submission_peer_review(self, user, **kwargs): from canvasapi.user import User user_id = obj_or_id(user, "user", (User,)) - kwargs['user_id'] = user_id + kwargs["user_id"] = user_id response = self._requester.request( - 'POST', - 'courses/{}/assignments/{}/submissions/{}/peer_reviews'.format( + "POST", + "courses/{}/assignments/{}/submissions/{}/peer_reviews".format( self.course_id, self.assignment_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -57,10 +57,10 @@ def delete_submission_peer_review(self, user, **kwargs): from canvasapi.user import User user_id = obj_or_id(user, "user", (User,)) - kwargs['user_id'] = user_id + kwargs["user_id"] = user_id response = self._requester.request( - 'DELETE', - 'courses/{}/assignments/{}/submissions/{}/peer_reviews'.format( + "DELETE", + "courses/{}/assignments/{}/submissions/{}/peer_reviews".format( self.course_id, self.assignment_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -77,8 +77,8 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.submission.Submission` """ response = self._requester.request( - 'PUT', - 'courses/{}/assignments/{}/submissions/{}'.format( + "PUT", + "courses/{}/assignments/{}/submissions/{}".format( self.course_id, self.assignment_id, self.user_id ), _kwargs=combine_kwargs(**kwargs), @@ -101,8 +101,8 @@ def mark_read(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'PUT', - 'courses/{}/assignments/{}/submissions/{}/read'.format( + "PUT", + "courses/{}/assignments/{}/submissions/{}/read".format( self.course_id, self.assignment_id, self.user_id ), ) @@ -120,8 +120,8 @@ def mark_unread(self, **kwargs): :rtype: bool """ response = self._requester.request( - 'DELETE', - 'courses/{}/assignments/{}/submissions/{}/read'.format( + "DELETE", + "courses/{}/assignments/{}/submissions/{}/read".format( self.course_id, self.assignment_id, self.user_id ), ) @@ -141,8 +141,8 @@ def get_submission_peer_reviews(self, **kwargs): return PaginatedList( PeerReview, self._requester, - 'GET', - 'courses/{}/assignments/{}/submissions/{}/peer_reviews'.format( + "GET", + "courses/{}/assignments/{}/submissions/{}/peer_reviews".format( self.course_id, self.assignment_id, self.id ), _kwargs=combine_kwargs(**kwargs), @@ -164,7 +164,7 @@ def upload_comment(self, file, **kwargs): """ response = Uploader( self._requester, - 'courses/{}/assignments/{}/submissions/{}/comments/files'.format( + "courses/{}/assignments/{}/submissions/{}/comments/files".format( self.course_id, self.assignment_id, self.user_id ), file, @@ -172,7 +172,7 @@ def upload_comment(self, file, **kwargs): ).start() if response[0]: - self.edit(comment={'file_ids': [response[1]['id']]}) + self.edit(comment={"file_ids": [response[1]["id"]]}) return response @@ -187,9 +187,9 @@ def __init__(self, requester, attributes): try: self.submissions = [ Submission(requester, submission) - for submission in attributes['submissions'] + for submission in attributes["submissions"] ] - del attributes['submissions'] + del attributes["submissions"] except KeyError: self.submissions = list() diff --git a/canvasapi/tab.py b/canvasapi/tab.py index a9e321f9..3e4c86f9 100644 --- a/canvasapi/tab.py +++ b/canvasapi/tab.py @@ -23,16 +23,16 @@ def update(self, **kwargs): :rtype: :class:`canvasapi.tab.Tab` """ - if not hasattr(self, 'course_id'): - raise ValueError('Can only update tabs from a Course.') + if not hasattr(self, "course_id"): + raise ValueError("Can only update tabs from a Course.") response = self._requester.request( - 'PUT', - 'courses/{}/tabs/{}'.format(self.course_id, self.id), + "PUT", + "courses/{}/tabs/{}".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'course_id': self.course_id}) + response_json.update({"course_id": self.course_id}) super(Tab, self).set_attributes(response_json) diff --git a/canvasapi/upload.py b/canvasapi/upload.py index de685701..1a3017dd 100644 --- a/canvasapi/upload.py +++ b/canvasapi/upload.py @@ -23,7 +23,7 @@ def __init__(self, requester, url, file, **kwargs): """ if isinstance(file, string_types): if not os.path.exists(file): - raise IOError('File ' + file + ' does not exist.') + raise IOError("File " + file + " does not exist.") self._using_filename = True else: self._using_filename = False @@ -44,7 +44,7 @@ def start(self): :rtype: tuple """ if self._using_filename: - with open(self.file, 'rb') as file: + with open(self.file, "rb") as file: return self.request_upload_token(file) else: return self.request_upload_token(self.file) @@ -58,11 +58,11 @@ def request_upload_token(self, file): and the JSON response from the API. :rtype: tuple """ - self.kwargs['name'] = os.path.basename(file.name) - self.kwargs['size'] = os.fstat(file.fileno()).st_size + self.kwargs["name"] = os.path.basename(file.name) + self.kwargs["size"] = os.fstat(file.fileno()).st_size response = self._requester.request( - 'POST', self.url, _kwargs=combine_kwargs(**self.kwargs) + "POST", self.url, _kwargs=combine_kwargs(**self.kwargs) ) return self.upload(response, file) @@ -79,23 +79,23 @@ def upload(self, response, file): :rtype: tuple """ response = response.json() - if not response.get('upload_url'): - raise ValueError('Bad API response. No upload_url.') + if not response.get("upload_url"): + raise ValueError("Bad API response. No upload_url.") - if not response.get('upload_params'): - raise ValueError('Bad API response. No upload_params.') + if not response.get("upload_params"): + raise ValueError("Bad API response. No upload_params.") - kwargs = response.get('upload_params') + kwargs = response.get("upload_params") response = self._requester.request( - 'POST', + "POST", use_auth=False, - _url=response.get('upload_url'), + _url=response.get("upload_url"), file=file, _kwargs=combine_kwargs(**kwargs), ) # remove `while(1);` that may appear at the top of a response - response_json = json.loads(response.text.lstrip('while(1);')) + response_json = json.loads(response.text.lstrip("while(1);")) - return ('url' in response_json, response_json) + return ("url" in response_json, response_json) diff --git a/canvasapi/user.py b/canvasapi/user.py index 87a9817e..aebe15b2 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -26,7 +26,7 @@ def get_profile(self, **kwargs): :rtype: dict """ - response = self._requester.request('GET', 'users/{}/profile'.format(self.id)) + response = self._requester.request("GET", "users/{}/profile".format(self.id)) return response.json() def get_page_views(self, **kwargs): @@ -44,8 +44,8 @@ def get_page_views(self, **kwargs): return PaginatedList( PageView, self._requester, - 'GET', - 'users/{}/page_views'.format(self.id), + "GET", + "users/{}/page_views".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -64,8 +64,8 @@ def get_courses(self, **kwargs): return PaginatedList( Course, self._requester, - 'GET', - 'users/{}/courses'.format(self.id), + "GET", + "users/{}/courses".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -85,8 +85,8 @@ def get_missing_submissions(self): return PaginatedList( Assignment, self._requester, - 'GET', - 'users/{}/missing_submissions'.format(self.id), + "GET", + "users/{}/missing_submissions".format(self.id), ) def update_settings(self, **kwargs): @@ -99,7 +99,7 @@ def update_settings(self, **kwargs): :rtype: dict """ response = self._requester.request( - 'PUT', 'users/{}/settings'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "users/{}/settings".format(self.id), _kwargs=combine_kwargs(**kwargs) ) return response.json() @@ -117,7 +117,7 @@ def get_color(self, asset_string): :rtype: dict """ response = self._requester.request( - 'GET', 'users/{}/colors/{}'.format(self.id, asset_string) + "GET", "users/{}/colors/{}".format(self.id, asset_string) ) return response.json() @@ -130,7 +130,7 @@ def get_colors(self): :rtype: dict """ - response = self._requester.request('GET', 'users/{}/colors'.format(self.id)) + response = self._requester.request("GET", "users/{}/colors".format(self.id)) return response.json() def update_color(self, asset_string, hexcode): @@ -152,7 +152,7 @@ def update_color(self, asset_string, hexcode): :rtype: dict """ response = self._requester.request( - 'PUT', 'users/{}/colors/{}'.format(self.id, asset_string), hexcode=hexcode + "PUT", "users/{}/colors/{}".format(self.id, asset_string), hexcode=hexcode ) return response.json() @@ -166,7 +166,7 @@ def edit(self, **kwargs): :rtype: :class:`canvasapi.user.User` """ response = self._requester.request( - 'PUT', 'users/{}'.format(self.id), _kwargs=combine_kwargs(**kwargs) + "PUT", "users/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) super(User, self).set_attributes(response.json()) return self @@ -183,10 +183,10 @@ def merge_into(self, destination_user): :rtype: :class:`canvasapi.user.User` """ - dest_user_id = obj_or_id(destination_user, 'destination_user', (User,)) + dest_user_id = obj_or_id(destination_user, "destination_user", (User,)) response = self._requester.request( - 'PUT', 'users/{}/merge_into/{}'.format(self.id, dest_user_id) + "PUT", "users/{}/merge_into/{}".format(self.id, dest_user_id) ) super(User, self).set_attributes(response.json()) return self @@ -204,7 +204,7 @@ def get_avatars(self): from canvasapi.avatar import Avatar return PaginatedList( - Avatar, self._requester, 'GET', 'users/{}/avatars'.format(self.id) + Avatar, self._requester, "GET", "users/{}/avatars".format(self.id) ) def get_assignments(self, course, **kwargs): @@ -229,8 +229,8 @@ def get_assignments(self, course, **kwargs): return PaginatedList( Assignment, self._requester, - 'GET', - 'users/{}/courses/{}/assignments'.format(self.id, course_id), + "GET", + "users/{}/courses/{}/assignments".format(self.id, course_id), _kwargs=combine_kwargs(**kwargs), ) @@ -249,8 +249,8 @@ def get_enrollments(self, **kwargs): return PaginatedList( Enrollment, self._requester, - 'GET', - 'users/{}/enrollments'.format(self.id), + "GET", + "users/{}/enrollments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -272,7 +272,7 @@ def upload(self, file, **kwargs): :rtype: tuple """ return Uploader( - self._requester, 'users/{}/files'.format(self.id), file, **kwargs + self._requester, "users/{}/files".format(self.id), file, **kwargs ).start() def list_calendar_events_for_user(self, **kwargs): @@ -311,8 +311,8 @@ def get_calendar_events_for_user(self, **kwargs): return PaginatedList( CalendarEvent, self._requester, - 'GET', - 'users/{}/calendar_events'.format(self.id), + "GET", + "users/{}/calendar_events".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -354,8 +354,8 @@ def get_communication_channels(self, **kwargs): return PaginatedList( CommunicationChannel, self._requester, - 'GET', - 'users/{}/communication_channels'.format(self.id), + "GET", + "users/{}/communication_channels".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -369,8 +369,8 @@ def create_communication_channel(self, **kwargs): :rtype: :class:`canvasapi.communication_channel.CommunicationChannel` """ response = self._requester.request( - 'POST', - 'users/{}/communication_channels'.format(self.id), + "POST", + "users/{}/communication_channels".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -413,8 +413,8 @@ def get_files(self, **kwargs): return PaginatedList( File, self._requester, - 'GET', - 'users/{}/files'.format(self.id), + "GET", + "users/{}/files".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -435,8 +435,8 @@ def get_file(self, file, **kwargs): file_id = obj_or_id(file, "file", (File,)) response = self._requester.request( - 'GET', - 'users/{}/files/{}'.format(self.id, file_id), + "GET", + "users/{}/files/{}".format(self.id, file_id), _kwargs=combine_kwargs(**kwargs), ) return File(self._requester, response.json()) @@ -458,7 +458,7 @@ def get_folder(self, folder): folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - 'GET', 'users/{}/folders/{}'.format(self.id, folder_id) + "GET", "users/{}/folders/{}".format(self.id, folder_id) ) return Folder(self._requester, response.json()) @@ -499,8 +499,8 @@ def get_folders(self, **kwargs): return PaginatedList( Folder, self._requester, - 'GET', - 'users/{}/folders'.format(self.id), + "GET", + "users/{}/folders".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -516,8 +516,8 @@ def create_folder(self, name, **kwargs): :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - 'POST', - 'users/{}/folders'.format(self.id), + "POST", + "users/{}/folders".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) @@ -560,8 +560,8 @@ def get_user_logins(self, **kwargs): return PaginatedList( Login, self._requester, - 'GET', - 'users/{}/logins'.format(self.id), + "GET", + "users/{}/logins".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -601,8 +601,8 @@ def get_observees(self, **kwargs): return PaginatedList( User, self._requester, - 'GET', - 'users/{}/observees'.format(self.id), + "GET", + "users/{}/observees".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -617,8 +617,8 @@ def add_observee_with_credentials(self, **kwargs): """ response = self._requester.request( - 'POST', - 'users/{}/observees'.format(self.id), + "POST", + "users/{}/observees".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return User(self._requester, response.json()) @@ -636,7 +636,7 @@ def show_observee(self, observee_id): """ response = self._requester.request( - 'GET', 'users/{}/observees/{}'.format(self.id, observee_id) + "GET", "users/{}/observees/{}".format(self.id, observee_id) ) return User(self._requester, response.json()) @@ -653,7 +653,7 @@ def add_observee(self, observee_id): """ response = self._requester.request( - 'PUT', 'users/{}/observees/{}'.format(self.id, observee_id) + "PUT", "users/{}/observees/{}".format(self.id, observee_id) ) return User(self._requester, response.json()) @@ -670,7 +670,7 @@ def remove_observee(self, observee_id): """ response = self._requester.request( - 'DELETE', 'users/{}/observees/{}'.format(self.id, observee_id) + "DELETE", "users/{}/observees/{}".format(self.id, observee_id) ) return User(self._requester, response.json()) @@ -689,20 +689,20 @@ def create_content_migration(self, migration_type, **kwargs): from canvasapi.content_migration import ContentMigration, Migrator if isinstance(migration_type, Migrator): - kwargs['migration_type'] = migration_type.type + kwargs["migration_type"] = migration_type.type elif isinstance(migration_type, string_types): - kwargs['migration_type'] = migration_type + kwargs["migration_type"] = migration_type else: - raise TypeError('Parameter migration_type must be of type Migrator or str') + raise TypeError("Parameter migration_type must be of type Migrator or str") response = self._requester.request( - 'POST', - 'users/{}/content_migrations'.format(self.id), + "POST", + "users/{}/content_migrations".format(self.id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'user_id': self.id}) + response_json.update({"user_id": self.id}) return ContentMigration(self._requester, response_json) @@ -725,13 +725,13 @@ def get_content_migration(self, content_migration, **kwargs): ) response = self._requester.request( - 'GET', - 'users/{}/content_migrations/{}'.format(self.id, migration_id), + "GET", + "users/{}/content_migrations/{}".format(self.id, migration_id), _kwargs=combine_kwargs(**kwargs), ) response_json = response.json() - response_json.update({'user_id': self.id}) + response_json.update({"user_id": self.id}) return ContentMigration(self._requester, response_json) @@ -750,9 +750,9 @@ def get_content_migrations(self, **kwargs): return PaginatedList( ContentMigration, self._requester, - 'GET', - 'users/{}/content_migrations'.format(self.id), - {'user_id': self.id}, + "GET", + "users/{}/content_migrations".format(self.id), + {"user_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -771,8 +771,8 @@ def get_migration_systems(self, **kwargs): return PaginatedList( Migrator, self._requester, - 'GET', - 'users/{}/content_migrations/migrators'.format(self.id), + "GET", + "users/{}/content_migrations/migrators".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -791,8 +791,8 @@ def get_content_exports(self, **kwargs): return PaginatedList( ContentExport, self._requester, - 'GET', - 'users/{}/content_exports'.format(self.id), + "GET", + "users/{}/content_exports".format(self.id), kwargs=combine_kwargs(**kwargs), ) @@ -813,8 +813,8 @@ def get_content_export(self, content_export, **kwargs): export_id = obj_or_id(content_export, "content_export", (ContentExport,)) response = self._requester.request( - 'GET', - 'users/{}/content_exports/{}'.format(self.id, export_id), + "GET", + "users/{}/content_exports/{}".format(self.id, export_id), _kwargs=combine_kwargs(**kwargs), ) @@ -834,11 +834,11 @@ def export_content(self, export_type, **kwargs): """ from canvasapi.content_export import ContentExport - kwargs['export_type'] = export_type + kwargs["export_type"] = export_type response = self._requester.request( - 'POST', - 'users/{}/content_exports'.format(self.id), + "POST", + "users/{}/content_exports".format(self.id), _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json()) @@ -858,9 +858,9 @@ def get_open_poll_sessions(self, **kwargs): return PaginatedList( PollSession, self._requester, - 'GET', - 'poll_sessions/opened', - _root='poll_sessions', + "GET", + "poll_sessions/opened", + _root="poll_sessions", _kwargs=combine_kwargs(**kwargs), ) @@ -879,9 +879,9 @@ def get_closed_poll_sessions(self, **kwargs): return PaginatedList( PollSession, self._requester, - 'GET', - 'poll_sessions/closed', - _root='poll_sessions', + "GET", + "poll_sessions/closed", + _root="poll_sessions", _kwargs=combine_kwargs(**kwargs), ) diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 0097e9f6..00000000 --- a/pyproject.toml +++ /dev/null @@ -1,2 +0,0 @@ -[tool.black] -skip-string-normalization = true diff --git a/tests/settings.py b/tests/settings.py index 536a5e24..4fbbcab8 100644 --- a/tests/settings.py +++ b/tests/settings.py @@ -1,10 +1,10 @@ from __future__ import absolute_import, division, print_function, unicode_literals -BASE_URL = 'https://example.com' -BASE_URL_WITH_VERSION = 'https://example.com/api/v1/' -BASE_URL_AS_HTTP = 'http://example.com' -BASE_URL_AS_BLANK = '' -BASE_URL_AS_INVALID = 'example.com' -API_KEY = '123' +BASE_URL = "https://example.com" +BASE_URL_WITH_VERSION = "https://example.com/api/v1/" +BASE_URL_AS_HTTP = "http://example.com" +BASE_URL_AS_BLANK = "" +BASE_URL_AS_INVALID = "example.com" +API_KEY = "123" INVALID_ID = 9001 diff --git a/tests/test_account.py b/tests/test_account.py index 8db73ef9..646af870 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -42,7 +42,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = {'account': ['get_by_id', 'get_role'], 'user': ['get_by_id']} + requires = {"account": ["get_by_id", "get_role"], "user": ["get_by_id"]} register_uris(requires, m) self.account = self.canvas.get_account(1) @@ -56,50 +56,50 @@ def test__str__(self, m): # close_notification_for_user() def test_close_notification_for_user_id(self, m): - register_uris({'account': ['close_notification']}, m) + register_uris({"account": ["close_notification"]}, m) user_id = self.user.id notif_id = 1 closed_notif = self.account.close_notification_for_user(user_id, notif_id) self.assertIsInstance(closed_notif, AccountNotification) - self.assertTrue(hasattr(closed_notif, 'subject')) + self.assertTrue(hasattr(closed_notif, "subject")) def test_close_notification_for_user_obj(self, m): - register_uris({'account': ['close_notification']}, m) + register_uris({"account": ["close_notification"]}, m) notif_id = 1 self.account.close_notification_for_user(self.user, notif_id) # create_account() def test_create_account(self, m): - register_uris({'account': ['create_2']}, m) + register_uris({"account": ["create_2"]}, m) new_account = self.account.create_account() self.assertIsInstance(new_account, Account) - self.assertTrue(hasattr(new_account, 'id')) + self.assertTrue(hasattr(new_account, "id")) # create_course() def test_create_course(self, m): - register_uris({'account': ['create_course']}, m) + register_uris({"account": ["create_course"]}, m) course = self.account.create_course() self.assertIsInstance(course, Course) - self.assertTrue(hasattr(course, 'name')) + self.assertTrue(hasattr(course, "name")) # create_subaccount() def test_create_subaccount(self, m): - register_uris({'account': ['create_subaccount']}, m) + register_uris({"account": ["create_subaccount"]}, m) subaccount_name = "New Subaccount" - subaccount = self.account.create_subaccount({'name': subaccount_name}) + subaccount = self.account.create_subaccount({"name": subaccount_name}) self.assertIsInstance(subaccount, Account) - self.assertTrue(hasattr(subaccount, 'name')) + self.assertTrue(hasattr(subaccount, "name")) self.assertEqual(subaccount.name, subaccount_name) - self.assertTrue(hasattr(subaccount, 'root_account_id')) + self.assertTrue(hasattr(subaccount, "root_account_id")) self.assertEqual(subaccount.root_account_id, self.account.id) def test_create_course_missing_field(self, m): @@ -108,13 +108,13 @@ def test_create_course_missing_field(self, m): # create_user() def test_create_user(self, m): - register_uris({'account': ['create_user']}, m) + register_uris({"account": ["create_user"]}, m) unique_id = 123456 - user = self.account.create_user({'unique_id': unique_id}) + user = self.account.create_user({"unique_id": unique_id}) self.assertIsInstance(user, User) - self.assertTrue(hasattr(user, 'unique_id')) + self.assertTrue(hasattr(user, "unique_id")) self.assertEqual(user.unique_id, unique_id) def test_create_user_missing_field(self, m): @@ -123,21 +123,21 @@ def test_create_user_missing_field(self, m): # create_notification() def test_create_notification(self, m): - register_uris({'account': ['create_notification']}, m) + register_uris({"account": ["create_notification"]}, m) - subject = 'Subject' + subject = "Subject" notif_dict = { - 'subject': subject, - 'message': 'Message', - 'start_at': '2015-04-01T00:00:00Z', - 'end_at': '2018-04-01T00:00:00Z', + "subject": subject, + "message": "Message", + "start_at": "2015-04-01T00:00:00Z", + "end_at": "2018-04-01T00:00:00Z", } notif = self.account.create_notification(notif_dict) self.assertIsInstance(notif, AccountNotification) - self.assertTrue(hasattr(notif, 'subject')) + self.assertTrue(hasattr(notif, "subject")) self.assertEqual(notif.subject, subject) - self.assertTrue(hasattr(notif, 'start_at_date')) + self.assertTrue(hasattr(notif, "start_at_date")) self.assertIsInstance(notif.start_at_date, datetime.datetime) self.assertEqual(notif.start_at_date.tzinfo, pytz.utc) @@ -147,9 +147,9 @@ def test_create_notification_missing_field(self, m): # delete() def test_delete(self, m): - register_uris({'account': ['create_subaccount', 'delete_subaccount']}, m) + register_uris({"account": ["create_subaccount", "delete_subaccount"]}, m) - subaccount = self.account.create_subaccount({'name': 'New Subaccount'}) + subaccount = self.account.create_subaccount({"name": "New Subaccount"}) self.assertTrue(subaccount.delete()) @@ -159,24 +159,24 @@ def test_delete_root_account(self, m): # delete_user() def test_delete_user_id(self, m): - register_uris({'account': ['delete_user']}, m) + register_uris({"account": ["delete_user"]}, m) deleted_user = self.account.delete_user(self.user.id) self.assertIsInstance(deleted_user, User) - self.assertTrue(hasattr(deleted_user, 'name')) + self.assertTrue(hasattr(deleted_user, "name")) def test_delete_user_obj(self, m): - register_uris({'account': ['delete_user']}, m) + register_uris({"account": ["delete_user"]}, m) deleted_user = self.account.delete_user(self.user) self.assertIsInstance(deleted_user, User) - self.assertTrue(hasattr(deleted_user, 'name')) + self.assertTrue(hasattr(deleted_user, "name")) # get_courses() def test_get_courses(self, m): - required = {'account': ['get_courses', 'get_courses_page_2']} + required = {"account": ["get_courses", "get_courses_page_2"]} register_uris(required, m) courses = self.account.get_courses() @@ -184,24 +184,24 @@ def test_get_courses(self, m): course_list = [course for course in courses] self.assertEqual(len(course_list), 4) self.assertIsInstance(course_list[0], Course) - self.assertTrue(hasattr(course_list[0], 'name')) + self.assertTrue(hasattr(course_list[0], "name")) # get_external_tool() def test_get_external_tool(self, m): - required = {'external_tool': ['get_by_id_account']} + required = {"external_tool": ["get_by_id_account"]} register_uris(required, m) tool_by_id = self.account.get_external_tool(1) self.assertIsInstance(tool_by_id, ExternalTool) - self.assertTrue(hasattr(tool_by_id, 'name')) + self.assertTrue(hasattr(tool_by_id, "name")) tool_by_obj = self.account.get_external_tool(tool_by_id) self.assertIsInstance(tool_by_obj, ExternalTool) - self.assertTrue(hasattr(tool_by_obj, 'name')) + self.assertTrue(hasattr(tool_by_obj, "name")) # get_external_tools() def test_get_external_tools(self, m): - required = {'account': ['get_external_tools', 'get_external_tools_p2']} + required = {"account": ["get_external_tools", "get_external_tools_p2"]} register_uris(required, m) tools = self.account.get_external_tools() @@ -212,7 +212,7 @@ def test_get_external_tools(self, m): # get_index_of_reports() def test_get_index_of_reports(self, m): - required = {'account': ['report_index', 'report_index_page_2']} + required = {"account": ["report_index", "report_index_page_2"]} register_uris(required, m) reports_index = self.account.get_index_of_reports("sis_export_csv") @@ -220,11 +220,11 @@ def test_get_index_of_reports(self, m): reports_index_list = [index for index in reports_index] self.assertEqual(len(reports_index_list), 4) self.assertIsInstance(reports_index_list[0], AccountReport) - self.assertTrue(hasattr(reports_index_list[0], 'id')) + self.assertTrue(hasattr(reports_index_list[0], "id")) # get_reports() def test_get_reports(self, m): - required = {'account': ['reports', 'reports_page_2']} + required = {"account": ["reports", "reports_page_2"]} register_uris(required, m) reports = self.account.get_reports() @@ -232,11 +232,11 @@ def test_get_reports(self, m): reports_list = [report for report in reports] self.assertEqual(len(reports_list), 4) self.assertIsInstance(reports_list[0], AccountReport) - self.assertTrue(hasattr(reports_list[0], 'id')) + self.assertTrue(hasattr(reports_list[0], "id")) # get_subaccounts() def test_get_subaccounts(self, m): - required = {'account': ['subaccounts', 'subaccounts_page_2']} + required = {"account": ["subaccounts", "subaccounts_page_2"]} register_uris(required, m) subaccounts = self.account.get_subaccounts() @@ -244,11 +244,11 @@ def test_get_subaccounts(self, m): subaccounts_list = [account for account in subaccounts] self.assertEqual(len(subaccounts_list), 4) self.assertIsInstance(subaccounts_list[0], Account) - self.assertTrue(hasattr(subaccounts_list[0], 'name')) + self.assertTrue(hasattr(subaccounts_list[0], "name")) # get_users() def test_get_users(self, m): - required = {'account': ['users', 'users_page_2']} + required = {"account": ["users", "users_page_2"]} register_uris(required, m) users = self.account.get_users() @@ -256,11 +256,11 @@ def test_get_users(self, m): user_list = [user for user in users] self.assertEqual(len(user_list), 4) self.assertIsInstance(user_list[0], User) - self.assertTrue(hasattr(user_list[0], 'name')) + self.assertTrue(hasattr(user_list[0], "name")) # get_user_notifications() def test_get_user_notifications_id(self, m): - required = {'account': ['user_notifs', 'user_notifs_page_2']} + required = {"account": ["user_notifs", "user_notifs_page_2"]} register_uris(required, m) user_notifs = self.account.get_user_notifications(self.user.id) @@ -268,10 +268,10 @@ def test_get_user_notifications_id(self, m): notif_list = [notif for notif in user_notifs] self.assertEqual(len(notif_list), 4) self.assertIsInstance(user_notifs[0], AccountNotification) - self.assertTrue(hasattr(user_notifs[0], 'subject')) + self.assertTrue(hasattr(user_notifs[0], "subject")) def test_get_user_notifications_obj(self, m): - required = {'account': ['user_notifs', 'user_notifs_page_2']} + required = {"account": ["user_notifs", "user_notifs_page_2"]} register_uris(required, m) user_notifs = self.account.get_user_notifications(self.user) @@ -279,33 +279,33 @@ def test_get_user_notifications_obj(self, m): notif_list = [notif for notif in user_notifs] self.assertEqual(len(notif_list), 4) self.assertIsInstance(user_notifs[0], AccountNotification) - self.assertTrue(hasattr(user_notifs[0], 'subject')) + self.assertTrue(hasattr(user_notifs[0], "subject")) # update() def test_update(self, m): - register_uris({'account': ['update']}, m) + register_uris({"account": ["update"]}, m) - self.assertEqual(self.account.name, 'Canvas Account') + self.assertEqual(self.account.name, "Canvas Account") - new_name = 'Updated Name' - update_account_dict = {'name': new_name} + new_name = "Updated Name" + update_account_dict = {"name": new_name} self.assertTrue(self.account.update(account=update_account_dict)) self.assertEqual(self.account.name, new_name) def test_update_fail(self, m): - register_uris({'account': ['update_fail']}, m) + register_uris({"account": ["update_fail"]}, m) - self.assertEqual(self.account.name, 'Canvas Account') + self.assertEqual(self.account.name, "Canvas Account") - new_name = 'Updated Name' - update_account_dict = {'name': new_name} + new_name = "Updated Name" + update_account_dict = {"name": new_name} self.assertFalse(self.account.update(account=update_account_dict)) # list_roles() def test_list_roles(self, m): - requires = {'account': ['get_roles', 'get_roles_2']} + requires = {"account": ["get_roles", "get_roles_2"]} register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: @@ -314,15 +314,15 @@ def test_list_roles(self, m): self.assertEqual(len(role_list), 4) self.assertIsInstance(role_list[0], Role) - self.assertTrue(hasattr(role_list[0], 'role')) - self.assertTrue(hasattr(role_list[0], 'label')) + self.assertTrue(hasattr(role_list[0], "role")) + self.assertTrue(hasattr(role_list[0], "label")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_roles() def test_get_roles(self, m): - requires = {'account': ['get_roles', 'get_roles_2']} + requires = {"account": ["get_roles", "get_roles_2"]} register_uris(requires, m) roles = self.account.get_roles() @@ -330,72 +330,72 @@ def test_get_roles(self, m): self.assertEqual(len(role_list), 4) self.assertIsInstance(role_list[0], Role) - self.assertTrue(hasattr(role_list[0], 'role')) - self.assertTrue(hasattr(role_list[0], 'label')) + self.assertTrue(hasattr(role_list[0], "role")) + self.assertTrue(hasattr(role_list[0], "label")) def test_get_role(self, m): - register_uris({'account': ['get_role']}, m) + register_uris({"account": ["get_role"]}, m) target_role_by_id = self.account.get_role(2) self.assertIsInstance(target_role_by_id, Role) - self.assertTrue(hasattr(target_role_by_id, 'role')) - self.assertTrue(hasattr(target_role_by_id, 'label')) + self.assertTrue(hasattr(target_role_by_id, "role")) + self.assertTrue(hasattr(target_role_by_id, "label")) target_role_by_obj = self.account.get_role(self.role) self.assertIsInstance(target_role_by_obj, Role) - self.assertTrue(hasattr(target_role_by_obj, 'role')) - self.assertTrue(hasattr(target_role_by_obj, 'label')) + self.assertTrue(hasattr(target_role_by_obj, "role")) + self.assertTrue(hasattr(target_role_by_obj, "label")) def test_create_role(self, m): - register_uris({'account': ['create_role']}, m) + register_uris({"account": ["create_role"]}, m) new_role = self.account.create_role(1) self.assertIsInstance(new_role, Role) - self.assertTrue(hasattr(new_role, 'role')) - self.assertTrue(hasattr(new_role, 'label')) + self.assertTrue(hasattr(new_role, "role")) + self.assertTrue(hasattr(new_role, "label")) def test_deactivate_role(self, m): - register_uris({'account': ['deactivate_role']}, m) + register_uris({"account": ["deactivate_role"]}, m) old_role_by_id = self.account.deactivate_role(2) self.assertIsInstance(old_role_by_id, Role) - self.assertTrue(hasattr(old_role_by_id, 'role')) - self.assertTrue(hasattr(old_role_by_id, 'label')) + self.assertTrue(hasattr(old_role_by_id, "role")) + self.assertTrue(hasattr(old_role_by_id, "label")) old_role_by_obj = self.account.deactivate_role(self.role) self.assertIsInstance(old_role_by_obj, Role) - self.assertTrue(hasattr(old_role_by_obj, 'role')) - self.assertTrue(hasattr(old_role_by_obj, 'label')) + self.assertTrue(hasattr(old_role_by_obj, "role")) + self.assertTrue(hasattr(old_role_by_obj, "label")) def test_activate_role(self, m): - register_uris({'account': ['activate_role']}, m) + register_uris({"account": ["activate_role"]}, m) activated_role_by_id = self.account.activate_role(2) self.assertIsInstance(activated_role_by_id, Role) - self.assertTrue(hasattr(activated_role_by_id, 'role')) - self.assertTrue(hasattr(activated_role_by_id, 'label')) + self.assertTrue(hasattr(activated_role_by_id, "role")) + self.assertTrue(hasattr(activated_role_by_id, "label")) activated_role_by_obj = self.account.activate_role(self.role) self.assertIsInstance(activated_role_by_obj, Role) - self.assertTrue(hasattr(activated_role_by_obj, 'role')) - self.assertTrue(hasattr(activated_role_by_obj, 'label')) + self.assertTrue(hasattr(activated_role_by_obj, "role")) + self.assertTrue(hasattr(activated_role_by_obj, "label")) def test_update_role(self, m): - register_uris({'account': ['update_role']}, m) + register_uris({"account": ["update_role"]}, m) updated_role_by_id = self.account.update_role(2) self.assertIsInstance(updated_role_by_id, Role) - self.assertTrue(hasattr(updated_role_by_id, 'role')) - self.assertTrue(hasattr(updated_role_by_id, 'label')) + self.assertTrue(hasattr(updated_role_by_id, "role")) + self.assertTrue(hasattr(updated_role_by_id, "label")) updated_role_by_obj = self.account.update_role(self.role) self.assertIsInstance(updated_role_by_obj, Role) - self.assertTrue(hasattr(updated_role_by_obj, 'role')) - self.assertTrue(hasattr(updated_role_by_obj, 'label')) + self.assertTrue(hasattr(updated_role_by_obj, "role")) + self.assertTrue(hasattr(updated_role_by_obj, "label")) # get_enrollment() def test_get_enrollment(self, m): - register_uris({'enrollment': ['get_by_id']}, m) + register_uris({"enrollment": ["get_by_id"]}, m) enrollment_by_id = self.account.get_enrollment(1) self.assertIsInstance(enrollment_by_id, Enrollment) @@ -405,7 +405,7 @@ def test_get_enrollment(self, m): # list_groups() def test_list_groups(self, m): - requires = {'account': ['get_groups_context', 'get_groups_context2']} + requires = {"account": ["get_groups_context", "get_groups_context2"]} register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: @@ -420,7 +420,7 @@ def test_list_groups(self, m): # get_groups() def test_get_groups(self, m): - requires = {'account': ['get_groups_context', 'get_groups_context2']} + requires = {"account": ["get_groups_context", "get_groups_context2"]} register_uris(requires, m) groups = self.account.get_groups() @@ -431,7 +431,7 @@ def test_get_groups(self, m): # create_group_category() def test_create_group_category(self, m): - register_uris({'account': ['create_group_category']}, m) + register_uris({"account": ["create_group_category"]}, m) name_str = "Test String" response = self.account.create_group_category(name=name_str) @@ -439,7 +439,7 @@ def test_create_group_category(self, m): # list_group_categories() def test_list_group_categories(self, m): - register_uris({'account': ['get_group_categories']}, m) + register_uris({"account": ["get_group_categories"]}, m) with warnings.catch_warnings(record=True) as warning_list: response = self.account.list_group_categories() @@ -452,7 +452,7 @@ def test_list_group_categories(self, m): # get_group_categories() def test_get_group_categories(self, m): - register_uris({'account': ['get_group_categories']}, m) + register_uris({"account": ["get_group_categories"]}, m) response = self.account.get_group_categories() category_list = [category for category in response] @@ -461,7 +461,7 @@ def test_get_group_categories(self, m): # create_external_tool() def test_create_external_tool(self, m): - register_uris({'external_tool': ['create_tool_account']}, m) + register_uris({"external_tool": ["create_tool_account"]}, m) response = self.account.create_external_tool( name="External Tool - Account", @@ -471,12 +471,12 @@ def test_create_external_tool(self, m): ) self.assertIsInstance(response, ExternalTool) - self.assertTrue(hasattr(response, 'id')) + self.assertTrue(hasattr(response, "id")) self.assertEqual(response.id, 10) # create_enrollment_term() def test_create_enrollment_term(self, m): - register_uris({'enrollment_term': ['create_enrollment_term']}, m) + register_uris({"enrollment_term": ["create_enrollment_term"]}, m) evnt = self.account.create_enrollment_term(name="Test Enrollment Term", id=45) @@ -486,7 +486,7 @@ def test_create_enrollment_term(self, m): # list_enrollment_terms() def test_list_enrollment_terms(self, m): - register_uris({'account': ['get_enrollment_terms']}, m) + register_uris({"account": ["get_enrollment_terms"]}, m) with warnings.catch_warnings(record=True) as warning_list: response = self.account.list_enrollment_terms() @@ -499,7 +499,7 @@ def test_list_enrollment_terms(self, m): # get_enrollment_terms() def test_get_enrollment_terms(self, m): - register_uris({'account': ['get_enrollment_terms']}, m) + register_uris({"account": ["get_enrollment_terms"]}, m) response = self.account.get_enrollment_terms() enrollment_terms_list = [category for category in response] @@ -508,7 +508,7 @@ def test_get_enrollment_terms(self, m): # list_user_logins() def test_list_user_logins(self, m): - requires = {'account': ['get_user_logins', 'get_user_logins_2']} + requires = {"account": ["get_user_logins", "get_user_logins_2"]} register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: @@ -523,7 +523,7 @@ def test_list_user_logins(self, m): # get_user_logins() def test_get_user_logins(self, m): - requires = {'account': ['get_user_logins', 'get_user_logins_2']} + requires = {"account": ["get_user_logins", "get_user_logins_2"]} register_uris(requires, m) response = self.account.get_user_logins() @@ -534,17 +534,17 @@ def test_get_user_logins(self, m): # create_user_login() def test_create_user_login(self, m): - register_uris({'login': ['create_user_login']}, m) + register_uris({"login": ["create_user_login"]}, m) - unique_id = 'belieber@example.com' + unique_id = "belieber@example.com" response = self.account.create_user_login( - user={'id': 1}, login={'unique_id': unique_id} + user={"id": 1}, login={"unique_id": unique_id} ) self.assertIsInstance(response, Login) - self.assertTrue(hasattr(response, 'id')) - self.assertTrue(hasattr(response, 'unique_id')) + self.assertTrue(hasattr(response, "id")) + self.assertTrue(hasattr(response, "unique_id")) self.assertEqual(response.id, 101) self.assertEqual(response.unique_id, unique_id) @@ -554,12 +554,12 @@ def test_create_user_login_fail_on_user_id(self, m): def test_create_user_login_fail_on_login_unique_id(self, m): with self.assertRaises(RequiredFieldMissing): - self.account.create_user_login(user={'id': 1}, login={}) + self.account.create_user_login(user={"id": 1}, login={}) # get_department_level_participation_data_with_given_term() def test_get_department_level_participation_data_with_given_term(self, m): register_uris( - {'account': ['get_department_level_participation_data_with_given_term']}, m + {"account": ["get_department_level_participation_data_with_given_term"]}, m ) response = self.account.get_department_level_participation_data_with_given_term( @@ -571,7 +571,7 @@ def test_get_department_level_participation_data_with_given_term(self, m): # get_department_level_participation_data_current() def test_get_department_level_participation_data_current(self, m): register_uris( - {'account': ['get_department_level_participation_data_current']}, m + {"account": ["get_department_level_participation_data_current"]}, m ) response = self.account.get_department_level_participation_data_current() @@ -581,7 +581,7 @@ def test_get_department_level_participation_data_current(self, m): # get_department_level_participation_data_completed() def test_get_department_level_participation_data_completed(self, m): register_uris( - {'account': ['get_department_level_participation_data_completed']}, m + {"account": ["get_department_level_participation_data_completed"]}, m ) response = self.account.get_department_level_participation_data_completed() @@ -591,7 +591,7 @@ def test_get_department_level_participation_data_completed(self, m): # get_department_level_grade_data_with_given_term() def test_get_department_level_grade_data_with_given_term(self, m): register_uris( - {'account': ['get_department_level_grade_data_with_given_term']}, m + {"account": ["get_department_level_grade_data_with_given_term"]}, m ) response = self.account.get_department_level_grade_data_with_given_term(1) @@ -600,7 +600,7 @@ def test_get_department_level_grade_data_with_given_term(self, m): # get_department_level_grade_data_current() def test_get_department_level_grade_data_current(self, m): - register_uris({'account': ['get_department_level_grade_data_current']}, m) + register_uris({"account": ["get_department_level_grade_data_current"]}, m) response = self.account.get_department_level_grade_data_current() @@ -608,7 +608,7 @@ def test_get_department_level_grade_data_current(self, m): # get_department_level_grade_data_completed() def test_get_department_level_grade_data_completed(self, m): - register_uris({'account': ['get_department_level_grade_data_completed']}, m) + register_uris({"account": ["get_department_level_grade_data_completed"]}, m) response = self.account.get_department_level_grade_data_completed() @@ -617,7 +617,7 @@ def test_get_department_level_grade_data_completed(self, m): # get_department_level_statistics_with_given_term() def test_get_department_level_statistics_with_given_term(self, m): register_uris( - {'account': ['get_department_level_statistics_with_given_term']}, m + {"account": ["get_department_level_statistics_with_given_term"]}, m ) response = self.account.get_department_level_statistics_with_given_term(1) @@ -626,7 +626,7 @@ def test_get_department_level_statistics_with_given_term(self, m): # get_department_level_statistics_current() def test_get_department_level_statistics_current(self, m): - register_uris({'account': ['get_department_level_statistics_current']}, m) + register_uris({"account": ["get_department_level_statistics_current"]}, m) response = self.account.get_department_level_statistics_current() @@ -634,7 +634,7 @@ def test_get_department_level_statistics_current(self, m): # get_department_level_statistics_completed() def test_get_department_level_statistics_completed(self, m): - register_uris({'account': ['get_department_level_statistics_completed']}, m) + register_uris({"account": ["get_department_level_statistics_completed"]}, m) response = self.account.get_department_level_statistics_completed() @@ -643,9 +643,9 @@ def test_get_department_level_statistics_completed(self, m): # list_authentication_providers() def test_list_authentication_providers(self, m): requires = { - 'account': [ - 'list_authentication_providers', - 'list_authentication_providers_2', + "account": [ + "list_authentication_providers", + "list_authentication_providers_2", ] } register_uris(requires, m) @@ -661,8 +661,8 @@ def test_list_authentication_providers(self, m): self.assertIsInstance( authentication_providers_list[0], AuthenticationProvider ) - self.assertTrue(hasattr(authentication_providers_list[0], 'auth_type')) - self.assertTrue(hasattr(authentication_providers_list[0], 'position')) + self.assertTrue(hasattr(authentication_providers_list[0], "auth_type")) + self.assertTrue(hasattr(authentication_providers_list[0], "position")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -670,9 +670,9 @@ def test_list_authentication_providers(self, m): # get_authentication_providers() def test_get_authentication_providers(self, m): requires = { - 'account': [ - 'list_authentication_providers', - 'list_authentication_providers_2', + "account": [ + "list_authentication_providers", + "list_authentication_providers_2", ] } register_uris(requires, m) @@ -685,22 +685,22 @@ def test_get_authentication_providers(self, m): self.assertEqual(len(authentication_providers_list), 4) self.assertIsInstance(authentication_providers_list[0], AuthenticationProvider) - self.assertTrue(hasattr(authentication_providers_list[0], 'auth_type')) - self.assertTrue(hasattr(authentication_providers_list[0], 'position')) + self.assertTrue(hasattr(authentication_providers_list[0], "auth_type")) + self.assertTrue(hasattr(authentication_providers_list[0], "position")) # add_authentication_providers() def test_add_authentication_providers(self, m): - register_uris({'account': ['add_authentication_providers']}, m) + register_uris({"account": ["add_authentication_providers"]}, m) new_authentication_provider = self.account.add_authentication_providers() self.assertIsInstance(new_authentication_provider, AuthenticationProvider) - self.assertTrue(hasattr(new_authentication_provider, 'auth_type')) - self.assertTrue(hasattr(new_authentication_provider, 'position')) + self.assertTrue(hasattr(new_authentication_provider, "auth_type")) + self.assertTrue(hasattr(new_authentication_provider, "position")) # get_authentication_provider() def test_get_authentication_provider(self, m): - register_uris({'account': ['get_authentication_providers']}, m) + register_uris({"account": ["get_authentication_providers"]}, m) authentication_provider_by_id = self.account.get_authentication_provider(1) self.assertIsInstance(authentication_provider_by_id, AuthenticationProvider) @@ -712,7 +712,7 @@ def test_get_authentication_provider(self, m): # show_account_auth_settings() def test_show_account_auth_settings(self, m): - register_uris({'account': ['show_account_auth_settings']}, m) + register_uris({"account": ["show_account_auth_settings"]}, m) response = self.account.show_account_auth_settings() @@ -720,7 +720,7 @@ def test_show_account_auth_settings(self, m): # update_account_auth_settings() def test_update_account_auth_settings(self, m): - register_uris({'account': ['update_account_auth_settings']}, m) + register_uris({"account": ["update_account_auth_settings"]}, m) response = self.account.update_account_auth_settings() @@ -728,7 +728,7 @@ def test_update_account_auth_settings(self, m): # get_root_outcome_group() def test_get_root_outcome_group(self, m): - register_uris({'outcome': ['account_root_outcome_group']}, m) + register_uris({"outcome": ["account_root_outcome_group"]}, m) outcome_group = self.account.get_root_outcome_group() @@ -738,7 +738,7 @@ def test_get_root_outcome_group(self, m): # get_outcome_group() def test_get_outcome_group(self, m): - register_uris({'outcome': ['account_get_outcome_group']}, m) + register_uris({"outcome": ["account_get_outcome_group"]}, m) outcome_group_by_id = self.account.get_outcome_group(1) self.assertIsInstance(outcome_group_by_id, OutcomeGroup) @@ -752,7 +752,7 @@ def test_get_outcome_group(self, m): # get_outcome_groups_in_context() def test_get_outcome_groups_in_context(self, m): - register_uris({'outcome': ['account_outcome_groups_in_context']}, m) + register_uris({"outcome": ["account_outcome_groups_in_context"]}, m) outcome_group_list = self.account.get_outcome_groups_in_context() @@ -762,17 +762,17 @@ def test_get_outcome_groups_in_context(self, m): # get_all_outcome_links_in_context() def test_get_outcome_links_in_context(self, m): - register_uris({'outcome': ['account_outcome_links_in_context']}, m) + register_uris({"outcome": ["account_outcome_links_in_context"]}, m) outcome_link_list = self.account.get_all_outcome_links_in_context() self.assertIsInstance(outcome_link_list[0], OutcomeLink) - self.assertEqual(outcome_link_list[0].outcome_group['id'], 2) - self.assertEqual(outcome_link_list[0].outcome_group['title'], "test outcome") + self.assertEqual(outcome_link_list[0].outcome_group["id"], 2) + self.assertEqual(outcome_link_list[0].outcome_group["title"], "test outcome") # add_grading_standards() def test_add_grading_standards(self, m): - register_uris({'account': ['add_grading_standards']}, m) + register_uris({"account": ["add_grading_standards"]}, m) title = "Grading Standard 1" grading_scheme = [] @@ -783,36 +783,36 @@ def test_add_grading_standards(self, m): response = self.account.add_grading_standards(title, grading_scheme) self.assertIsInstance(response, GradingStandard) - self.assertTrue(hasattr(response, 'title')) + self.assertTrue(hasattr(response, "title")) self.assertEqual(title, response.title) self.assertTrue(hasattr(response, "grading_scheme")) - self.assertEqual(response.grading_scheme[0].get('name'), "A") - self.assertEqual(response.grading_scheme[0].get('value'), 0.9) + self.assertEqual(response.grading_scheme[0].get("name"), "A") + self.assertEqual(response.grading_scheme[0].get("value"), 0.9) # add_grading_standards() def test_add_grading_standards_empty_list(self, m): - register_uris({'account': ['add_grading_standards']}, m) + register_uris({"account": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): self.account.add_grading_standards("title", []) def test_add_grading_standards_non_dict_list(self, m): - register_uris({'account': ['add_grading_standards']}, m) + register_uris({"account": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): self.account.add_grading_standards("title", [1, 2, 3]) def test_add_grading_standards_missing_value_key(self, m): - register_uris({'account': ['add_grading_standards']}, m) + register_uris({"account": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): - self.account.add_grading_standards("title", [{'name': "test"}]) + self.account.add_grading_standards("title", [{"name": "test"}]) def test_add_grading_standards_missing_name_key(self, m): - register_uris({'account': ['add_grading_standards']}, m) + register_uris({"account": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): - self.account.add_grading_standards("title", [{'value': 2}]) + self.account.add_grading_standards("title", [{"value": 2}]) # get_grading_standards() def test_get_grading_standards(self, m): - register_uris({'account': ['get_grading_standards']}, m) + register_uris({"account": ["get_grading_standards"]}, m) standards = self.account.get_grading_standards() standard_list = [standard for standard in standards] @@ -822,22 +822,22 @@ def test_get_grading_standards(self, m): # get_single_grading_standards() def test_get_single_grading_standard(self, m): - register_uris({'account': ['get_single_grading_standard']}, m) + register_uris({"account": ["get_single_grading_standard"]}, m) response = self.account.get_single_grading_standard(1) self.assertIsInstance(response, GradingStandard) - self.assertTrue(hasattr(response, 'id')) + self.assertTrue(hasattr(response, "id")) self.assertEqual(1, response.id) - self.assertTrue(hasattr(response, 'title')) + self.assertTrue(hasattr(response, "title")) self.assertEqual("Grading Standard 1", response.title) self.assertTrue(hasattr(response, "grading_scheme")) - self.assertEqual(response.grading_scheme[0].get('name'), "A") - self.assertEqual(response.grading_scheme[0].get('value'), 0.9) + self.assertEqual(response.grading_scheme[0].get("name"), "A") + self.assertEqual(response.grading_scheme[0].get("value"), 0.9) # get_rubric def test_get_rubric(self, m): - register_uris({'account': ['get_rubric_single']}, m) + register_uris({"account": ["get_rubric_single"]}, m) rubric_id = 1 rubric = self.account.get_rubric(rubric_id) @@ -848,7 +848,7 @@ def test_get_rubric(self, m): # list_rubrics def test_list_rubrics(self, m): - register_uris({'account': ['get_rubric_multiple']}, m) + register_uris({"account": ["get_rubric_multiple"]}, m) with warnings.catch_warnings(record=True) as warning_list: rubrics = self.account.list_rubrics() @@ -867,7 +867,7 @@ def test_list_rubrics(self, m): # get_rubrics def test_get_rubrics(self, m): - register_uris({'account': ['get_rubric_multiple']}, m) + register_uris({"account": ["get_rubric_multiple"]}, m) rubrics = self.account.get_rubrics() @@ -882,16 +882,16 @@ def test_get_rubrics(self, m): # create_content_migration def test_create_content_migration(self, m): - register_uris({'account': ['create_content_migration']}, m) + register_uris({"account": ["create_content_migration"]}, m) - content_migration = self.account.create_content_migration('dummy_importer') + content_migration = self.account.create_content_migration("dummy_importer") self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_migrator(self, m): register_uris( - {'account': ['create_content_migration', 'get_migration_systems_multiple']}, + {"account": ["create_content_migration", "get_migration_systems_multiple"]}, m, ) @@ -899,26 +899,26 @@ def test_create_content_migration_migrator(self, m): content_migration = self.account.create_content_migration(migrators[0]) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_bad_migration_type(self, m): - register_uris({'account': ['create_content_migration']}, m) + register_uris({"account": ["create_content_migration"]}, m) with self.assertRaises(TypeError): self.account.create_content_migration(1) # get_content_migration def test_get_content_migration(self, m): - register_uris({'account': ['get_content_migration_single']}, m) + register_uris({"account": ["get_content_migration_single"]}, m) content_migration = self.account.get_content_migration(1) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) # get_content_migrations def test_get_content_migrations(self, m): - register_uris({'account': ['get_content_migration_multiple']}, m) + register_uris({"account": ["get_content_migration_multiple"]}, m) content_migrations = self.account.get_content_migrations() @@ -933,7 +933,7 @@ def test_get_content_migrations(self, m): # get_migration_systems def test_get_migration_systems(self, m): - register_uris({'account': ['get_migration_systems_multiple']}, m) + register_uris({"account": ["get_migration_systems_multiple"]}, m) migration_systems = self.account.get_migration_systems() @@ -950,7 +950,7 @@ def test_get_migration_systems(self, m): # get_admins() def test_get_admins(self, m): - register_uris({'account': ['get_admins', 'get_admins_page_2']}, m) + register_uris({"account": ["get_admins", "get_admins_page_2"]}, m) admins = self.account.get_admins() admin_list = [admin for admin in admins] @@ -960,109 +960,109 @@ def test_get_admins(self, m): self.assertIsInstance(admin_list[0], Admin) self.assertIsInstance(admin_list[1], Admin) - self.assertTrue(hasattr(admin_list[0], 'id')) - self.assertTrue(hasattr(admin_list[1], 'role')) - self.assertTrue(hasattr(admin_list[0], 'role_id')) - self.assertTrue(hasattr(admin_list[1], 'workflow_state')) + self.assertTrue(hasattr(admin_list[0], "id")) + self.assertTrue(hasattr(admin_list[1], "role")) + self.assertTrue(hasattr(admin_list[0], "role_id")) + self.assertTrue(hasattr(admin_list[1], "workflow_state")) - self.assertEqual(admin_list[1].user['login_id'], 'jdoe') - self.assertEqual(admin_list[1].role, 'AccountAdmin') + self.assertEqual(admin_list[1].user["login_id"], "jdoe") + self.assertEqual(admin_list[1].role, "AccountAdmin") self.assertEqual(admin_list[0].role_id, 2) # create_sis_import() def test_create_sis_import(self, m): import os - register_uris({'account': ['create_sis_import']}, m) + register_uris({"account": ["create_sis_import"]}, m) - filepath = os.path.join('tests', 'fixtures', 'test_create_sis_import.csv') + filepath = os.path.join("tests", "fixtures", "test_create_sis_import.csv") sis_import = self.account.create_sis_import(filepath) self.assertTrue(isinstance(sis_import, SisImport)) - self.assertTrue(hasattr(sis_import, 'account_id')) - self.assertTrue(hasattr(sis_import, 'user')) + self.assertTrue(hasattr(sis_import, "account_id")) + self.assertTrue(hasattr(sis_import, "user")) - self.assertEqual(sis_import.account_id, sis_import.user['id']) + self.assertEqual(sis_import.account_id, sis_import.user["id"]) def test_create_sis_import_binary(self, m): import os - register_uris({'account': ['create_sis_import']}, m) + register_uris({"account": ["create_sis_import"]}, m) - filepath = os.path.join('tests', 'fixtures', 'test_create_sis_import.csv') + filepath = os.path.join("tests", "fixtures", "test_create_sis_import.csv") - with open(filepath, 'rb') as f: + with open(filepath, "rb") as f: sis_import = self.account.create_sis_import(f) self.assertIsInstance(sis_import, SisImport) - self.assertTrue(hasattr(sis_import, 'account_id')) - self.assertTrue(hasattr(sis_import, 'user')) + self.assertTrue(hasattr(sis_import, "account_id")) + self.assertTrue(hasattr(sis_import, "user")) - self.assertEqual(sis_import.account_id, sis_import.user['id']) + self.assertEqual(sis_import.account_id, sis_import.user["id"]) def test_create_sis_import_ioerror(self, m): - f = '!@#$%^&*()_+QWERTYUIOP{}|' + f = "!@#$%^&*()_+QWERTYUIOP{}|" with self.assertRaises(IOError): self.account.create_sis_import(f) # get_sis_import() def test_get_sis_import(self, m): - register_uris({'account': ['get_sis_import']}, m) + register_uris({"account": ["get_sis_import"]}, m) sis_import_id = 2 sis_import = self.account.get_sis_import(sis_import_id) self.assertIsInstance(sis_import, SisImport) - self.assertTrue(hasattr(sis_import, 'account_id')) + self.assertTrue(hasattr(sis_import, "account_id")) self.assertEqual(sis_import_id, sis_import.id) # get_sis_imports() def test_get_sis_imports(self, m): - register_uris({'account': ['get_sis_imports']}, m) + register_uris({"account": ["get_sis_imports"]}, m) sis_imports = self.account.get_sis_imports() self.assertIsInstance(sis_imports[0], SisImport) self.assertIsInstance(sis_imports[1], SisImport) - self.assertTrue(hasattr(sis_imports[0], 'account_id')) + self.assertTrue(hasattr(sis_imports[0], "account_id")) self.assertNotEqual(sis_imports[0].id, sis_imports[1].id) # get_sis_imports_running() def test_get_sis_imports_running(self, m): - register_uris({'account': ['get_sis_imports_running']}, m) + register_uris({"account": ["get_sis_imports_running"]}, m) sis_imports = self.account.get_sis_imports_running() self.assertIsInstance(sis_imports[0], SisImport) - self.assertTrue(hasattr(sis_imports[0], 'account_id')) + self.assertTrue(hasattr(sis_imports[0], "account_id")) for sis_import in sis_imports: self.assertEqual(sis_import.workflow_state, "importing") # abort_sis_imports_pending() def test_abort_sis_imports_pending(self, m): - register_uris({'account': ['abort_sis_imports_pending']}, m) + register_uris({"account": ["abort_sis_imports_pending"]}, m) aborted = self.account.abort_sis_imports_pending() self.assertTrue(aborted) def test_abort_sis_imports_pending_false(self, m): - register_uris({'account': ['abort_sis_imports_pending_false']}, m) + register_uris({"account": ["abort_sis_imports_pending_false"]}, m) aborted = self.account.abort_sis_imports_pending() self.assertFalse(aborted) def test_abort_sis_imports_pending_blank(self, m): - register_uris({'account': ['abort_sis_imports_pending_blank']}, m) + register_uris({"account": ["abort_sis_imports_pending_blank"]}, m) aborted = self.account.abort_sis_imports_pending() @@ -1070,17 +1070,17 @@ def test_abort_sis_imports_pending_blank(self, m): # create_admins() def test_create_admin(self, m): - register_uris({'account': ['create_admin']}, m) + register_uris({"account": ["create_admin"]}, m) user_id = 123 admin = self.account.create_admin(user=user_id) self.assertIsInstance(admin, Admin) - self.assertTrue(hasattr(admin, 'id')) - self.assertTrue(hasattr(admin, 'role')) - self.assertTrue(hasattr(admin, 'role_id')) - self.assertTrue(hasattr(admin, 'workflow_state')) - self.assertEqual(admin.user['login_id'], 'jdoe') - self.assertEqual(admin.role, 'AccountAdmin') + self.assertTrue(hasattr(admin, "id")) + self.assertTrue(hasattr(admin, "role")) + self.assertTrue(hasattr(admin, "role_id")) + self.assertTrue(hasattr(admin, "workflow_state")) + self.assertEqual(admin.user["login_id"], "jdoe") + self.assertEqual(admin.role, "AccountAdmin") self.assertEqual(admin.role_id, 1) # get_outcome_import_status() @@ -1154,7 +1154,7 @@ def test_import_outcome_ioerror(self, m): # get_grading_periods() def test_get_grading_periods(self, m): - register_uris({'account': ['get_grading_periods']}, m) + register_uris({"account": ["get_grading_periods"]}, m) response = self.account.get_grading_periods() @@ -1168,7 +1168,7 @@ def test_get_grading_periods(self, m): # delete_grading_periods() def test_delete_grading_periods(self, m): - register_uris({'account': ['delete_grading_period']}, m) + register_uris({"account": ["delete_grading_period"]}, m) self.grading_period = GradingPeriod( self.canvas._Canvas__requester, diff --git a/tests/test_appointment_group.py b/tests/test_appointment_group.py index 336b228e..bdde56e9 100644 --- a/tests/test_appointment_group.py +++ b/tests/test_appointment_group.py @@ -16,31 +16,31 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'appointment_group': ['get_appointment_group']}, m) + register_uris({"appointment_group": ["get_appointment_group"]}, m) self.appointment_group = self.canvas.get_appointment_group(567) # delete() def test_delete_appointment_group(self, m): - register_uris({'appointment_group': ['delete_appointment_group']}, m) + register_uris({"appointment_group": ["delete_appointment_group"]}, m) deleted_appointment_group = self.appointment_group.delete() self.assertIsInstance(deleted_appointment_group, AppointmentGroup) - self.assertTrue(hasattr(deleted_appointment_group, 'title')) - self.assertEqual(deleted_appointment_group.title, 'Test Group 3') + self.assertTrue(hasattr(deleted_appointment_group, "title")) + self.assertEqual(deleted_appointment_group.title, "Test Group 3") # edit() def test_edit_appointment_group(self, m): - register_uris({'appointment_group': ['edit_appointment_group']}, m) + register_uris({"appointment_group": ["edit_appointment_group"]}, m) - title = 'New Name' + title = "New Name" edited_appointment_group = self.appointment_group.edit( - appointment_group={'title': title, 'context_codes': {'course_765'}} + appointment_group={"title": title, "context_codes": {"course_765"}} ) self.assertIsInstance(edited_appointment_group, AppointmentGroup) - self.assertTrue(hasattr(edited_appointment_group, 'title')) + self.assertTrue(hasattr(edited_appointment_group, "title")) self.assertEqual(edited_appointment_group.title, title) def test_edit_appointment_group_fail(self, m): diff --git a/tests/test_assignment.py b/tests/test_assignment.py index 67e0d0c7..13bca611 100644 --- a/tests/test_assignment.py +++ b/tests/test_assignment.py @@ -21,28 +21,28 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'get_assignment_by_id']}, m) + register_uris({"course": ["get_by_id", "get_assignment_by_id"]}, m) self.course = self.canvas.get_course(1) self.assignment = self.course.get_assignment(1) # create_override() def test_create_override(self, m): - register_uris({'assignment': ['create_override']}, m) + register_uris({"assignment": ["create_override"]}, m) override = self.assignment.create_override( assignment_override={ - 'student_ids': [1, 2, 3], - 'title': 'New Assignment Override', + "student_ids": [1, 2, 3], + "title": "New Assignment Override", } ) self.assertIsInstance(override, AssignmentOverride) - self.assertEqual(override.title, 'New Assignment Override') + self.assertEqual(override.title, "New Assignment Override") # delete() def test_delete_assignments(self, m): - register_uris({'assignment': ['delete_assignment']}, m) + register_uris({"assignment": ["delete_assignment"]}, m) deleted_assignment = self.assignment.delete() @@ -50,18 +50,18 @@ def test_delete_assignments(self, m): # edit() def test_edit_assignment(self, m): - register_uris({'assignment': ['edit_assignment']}, m) + register_uris({"assignment": ["edit_assignment"]}, m) - name = 'New Name' - edited_assignment = self.assignment.edit(assignment={'name': name}) + name = "New Name" + edited_assignment = self.assignment.edit(assignment={"name": name}) self.assertIsInstance(edited_assignment, Assignment) - self.assertTrue(hasattr(edited_assignment, 'name')) + self.assertTrue(hasattr(edited_assignment, "name")) self.assertEqual(edited_assignment.name, name) # get_gradeable_students() def test_get_gradeable_students(self, m): - register_uris({'course': ['list_gradeable_students']}, m) + register_uris({"course": ["list_gradeable_students"]}, m) students = self.assignment.get_gradeable_students() student_list = [student for student in students] @@ -71,7 +71,7 @@ def test_get_gradeable_students(self, m): # get_override() def test_get_override(self, m): - register_uris({'assignment': ['get_assignment_override']}, m) + register_uris({"assignment": ["get_assignment_override"]}, m) override = self.assignment.get_override(1) @@ -81,9 +81,9 @@ def test_get_override(self, m): def test_get_overrides(self, m): register_uris( { - 'assignment': [ - 'list_assignment_overrides', - 'list_assignment_overrides_p2', + "assignment": [ + "list_assignment_overrides", + "list_assignment_overrides_p2", ] }, m, @@ -98,7 +98,7 @@ def test_get_overrides(self, m): # get_peer_reviews() def test_get_peer_reviews(self, m): - register_uris({'assignment': ['list_peer_reviews']}, m) + register_uris({"assignment": ["list_peer_reviews"]}, m) peer_reviews = self.assignment.get_peer_reviews() peer_review_list = [peer_review for peer_review in peer_reviews] @@ -108,21 +108,21 @@ def test_get_peer_reviews(self, m): # get_submission() def test_get_submission(self, m): - register_uris({'submission': ['get_by_id_course'], 'user': ['get_by_id']}, m) + register_uris({"submission": ["get_by_id_course"], "user": ["get_by_id"]}, m) user_id = 1 submission_by_id = self.assignment.get_submission(user_id) self.assertIsInstance(submission_by_id, Submission) - self.assertTrue(hasattr(submission_by_id, 'submission_type')) + self.assertTrue(hasattr(submission_by_id, "submission_type")) user = self.canvas.get_user(user_id) submission_by_obj = self.assignment.get_submission(user) self.assertIsInstance(submission_by_obj, Submission) - self.assertTrue(hasattr(submission_by_obj, 'submission_type')) + self.assertTrue(hasattr(submission_by_obj, "submission_type")) # get_submissions() def test_get_submissions(self, m): - register_uris({'submission': ['list_submissions']}, m) + register_uris({"submission": ["list_submissions"]}, m) submissions = self.assignment.get_submissions() submission_list_by_id = [submission for submission in submissions] @@ -132,14 +132,14 @@ def test_get_submissions(self, m): # submit() def test_submit(self, m): - register_uris({'assignment': ['submit']}, m) + register_uris({"assignment": ["submit"]}, m) sub_type = "online_upload" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} submission = self.assignment.submit(sub_dict) self.assertIsInstance(submission, Submission) - self.assertTrue(hasattr(submission, 'submission_type')) + self.assertTrue(hasattr(submission, "submission_type")) self.assertEqual(submission.submission_type, sub_type) def test_submit_fail(self, m): @@ -147,40 +147,40 @@ def test_submit_fail(self, m): self.assignment.submit({}) def test_submit_file(self, m): - register_uris({'assignment': ['submit', 'upload', 'upload_final']}, m) + register_uris({"assignment": ["submit", "upload", "upload_final"]}, m) - filename = 'testfile_assignment_{}'.format(uuid.uuid4().hex) + filename = "testfile_assignment_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: sub_type = "online_upload" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} submission = self.assignment.submit(sub_dict, file) self.assertIsInstance(submission, Submission) - self.assertTrue(hasattr(submission, 'submission_type')) + self.assertTrue(hasattr(submission, "submission_type")) self.assertEqual(submission.submission_type, sub_type) finally: cleanup_file(filename) def test_submit_file_wrong_type(self, m): - filename = 'testfile_assignment_{}'.format(uuid.uuid4().hex) + filename = "testfile_assignment_{}".format(uuid.uuid4().hex) sub_type = "online_text_entry" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} with self.assertRaises(ValueError): self.assignment.submit(sub_dict, filename) def test_submit_file_upload_failure(self, m): - register_uris({'assignment': ['submit', 'upload', 'upload_fail']}, m) + register_uris({"assignment": ["submit", "upload", "upload_fail"]}, m) - filename = 'testfile_assignment_{}'.format(uuid.uuid4().hex) + filename = "testfile_assignment_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: sub_type = "online_upload" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} with self.assertRaises(CanvasException): self.assignment.submit(sub_dict, file) finally: @@ -193,10 +193,10 @@ def test__str__(self, m): # submissions_bulk_update() def test_submissions_bulk_update(self, m): - register_uris({'assignment': ['update_submissions']}, m) - register_uris({'progress': ['course_progress']}, m) + register_uris({"assignment": ["update_submissions"]}, m) + register_uris({"progress": ["course_progress"]}, m) progress = self.assignment.submissions_bulk_update( - grade_data={'1': {'posted_grade': 97}, '2': {'posted_grade': 98}} + grade_data={"1": {"posted_grade": 97}, "2": {"posted_grade": 98}} ) self.assertIsInstance(progress, Progress) self.assertTrue(progress.context_type == "Course") @@ -205,34 +205,34 @@ def test_submissions_bulk_update(self, m): # upload_to_submission() def test_upload_to_submission_self(self, m): - register_uris({'assignment': ['upload', 'upload_final']}, m) + register_uris({"assignment": ["upload", "upload_final"]}, m) - filename = 'testfile_assignment_{}'.format(uuid.uuid4().hex) + filename = "testfile_assignment_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.assignment.upload_to_submission(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) def test_upload_to_submission_user(self, m): - register_uris({'assignment': ['upload_by_id', 'upload_final']}, m) + register_uris({"assignment": ["upload_by_id", "upload_final"]}, m) - filename = 'testfile_assignment_{}'.format(uuid.uuid4().hex) + filename = "testfile_assignment_{}".format(uuid.uuid4().hex) user_id = 1 try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.assignment.upload_to_submission(file, user_id) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) @@ -244,7 +244,7 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( - {'course': ['get_by_id'], 'assignment': ['get_assignment_group']}, m + {"course": ["get_by_id"], "assignment": ["get_assignment_group"]}, m ) self.course = self.canvas.get_course(1) @@ -252,26 +252,26 @@ def setUp(self): # edit() def test_edit_assignment_group(self, m): - register_uris({'assignment': ['edit_assignment_group']}, m) + register_uris({"assignment": ["edit_assignment_group"]}, m) - name = 'New Name' + name = "New Name" edited_assignment_group = self.assignment_group.edit( - assignment_group={'name': name} + assignment_group={"name": name} ) self.assertIsInstance(edited_assignment_group, AssignmentGroup) - self.assertTrue(hasattr(edited_assignment_group, 'name')) + self.assertTrue(hasattr(edited_assignment_group, "name")) self.assertEqual(edited_assignment_group.name, name) # delete() def test_delete_assignment_group(self, m): - register_uris({'assignment': ['delete_assignment_group']}, m) + register_uris({"assignment": ["delete_assignment_group"]}, m) deleted_assignment_group = self.assignment_group.delete() self.assertIsInstance(deleted_assignment_group, AssignmentGroup) - self.assertTrue(hasattr(deleted_assignment_group, 'name')) - self.assertEqual(deleted_assignment_group.name, 'Assignment Group 5') + self.assertTrue(hasattr(deleted_assignment_group, "name")) + self.assertEqual(deleted_assignment_group.name, "Assignment Group 5") # __str__() def test__str__(self, m): @@ -287,8 +287,8 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'course': ['get_by_id', 'get_assignment_by_id'], - 'assignment': ['get_assignment_override'], + "course": ["get_by_id", "get_assignment_by_id"], + "assignment": ["get_assignment_override"], }, m, ) @@ -301,11 +301,11 @@ def setUp(self): def test__str__(self, m): string = str(self.assignment_override) self.assertIsInstance(string, str) - self.assertEqual(string, 'Assignment Override 1 (1)') + self.assertEqual(string, "Assignment Override 1 (1)") # delete() def test_delete(self, m): - register_uris({'assignment': ['delete_override']}, m) + register_uris({"assignment": ["delete_override"]}, m) deleted = self.assignment_override.delete() self.assertIsInstance(deleted, AssignmentOverride) @@ -313,15 +313,15 @@ def test_delete(self, m): # edit() def test_edit(self, m): - register_uris({'assignment': ['edit_override']}, m) + register_uris({"assignment": ["edit_override"]}, m) edited = self.assignment_override.edit( assignment_override={ - 'title': 'New Title', - 'student_ids': self.assignment_override.student_ids, + "title": "New Title", + "student_ids": self.assignment_override.student_ids, } ) self.assertEqual(edited, self.assignment_override) self.assertIsInstance(self.assignment_override, AssignmentOverride) - self.assertEqual(edited.title, 'New Title') + self.assertEqual(edited.title, "New Title") diff --git a/tests/test_authentication_providers.py b/tests/test_authentication_providers.py index 02962707..e2e02037 100644 --- a/tests/test_authentication_providers.py +++ b/tests/test_authentication_providers.py @@ -15,7 +15,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'account': ['get_by_id', 'add_authentication_providers']}, m) + register_uris({"account": ["get_by_id", "add_authentication_providers"]}, m) self.account = self.canvas.get_account(1) self.authentication_providers = self.account.add_authentication_providers( @@ -25,10 +25,10 @@ def setUp(self): # update() def test_update_authentication_providers(self, m): register_uris( - {'authentication_providers': ['update_authentication_providers']}, m + {"authentication_providers": ["update_authentication_providers"]}, m ) - new_auth_type = 'New Authentication Providers' + new_auth_type = "New Authentication Providers" self.authentication_providers.update( authentication_providers={"auth_type": new_auth_type} @@ -38,15 +38,15 @@ def test_update_authentication_providers(self, m): # delete() def test_delete_authentication_providers(self, m): register_uris( - {'authentication_providers': ['delete_authentication_providers']}, m + {"authentication_providers": ["delete_authentication_providers"]}, m ) deleted_authentication_providers = self.authentication_providers.delete() self.assertIsInstance(deleted_authentication_providers, AuthenticationProvider) - self.assertTrue(hasattr(deleted_authentication_providers, 'auth_type')) + self.assertTrue(hasattr(deleted_authentication_providers, "auth_type")) self.assertEqual( - deleted_authentication_providers.auth_type, 'Authentication Providers' + deleted_authentication_providers.auth_type, "Authentication Providers" ) # __str__() diff --git a/tests/test_blueprint.py b/tests/test_blueprint.py index 5b518d65..fd4b60a2 100644 --- a/tests/test_blueprint.py +++ b/tests/test_blueprint.py @@ -18,12 +18,12 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': [ - 'get_blueprint', - 'get_by_id', - 'list_blueprint_subscriptions', + "course": [ + "get_blueprint", + "get_by_id", + "list_blueprint_subscriptions", ], - 'blueprint': ['show_blueprint_migration'], + "blueprint": ["show_blueprint_migration"], } register_uris(requires, m) @@ -38,7 +38,7 @@ def test__str__(self, m): # get_associated_courses() def test_get_associated_courses(self, m): - register_uris({'blueprint': ['get_associated_courses']}, m) + register_uris({"blueprint": ["get_associated_courses"]}, m) associated_courses = self.blueprint.get_associated_courses() self.assertIsInstance(associated_courses, PaginatedList) self.assertEqual(associated_courses[0].id, 1) @@ -46,20 +46,20 @@ def test_get_associated_courses(self, m): # update_associated_courses() def test_update_associated_courses(self, m): - register_uris({'blueprint': ['update_associated_courses']}, m) + register_uris({"blueprint": ["update_associated_courses"]}, m) updated_associations = self.blueprint.update_associated_courses() self.assertEqual(updated_associations, True) # associated_course_migration() def test_associated_course_migration(self, m): - register_uris({'blueprint': ['associated_course_migration']}, m) + register_uris({"blueprint": ["associated_course_migration"]}, m) associated_migration = self.blueprint.associated_course_migration() self.assertEqual(associated_migration.id, 1) self.assertEqual(associated_migration.comment, "test1") # change_blueprint_restrictions() def test_change_blueprint_restrictions(self, m): - register_uris({'blueprint': ['change_blueprint_restrictions']}, m) + register_uris({"blueprint": ["change_blueprint_restrictions"]}, m) blueprint_restriction = self.blueprint.change_blueprint_restrictions( "quiz", 1, True ) @@ -67,7 +67,7 @@ def test_change_blueprint_restrictions(self, m): # get_unsynced_changes() def test_get_unsynced_changes(self, m): - register_uris({'blueprint': ['get_unsynced_changes']}, m) + register_uris({"blueprint": ["get_unsynced_changes"]}, m) unsynced_changes = self.blueprint.get_unsynced_changes() self.assertIsInstance(unsynced_changes, PaginatedList) self.assertIsInstance(unsynced_changes[0], ChangeRecord) @@ -78,7 +78,7 @@ def test_get_unsynced_changes(self, m): # list_blueprint_migrations() def test_list_blueprint_migrations(self, m): - register_uris({'blueprint': ['list_blueprint_migrations']}, m) + register_uris({"blueprint": ["list_blueprint_migrations"]}, m) blueprint_migrations = self.blueprint.list_blueprint_migrations() self.assertIsInstance(blueprint_migrations, PaginatedList) self.assertIsInstance(blueprint_migrations[0], BlueprintMigration) @@ -88,7 +88,7 @@ def test_list_blueprint_migrations(self, m): # show_blueprint_migration() def test_show_blueprint_migration(self, m): - register_uris({'blueprint': ['show_blueprint_migration']}, m) + register_uris({"blueprint": ["show_blueprint_migration"]}, m) blueprint_migration = self.blueprint.show_blueprint_migration(1) self.assertIsInstance(blueprint_migration, BlueprintMigration) self.assertEqual(blueprint_migration.id, 1) @@ -104,12 +104,12 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': [ - 'get_blueprint', - 'get_by_id', - 'list_blueprint_subscriptions', + "course": [ + "get_blueprint", + "get_by_id", + "list_blueprint_subscriptions", ], - 'blueprint': ['show_blueprint_migration'], + "blueprint": ["show_blueprint_migration"], } register_uris(requires, m) @@ -126,7 +126,7 @@ def test__str__(self, m): # list_blueprint_imports() def test_list_blueprint_imports(self, m): - register_uris({'blueprint': ['list_blueprint_imports']}, m) + register_uris({"blueprint": ["list_blueprint_imports"]}, m) blueprint_imports = self.blueprint_subscription.list_blueprint_imports() self.assertIsInstance(blueprint_imports, PaginatedList) self.assertIsInstance(blueprint_imports[0], BlueprintMigration) @@ -136,7 +136,7 @@ def test_list_blueprint_imports(self, m): # show_blueprint_import def test_show_blueprint_import(self, m): - register_uris({'blueprint': ['show_blueprint_import']}, m) + register_uris({"blueprint": ["show_blueprint_import"]}, m) blueprint_import = self.blueprint_subscription.show_blueprint_import(3) self.assertIsInstance(blueprint_import, BlueprintMigration) @@ -148,15 +148,15 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': [ - 'get_blueprint', - 'get_by_id', - 'list_blueprint_subscriptions', + "course": [ + "get_blueprint", + "get_by_id", + "list_blueprint_subscriptions", ], - 'blueprint': [ - 'show_blueprint_migration', - 'list_blueprint_imports', - 'show_blueprint_import', + "blueprint": [ + "show_blueprint_migration", + "list_blueprint_imports", + "show_blueprint_import", ], } register_uris(requires, m) @@ -177,7 +177,7 @@ def test__str__(self, m): # get_details() def test_get_details(self, m): - register_uris({'blueprint': ['get_details']}, m) + register_uris({"blueprint": ["get_details"]}, m) migration_details = self.blueprint_migration.get_details() self.assertIsInstance(migration_details, PaginatedList) self.assertIsInstance(migration_details[0], ChangeRecord) @@ -192,7 +192,7 @@ def test_get_details(self, m): # get_import_details() def test_get_import_details(self, m): - register_uris({'blueprint': ['get_import_details']}, m) + register_uris({"blueprint": ["get_import_details"]}, m) import_details = self.b_import.get_import_details() self.assertIsInstance(import_details, PaginatedList) self.assertIsInstance(import_details[0], ChangeRecord) diff --git a/tests/test_bookmark.py b/tests/test_bookmark.py index 1fbf35b7..3f623f4e 100644 --- a/tests/test_bookmark.py +++ b/tests/test_bookmark.py @@ -16,7 +16,7 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( - {'bookmark': ['get_bookmark'], 'current_user': ['get_by_id']}, m + {"bookmark": ["get_bookmark"], "current_user": ["get_by_id"]}, m ) self.user = self.canvas.get_current_user() @@ -24,24 +24,24 @@ def setUp(self): # delete() def test_delete_bookmark(self, m): - register_uris({'bookmark': ['delete_bookmark']}, m) + register_uris({"bookmark": ["delete_bookmark"]}, m) deleted_bookmark = self.bookmark.delete() self.assertIsInstance(deleted_bookmark, Bookmark) - self.assertTrue(hasattr(deleted_bookmark, 'name')) - self.assertEqual(deleted_bookmark.name, 'Test Bookmark 3') + self.assertTrue(hasattr(deleted_bookmark, "name")) + self.assertEqual(deleted_bookmark.name, "Test Bookmark 3") # edit() def test_edit_bookmark(self, m): - register_uris({'bookmark': ['edit_bookmark']}, m) + register_uris({"bookmark": ["edit_bookmark"]}, m) - name = 'New Name' - url = 'http//happy-place.com' + name = "New Name" + url = "http//happy-place.com" edited_bookmark = self.bookmark.edit(name=name, url=url) self.assertIsInstance(edited_bookmark, Bookmark) - self.assertTrue(hasattr(edited_bookmark, 'name')) + self.assertTrue(hasattr(edited_bookmark, "name")) self.assertEqual(edited_bookmark.name, name) # __str__() diff --git a/tests/test_calendar_event.py b/tests/test_calendar_event.py index 5edac143..2ef823a2 100644 --- a/tests/test_calendar_event.py +++ b/tests/test_calendar_event.py @@ -15,31 +15,31 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'calendar_event': ['get_calendar_event']}, m) + register_uris({"calendar_event": ["get_calendar_event"]}, m) self.calendar_event = self.canvas.get_calendar_event(567) # delete() def test_delete_calendar_event(self, m): - register_uris({'calendar_event': ['delete_calendar_event']}, m) + register_uris({"calendar_event": ["delete_calendar_event"]}, m) deleted_calendar_event = self.calendar_event.delete() self.assertIsInstance(deleted_calendar_event, CalendarEvent) - self.assertTrue(hasattr(deleted_calendar_event, 'title')) - self.assertEqual(deleted_calendar_event.title, 'Test Event 3') + self.assertTrue(hasattr(deleted_calendar_event, "title")) + self.assertEqual(deleted_calendar_event.title, "Test Event 3") # edit() def test_edit_calendar_event(self, m): - register_uris({'calendar_event': ['edit_calendar_event']}, m) + register_uris({"calendar_event": ["edit_calendar_event"]}, m) - title = 'New Name' + title = "New Name" edited_calendar_event = self.calendar_event.edit( - calendar_event={'title': title} + calendar_event={"title": title} ) self.assertIsInstance(edited_calendar_event, CalendarEvent) - self.assertTrue(hasattr(edited_calendar_event, 'title')) + self.assertTrue(hasattr(edited_calendar_event, "title")) self.assertEqual(edited_calendar_event.title, title) # __str__() diff --git a/tests/test_canvas.py b/tests/test_canvas.py index 95d9589d..458759e8 100644 --- a/tests/test_canvas.py +++ b/tests/test_canvas.py @@ -46,8 +46,8 @@ def test_init_warns_when_url_is_http(self, m): self.assertRaises( UserWarning, msg=( - 'Canvas may respond unexpectedly when making requests to HTTP' - 'URLs. If possible, please use HTTPS.' + "Canvas may respond unexpectedly when making requests to HTTP" + "URLs. If possible, please use HTTPS." ), ) @@ -56,7 +56,7 @@ def test_init_warns_when_url_is_blank(self, m): Canvas(settings.BASE_URL_AS_BLANK, settings.API_KEY) self.assertRaises( UserWarning, - msg='Canvas needs a valid URL, please provide a non-blank `base_url`.', + msg="Canvas needs a valid URL, please provide a non-blank `base_url`.", ) def test_init_warns_when_url_is_invalid(self, m): @@ -65,27 +65,27 @@ def test_init_warns_when_url_is_invalid(self, m): self.assertRaises( UserWarning, msg=( - 'An invalid `base_url` for the Canvas API Instance was used.' - 'Please provide a valid HTTP or HTTPS URL if possible.' + "An invalid `base_url` for the Canvas API Instance was used." + "Please provide a valid HTTP or HTTPS URL if possible." ), ) # create_account() def test_create_account(self, m): - register_uris({'account': ['create']}, m) + register_uris({"account": ["create"]}, m) - name = 'Newly Created Account' + name = "Newly Created Account" - account_dict = {'name': name} + account_dict = {"name": name} account = self.canvas.create_account(account=account_dict) self.assertIsInstance(account, Account) - self.assertTrue(hasattr(account, 'name')) + self.assertTrue(hasattr(account, "name")) self.assertEqual(account.name, name) # get_account() def test_get_account(self, m): - register_uris({'account': ['get_by_id']}, m) + register_uris({"account": ["get_by_id"]}, m) account_by_id = self.canvas.get_account(1) self.assertIsInstance(account_by_id, Account) @@ -94,22 +94,22 @@ def test_get_account(self, m): self.assertIsInstance(account_by_obj, Account) def test_get_account_sis_id(self, m): - register_uris({'account': ['get_by_sis_id']}, m) + register_uris({"account": ["get_by_sis_id"]}, m) - account = self.canvas.get_account('test-sis-id', use_sis_id=True) + account = self.canvas.get_account("test-sis-id", use_sis_id=True) self.assertIsInstance(account, Account) - self.assertEqual(account.name, 'Account From SIS') + self.assertEqual(account.name, "Account From SIS") def test_get_account_fail(self, m): - register_uris({'generic': ['not_found']}, m) + register_uris({"generic": ["not_found"]}, m) with self.assertRaises(ResourceDoesNotExist): self.canvas.get_account(settings.INVALID_ID) # get_accounts() def test_get_accounts(self, m): - register_uris({'account': ['multiple']}, m) + register_uris({"account": ["multiple"]}, m) accounts = self.canvas.get_accounts() account_list = [account for account in accounts] @@ -117,7 +117,7 @@ def test_get_accounts(self, m): # get_course_accounts() def test_get_course_accounts(self, m): - register_uris({'account': ['multiple_course']}, m) + register_uris({"account": ["multiple_course"]}, m) accounts = self.canvas.get_course_accounts() account_list = [account for account in accounts] @@ -125,85 +125,85 @@ def test_get_course_accounts(self, m): # get_course() def test_get_course(self, m): - register_uris({'course': ['get_by_id']}, m) + register_uris({"course": ["get_by_id"]}, m) course_by_id = self.canvas.get_course(1) self.assertIsInstance(course_by_id, Course) - self.assertTrue(hasattr(course_by_id, 'name')) + self.assertTrue(hasattr(course_by_id, "name")) course_by_obj = self.canvas.get_course(course_by_id) self.assertIsInstance(course_by_obj, Course) - self.assertTrue(hasattr(course_by_obj, 'name')) + self.assertTrue(hasattr(course_by_obj, "name")) def test_get_course_sis_id(self, m): - register_uris({'course': ['get_by_sis_id']}, m) + register_uris({"course": ["get_by_sis_id"]}, m) - course = self.canvas.get_course('test-sis-id', use_sis_id=True) + course = self.canvas.get_course("test-sis-id", use_sis_id=True) self.assertIsInstance(course, Course) - self.assertEqual(course.name, 'SIS Course') + self.assertEqual(course.name, "SIS Course") def test_get_course_with_start_date(self, m): - register_uris({'course': ['start_at_date']}, m) + register_uris({"course": ["start_at_date"]}, m) course = self.canvas.get_course(2) - self.assertTrue(hasattr(course, 'start_at')) + self.assertTrue(hasattr(course, "start_at")) self.assertIsInstance(course.start_at, text_type) - self.assertTrue(hasattr(course, 'start_at_date')) + self.assertTrue(hasattr(course, "start_at_date")) self.assertIsInstance(course.start_at_date, datetime) self.assertEqual(course.start_at_date.tzinfo, pytz.utc) def test_get_course_non_unicode_char(self, m): - register_uris({'course': ['unicode_encode_error']}, m) + register_uris({"course": ["unicode_encode_error"]}, m) course = self.canvas.get_course(3) - self.assertTrue(hasattr(course, 'name')) + self.assertTrue(hasattr(course, "name")) def test_get_course_fail(self, m): - register_uris({'generic': ['not_found']}, m) + register_uris({"generic": ["not_found"]}, m) with self.assertRaises(ResourceDoesNotExist): self.canvas.get_course(settings.INVALID_ID) # get_user() def test_get_user(self, m): - register_uris({'user': ['get_by_id']}, m) + register_uris({"user": ["get_by_id"]}, m) user_by_id = self.canvas.get_user(1) self.assertIsInstance(user_by_id, User) - self.assertTrue(hasattr(user_by_id, 'name')) + self.assertTrue(hasattr(user_by_id, "name")) user_by_obj = self.canvas.get_user(user_by_id) self.assertIsInstance(user_by_obj, User) - self.assertTrue(hasattr(user_by_obj, 'name')) + self.assertTrue(hasattr(user_by_obj, "name")) def test_get_user_by_id_type(self, m): - register_uris({'user': ['get_by_id_type']}, m) + register_uris({"user": ["get_by_id_type"]}, m) - user = self.canvas.get_user('jdoe', 'sis_user_id') + user = self.canvas.get_user("jdoe", "sis_user_id") self.assertIsInstance(user, User) - self.assertTrue(hasattr(user, 'name')) + self.assertTrue(hasattr(user, "name")) def test_get_user_self(self, m): - register_uris({'user': ['get_by_id_self']}, m) + register_uris({"user": ["get_by_id_self"]}, m) - user = self.canvas.get_user('self') + user = self.canvas.get_user("self") self.assertIsInstance(user, User) - self.assertTrue(hasattr(user, 'name')) + self.assertTrue(hasattr(user, "name")) def test_get_user_fail(self, m): - register_uris({'generic': ['not_found']}, m) + register_uris({"generic": ["not_found"]}, m) with self.assertRaises(ResourceDoesNotExist): self.canvas.get_user(settings.INVALID_ID) # get_courses() def test_get_courses(self, m): - register_uris({'course': ['multiple', 'multiple_page_2']}, m) + register_uris({"course": ["multiple", "multiple_page_2"]}, m) courses = self.canvas.get_courses(per_page=1) @@ -213,7 +213,7 @@ def test_get_courses(self, m): # get_activity_stream_summary() def test_get_activity_stream_summary(self, m): - register_uris({'user': ['activity_stream_summary']}, m) + register_uris({"user": ["activity_stream_summary"]}, m) summary = self.canvas.get_activity_stream_summary() @@ -221,7 +221,7 @@ def test_get_activity_stream_summary(self, m): # get_todo_items() def test_get_todo_items(self, m): - register_uris({'user': ['todo_items']}, m) + register_uris({"user": ["todo_items"]}, m) todo_items = self.canvas.get_todo_items() @@ -229,7 +229,7 @@ def test_get_todo_items(self, m): # get_upcoming_events() def test_get_upcoming_events(self, m): - register_uris({'user': ['upcoming_events']}, m) + register_uris({"user": ["upcoming_events"]}, m) events = self.canvas.get_upcoming_events() @@ -237,69 +237,69 @@ def test_get_upcoming_events(self, m): # get_course_nicknames() def test_get_course_nicknames(self, m): - register_uris({'user': ['course_nicknames', 'course_nicknames_page_2']}, m) + register_uris({"user": ["course_nicknames", "course_nicknames_page_2"]}, m) nicknames = self.canvas.get_course_nicknames() nickname_list = [name for name in nicknames] self.assertEqual(len(nickname_list), 4) self.assertIsInstance(nickname_list[0], CourseNickname) - self.assertTrue(hasattr(nickname_list[0], 'nickname')) + self.assertTrue(hasattr(nickname_list[0], "nickname")) # get_course_nickname() def test_get_course_nickname(self, m): - register_uris({'course': ['get_by_id'], 'user': ['course_nickname']}, m) + register_uris({"course": ["get_by_id"], "user": ["course_nickname"]}, m) nickname_by_id = self.canvas.get_course_nickname(1) self.assertIsInstance(nickname_by_id, CourseNickname) - self.assertTrue(hasattr(nickname_by_id, 'nickname')) + self.assertTrue(hasattr(nickname_by_id, "nickname")) course_for_obj = self.canvas.get_course(1) nickname_by_obj = self.canvas.get_course_nickname(course_for_obj) self.assertIsInstance(nickname_by_obj, CourseNickname) - self.assertTrue(hasattr(nickname_by_obj, 'nickname')) + self.assertTrue(hasattr(nickname_by_obj, "nickname")) def test_get_course_nickname_fail(self, m): - register_uris({'generic': ['not_found']}, m) + register_uris({"generic": ["not_found"]}, m) with self.assertRaises(ResourceDoesNotExist): self.canvas.get_course_nickname(settings.INVALID_ID) # set_course_nickname() def test_set_course_nickname(self, m): - register_uris({'course': ['get_by_id'], 'user': ['course_nickname_set']}, m) + register_uris({"course": ["get_by_id"], "user": ["course_nickname_set"]}, m) - name = 'New Course Nickname' + name = "New Course Nickname" nickname_by_id = self.canvas.set_course_nickname(1, name) self.assertIsInstance(nickname_by_id, CourseNickname) - self.assertTrue(hasattr(nickname_by_id, 'nickname')) + self.assertTrue(hasattr(nickname_by_id, "nickname")) self.assertEqual(nickname_by_id.nickname, name) course_for_obj = self.canvas.get_course(1) nickname_by_obj = self.canvas.set_course_nickname(course_for_obj, name) self.assertIsInstance(nickname_by_obj, CourseNickname) - self.assertTrue(hasattr(nickname_by_obj, 'nickname')) + self.assertTrue(hasattr(nickname_by_obj, "nickname")) # clear_course_nicknames() def test_clear_course_nicknames(self, m): - register_uris({'user': ['course_nicknames_delete']}, m) + register_uris({"user": ["course_nicknames_delete"]}, m) success = self.canvas.clear_course_nicknames() self.assertTrue(success) # search_accounts() def test_search_accounts(self, m): - register_uris({'account': ['domains']}, m) + register_uris({"account": ["domains"]}, m) domains = self.canvas.search_accounts() self.assertIsInstance(domains, list) self.assertEqual(len(domains), 1) - self.assertIn('name', domains[0]) + self.assertIn("name", domains[0]) # get_section() def test_get_section(self, m): - register_uris({'section': ['get_by_id']}, m) + register_uris({"section": ["get_by_id"]}, m) section_by_id = self.canvas.get_section(1) self.assertIsInstance(section_by_id, Section) @@ -308,48 +308,48 @@ def test_get_section(self, m): self.assertIsInstance(section_by_obj, Section) def test_get_section_sis_id(self, m): - register_uris({'section': ['get_by_sis_id']}, m) + register_uris({"section": ["get_by_sis_id"]}, m) - section = self.canvas.get_section('test-sis-id', use_sis_id=True) + section = self.canvas.get_section("test-sis-id", use_sis_id=True) self.assertIsInstance(section, Section) - self.assertEqual(section.name, 'SIS Section') + self.assertEqual(section.name, "SIS Section") # create_group() def test_create_group(self, m): - register_uris({'group': ['create']}, m) + register_uris({"group": ["create"]}, m) group = self.canvas.create_group() self.assertIsInstance(group, Group) - self.assertTrue(hasattr(group, 'name')) - self.assertTrue(hasattr(group, 'description')) + self.assertTrue(hasattr(group, "name")) + self.assertTrue(hasattr(group, "description")) # get_group() def test_get_group(self, m): - register_uris({'group': ['get_by_id']}, m) + register_uris({"group": ["get_by_id"]}, m) group_by_id = self.canvas.get_group(1) self.assertIsInstance(group_by_id, Group) - self.assertTrue(hasattr(group_by_id, 'name')) - self.assertTrue(hasattr(group_by_id, 'description')) + self.assertTrue(hasattr(group_by_id, "name")) + self.assertTrue(hasattr(group_by_id, "description")) group_by_obj = self.canvas.get_group(group_by_id) self.assertIsInstance(group_by_obj, Group) - self.assertTrue(hasattr(group_by_obj, 'name')) - self.assertTrue(hasattr(group_by_obj, 'description')) + self.assertTrue(hasattr(group_by_obj, "name")) + self.assertTrue(hasattr(group_by_obj, "description")) def test_get_group_sis_id(self, m): - register_uris({'group': ['get_by_sis_id']}, m) + register_uris({"group": ["get_by_sis_id"]}, m) - group = self.canvas.get_group('test-sis-id', use_sis_id=True) + group = self.canvas.get_group("test-sis-id", use_sis_id=True) self.assertIsInstance(group, Group) - self.assertEqual(group.name, 'SIS Group') + self.assertEqual(group.name, "SIS Group") # get_group_category() def test_get_group_category(self, m): - register_uris({'group': ['get_category_by_id']}, m) + register_uris({"group": ["get_category_by_id"]}, m) group_category_by_id = self.canvas.get_group_category(1) self.assertIsInstance(group_category_by_id, GroupCategory) @@ -359,10 +359,10 @@ def test_get_group_category(self, m): # create_conversation() def test_create_conversation(self, m): - register_uris({'conversation': ['create_conversation']}, m) + register_uris({"conversation": ["create_conversation"]}, m) - recipients = ['2'] - body = 'Hello, World!' + recipients = ["2"] + body = "Hello, World!" conversations = self.canvas.create_conversation( recipients=recipients, body=body @@ -370,14 +370,14 @@ def test_create_conversation(self, m): self.assertIsInstance(conversations, list) self.assertEqual(len(conversations), 1) self.assertIsInstance(conversations[0], Conversation) - self.assertTrue(hasattr(conversations[0], 'last_message')) + self.assertTrue(hasattr(conversations[0], "last_message")) self.assertEqual(conversations[0].last_message, body) def test_create_conversation_multiple_people(self, m): - register_uris({'conversation': ['create_conversation_multiple']}, m) + register_uris({"conversation": ["create_conversation_multiple"]}, m) - recipients = ['2', '3'] - body = 'Hey guys!' + recipients = ["2", "3"] + body = "Hey guys!" conversations = self.canvas.create_conversation( recipients=recipients, body=body @@ -386,28 +386,28 @@ def test_create_conversation_multiple_people(self, m): self.assertEqual(len(conversations), 2) self.assertIsInstance(conversations[0], Conversation) - self.assertTrue(hasattr(conversations[0], 'last_message')) + self.assertTrue(hasattr(conversations[0], "last_message")) self.assertEqual(conversations[0].last_message, body) self.assertIsInstance(conversations[1], Conversation) - self.assertTrue(hasattr(conversations[1], 'last_message')) + self.assertTrue(hasattr(conversations[1], "last_message")) self.assertEqual(conversations[1].last_message, body) # get_conversation() def test_get_conversation(self, m): - register_uris({'conversation': ['get_by_id']}, m) + register_uris({"conversation": ["get_by_id"]}, m) conversation_by_id = self.canvas.get_conversation(1) self.assertIsInstance(conversation_by_id, Conversation) - self.assertTrue(hasattr(conversation_by_id, 'subject')) + self.assertTrue(hasattr(conversation_by_id, "subject")) conversation_by_obj = self.canvas.get_conversation(conversation_by_id) self.assertIsInstance(conversation_by_obj, Conversation) - self.assertTrue(hasattr(conversation_by_obj, 'subject')) + self.assertTrue(hasattr(conversation_by_obj, "subject")) # get_conversations() def test_get_conversations(self, m): - requires = {'conversation': ['get_conversations', 'get_conversations_2']} + requires = {"conversation": ["get_conversations", "get_conversations_2"]} register_uris(requires, m) convos = self.canvas.get_conversations() @@ -418,30 +418,30 @@ def test_get_conversations(self, m): # mark_all_as_read() def test_conversations_mark_all_as_read(self, m): - register_uris({'conversation': ['mark_all_as_read']}, m) + register_uris({"conversation": ["mark_all_as_read"]}, m) result = self.canvas.conversations_mark_all_as_read() self.assertTrue(result) # unread_count() def test_conversations_unread_count(self, m): - register_uris({'conversation': ['unread_count']}, m) + register_uris({"conversation": ["unread_count"]}, m) result = self.canvas.conversations_unread_count() - self.assertEqual(result['unread_count'], "7") + self.assertEqual(result["unread_count"], "7") # get_running_batches() def test_conversations_get_running_batches(self, m): - register_uris({'conversation': ['get_running_batches']}, m) + register_uris({"conversation": ["get_running_batches"]}, m) result = self.canvas.conversations_get_running_batches() self.assertEqual(len(result), 2) - self.assertIn('body', result[0]['message']) - self.assertEqual(result[1]['message']['author_id'], 1) + self.assertIn("body", result[0]["message"]) + self.assertEqual(result[1]["message"]["author_id"], 1) # batch_update() def test_conversations_batch_update(self, m): - register_uris({'conversation': ['batch_update']}, m) + register_uris({"conversation": ["batch_update"]}, m) conversation_ids = [1, 2] this_event = "mark_as_read" @@ -468,7 +468,7 @@ def test_conversations_batch_updated_fail_on_ids(self, m): # create_calendar_event() def test_create_calendar_event(self, m): - register_uris({'calendar_event': ['create_calendar_event']}, m) + register_uris({"calendar_event": ["create_calendar_event"]}, m) cal_event = {"context_code": "course_123"} evnt = self.canvas.create_calendar_event(calendar_event=cal_event) @@ -483,7 +483,7 @@ def test_create_calendar_event_fail(self, m): # list_calendar_events() def test_list_calendar_events(self, m): - register_uris({'calendar_event': ['list_calendar_events']}, m) + register_uris({"calendar_event": ["list_calendar_events"]}, m) with warnings.catch_warnings(record=True) as warning_list: cal_events = self.canvas.list_calendar_events() @@ -495,7 +495,7 @@ def test_list_calendar_events(self, m): # get_calendar_events() def test_get_calendar_events(self, m): - register_uris({'calendar_event': ['list_calendar_events']}, m) + register_uris({"calendar_event": ["list_calendar_events"]}, m) cal_events = self.canvas.get_calendar_events() cal_event_list = [cal_event for cal_event in cal_events] @@ -503,7 +503,7 @@ def test_get_calendar_events(self, m): # get_calendar_event() def test_get_calendar_event(self, m): - register_uris({'calendar_event': ['get_calendar_event']}, m) + register_uris({"calendar_event": ["get_calendar_event"]}, m) calendar_event_by_id = self.canvas.get_calendar_event(567) self.assertIsInstance(calendar_event_by_id, CalendarEvent) @@ -515,7 +515,7 @@ def test_get_calendar_event(self, m): # reserve_time_slot() def test_reserve_time_slot(self, m): - register_uris({'calendar_event': ['reserve_time_slot']}, m) + register_uris({"calendar_event": ["reserve_time_slot"]}, m) calendar_event_by_id = self.canvas.reserve_time_slot(calendar_event=567) self.assertIsInstance(calendar_event_by_id, CalendarEvent) @@ -528,7 +528,7 @@ def test_reserve_time_slot(self, m): self.assertEqual(calendar_event_by_obj.title, "Test Reservation") def test_reserve_time_slot_by_participant_id(self, m): - register_uris({'calendar_event': ['reserve_time_slot_participant_id']}, m) + register_uris({"calendar_event": ["reserve_time_slot_participant_id"]}, m) cal_event = self.canvas.reserve_time_slot( calendar_event=567, participant_id=777 @@ -539,7 +539,7 @@ def test_reserve_time_slot_by_participant_id(self, m): # list_appointment_groups() def test_list_appointment_groups(self, m): - register_uris({'appointment_group': ['list_appointment_groups']}, m) + register_uris({"appointment_group": ["list_appointment_groups"]}, m) with warnings.catch_warnings(record=True) as warning_list: appt_groups = self.canvas.list_appointment_groups() @@ -551,7 +551,7 @@ def test_list_appointment_groups(self, m): # get_appointment_groups() def test_get_appointment_groups(self, m): - register_uris({'appointment_group': ['list_appointment_groups']}, m) + register_uris({"appointment_group": ["list_appointment_groups"]}, m) appt_groups = self.canvas.get_appointment_groups() appt_groups_list = [appt_group for appt_group in appt_groups] @@ -559,7 +559,7 @@ def test_get_appointment_groups(self, m): # get_appointment_group() def test_get_appointment_group(self, m): - register_uris({'appointment_group': ['get_appointment_group']}, m) + register_uris({"appointment_group": ["get_appointment_group"]}, m) appointment_group_by_id = self.canvas.get_appointment_group(567) self.assertIsInstance(appointment_group_by_id, AppointmentGroup) @@ -573,7 +573,7 @@ def test_get_appointment_group(self, m): # create_appointment_group() def test_create_appointment_group(self, m): - register_uris({'appointment_group': ['create_appointment_group']}, m) + register_uris({"appointment_group": ["create_appointment_group"]}, m) evnt = self.canvas.create_appointment_group( {"context_codes": ["course_123"], "title": "Test Group"} @@ -595,9 +595,9 @@ def test_create_appointment_group_fail_on_title(self, m): def test_list_user_participants(self, m): register_uris( { - 'appointment_group': [ - 'get_appointment_group_222', - 'list_user_participants', + "appointment_group": [ + "get_appointment_group_222", + "list_user_participants", ] }, m, @@ -624,9 +624,9 @@ def test_list_user_participants(self, m): def test_get_user_participants(self, m): register_uris( { - 'appointment_group': [ - 'get_appointment_group_222', - 'list_user_participants', + "appointment_group": [ + "get_appointment_group_222", + "list_user_participants", ] }, m, @@ -645,9 +645,9 @@ def test_get_user_participants(self, m): def test_list_group_participants(self, m): register_uris( { - 'appointment_group': [ - 'get_appointment_group_222', - 'list_group_participants', + "appointment_group": [ + "get_appointment_group_222", + "list_group_participants", ] }, m, @@ -676,9 +676,9 @@ def test_list_group_participants(self, m): def test_get_group_participants(self, m): register_uris( { - 'appointment_group': [ - 'get_appointment_group_222', - 'list_group_participants', + "appointment_group": [ + "get_appointment_group_222", + "list_group_participants", ] }, m, @@ -695,7 +695,7 @@ def test_get_group_participants(self, m): # get_file() def test_get_file(self, m): - register_uris({'file': ['get_by_id']}, m) + register_uris({"file": ["get_by_id"]}, m) file_by_id = self.canvas.get_file(1) self.assertIsInstance(file_by_id, File) @@ -709,7 +709,7 @@ def test_get_file(self, m): # search_recipients() def test_search_recipients(self, m): - register_uris({'user': ['search_recipients']}, m) + register_uris({"user": ["search_recipients"]}, m) recipients = self.canvas.search_recipients() self.assertIsInstance(recipients, list) @@ -717,7 +717,7 @@ def test_search_recipients(self, m): # search_all_courses() def test_search_all_courses(self, m): - register_uris({'course': ['search_all_courses']}, m) + register_uris({"course": ["search_all_courses"]}, m) courses = self.canvas.search_all_courses() self.assertIsInstance(courses, list) @@ -725,7 +725,7 @@ def test_search_all_courses(self, m): # get_outcome() def test_get_outcome(self, m): - register_uris({'outcome': ['canvas_get_outcome']}, m) + register_uris({"outcome": ["canvas_get_outcome"]}, m) outcome_group_by_id = self.canvas.get_outcome(3) self.assertIsInstance(outcome_group_by_id, Outcome) @@ -739,7 +739,7 @@ def test_get_outcome(self, m): # get_root_outcome_group() def test_get_root_outcome_group(self, m): - register_uris({'outcome': ['canvas_root_outcome_group']}, m) + register_uris({"outcome": ["canvas_root_outcome_group"]}, m) outcome_group = self.canvas.get_root_outcome_group() self.assertIsInstance(outcome_group, OutcomeGroup) @@ -748,7 +748,7 @@ def test_get_root_outcome_group(self, m): # get_outcome_group() def test_get_outcome_group(self, m): - register_uris({'outcome': ['canvas_get_outcome_group']}, m) + register_uris({"outcome": ["canvas_get_outcome_group"]}, m) outcome_group_by_id = self.canvas.get_outcome_group(1) self.assertIsInstance(outcome_group_by_id, OutcomeGroup) @@ -762,16 +762,16 @@ def test_get_outcome_group(self, m): # get_progress() def test_get_progress(self, m): - register_uris({'content_migration': ['get_progress']}, m) + register_uris({"content_migration": ["get_progress"]}, m) progress = self.canvas.get_progress(1) self.assertIsInstance(progress, Progress) - self.assertTrue(hasattr(progress, 'id')) + self.assertTrue(hasattr(progress, "id")) self.assertEqual(progress.id, 1) # get_announcements() def test_get_announcements(self, m): - register_uris({'announcements': ['list_announcements']}, m) + register_uris({"announcements": ["list_announcements"]}, m) announcements = self.canvas.get_announcements() announcement_list = [announcement for announcement in announcements] self.assertIsInstance(announcements, PaginatedList) @@ -781,7 +781,7 @@ def test_get_announcements(self, m): # get_epub_exports() def test_get_epub_exports(self, m): - register_uris({'course': ['get_epub_exports']}, m) + register_uris({"course": ["get_epub_exports"]}, m) epub_export_list = self.canvas.get_epub_exports() @@ -798,7 +798,7 @@ def test_get_epub_exports(self, m): epub1 = epub_export_list[0].epub_export epub2 = epub_export_list[1].epub_export - self.assertEqual(epub1['id'], 1) - self.assertEqual(epub2['id'], 2) - self.assertEqual(epub1['workflow_state'], "exported") - self.assertEqual(epub2['workflow_state'], "exported") + self.assertEqual(epub1["id"], 1) + self.assertEqual(epub2["id"], 2) + self.assertEqual(epub1["workflow_state"], "exported") + self.assertEqual(epub2["workflow_state"], "exported") diff --git a/tests/test_canvas_object.py b/tests/test_canvas_object.py index 97cb3fea..6e3266d9 100644 --- a/tests/test_canvas_object.py +++ b/tests/test_canvas_object.py @@ -8,13 +8,13 @@ class TestCanvasObject(unittest.TestCase): # to_json() def test_canvas_object_to_json(self): - attributes = {'name': 'Test Object', 'id': 1} + attributes = {"name": "Test Object", "id": 1} canvas_obj = CanvasObject(None, attributes) prev_json = canvas_obj.to_json() self.assertIsInstance(prev_json, str) - attributes.update({'name': 'Test Object 2'}) + attributes.update({"name": "Test Object 2"}) canvas_obj.set_attributes(attributes) self.assertNotEqual(canvas_obj.to_json(), prev_json) diff --git a/tests/test_communication_channel.py b/tests/test_communication_channel.py index 7116b284..203ede3e 100644 --- a/tests/test_communication_channel.py +++ b/tests/test_communication_channel.py @@ -16,7 +16,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'user': ['get_by_id', 'list_comm_channels']}, m) + register_uris({"user": ["get_by_id", "list_comm_channels"]}, m) self.user = self.canvas.get_user(1) self.comm_chan = self.user.get_communication_channels()[0] @@ -28,66 +28,66 @@ def test__str__(self, m): # list_preferences() def test_list_preferences(self, m): - register_uris({'communication_channel': ['list_preferences']}, m) + register_uris({"communication_channel": ["list_preferences"]}, m) with warnings.catch_warnings(record=True) as warning_list: preferences = self.comm_chan.list_preferences() preference_list = [preference for preference in preferences] self.assertEqual(len(preference_list), 2) - self.assertEqual(preference_list[0]['notification'], 'new_announcement') + self.assertEqual(preference_list[0]["notification"], "new_announcement") self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_preferences() def test_get_preferences(self, m): - register_uris({'communication_channel': ['list_preferences']}, m) + register_uris({"communication_channel": ["list_preferences"]}, m) preferences = self.comm_chan.get_preferences() preference_list = [preference for preference in preferences] self.assertEqual(len(preference_list), 2) - self.assertEqual(preference_list[0]['notification'], 'new_announcement') + self.assertEqual(preference_list[0]["notification"], "new_announcement") # list_preference_categories() def test_list_preference_categories(self, m): - register_uris({'communication_channel': ['list_preference_categories']}, m) + register_uris({"communication_channel": ["list_preference_categories"]}, m) with warnings.catch_warnings(record=True) as warning_list: categories = self.comm_chan.list_preference_categories() self.assertEqual(len(categories), 2) self.assertIsInstance(categories, list) - self.assertEqual(categories[0], 'announcement') + self.assertEqual(categories[0], "announcement") self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_preference_categories() def test_get_preference_categories(self, m): - register_uris({'communication_channel': ['list_preference_categories']}, m) + register_uris({"communication_channel": ["list_preference_categories"]}, m) categories = self.comm_chan.get_preference_categories() self.assertEqual(len(categories), 2) self.assertIsInstance(categories, list) - self.assertEqual(categories[0], 'announcement') + self.assertEqual(categories[0], "announcement") # get_preference() def test_get_preference(self, m): - register_uris({'communication_channel': ['get_preference']}, m) + register_uris({"communication_channel": ["get_preference"]}, m) - preference = self.comm_chan.get_preference('new_announcement') + preference = self.comm_chan.get_preference("new_announcement") self.assertIsInstance(preference, NotificationPreference) - self.assertTrue(hasattr(preference, 'notification')) - self.assertEqual(preference.notification, 'new_announcement') + self.assertTrue(hasattr(preference, "notification")) + self.assertEqual(preference.notification, "new_announcement") # update_preference() def test_update_preference(self, m): - register_uris({'communication_channel': ['update_preference']}, m) - notification = 'new_announcement' - frequency = 'daily' + register_uris({"communication_channel": ["update_preference"]}, m) + notification = "new_announcement" + frequency = "daily" updated_pref = self.comm_chan.update_preference( notification=notification, frequency=frequency @@ -96,26 +96,26 @@ def test_update_preference(self, m): self.assertIsInstance(updated_pref, NotificationPreference) self.assertEqual(updated_pref.frequency, frequency) self.assertEqual(updated_pref.notification, notification) - self.assertEqual(updated_pref.category, 'announcement') + self.assertEqual(updated_pref.category, "announcement") # update_preferences_by_category() def test_update_preferences_by_category(self, m): - register_uris({'communication_channel': ['update_preferences_by_category']}, m) - category = 'course_content' - frequency = 'daily' + register_uris({"communication_channel": ["update_preferences_by_category"]}, m) + category = "course_content" + frequency = "daily" updated_prefs = self.comm_chan.update_preferences_by_catagory( category=category, frequency=frequency ) self.assertEqual(len(updated_prefs), 3) - self.assertEqual(updated_prefs[0]['frequency'], frequency) - self.assertEqual(updated_prefs[0]['category'], category) - self.assertEqual(updated_prefs[0]['notification'], 'assignment_changed') + self.assertEqual(updated_prefs[0]["frequency"], frequency) + self.assertEqual(updated_prefs[0]["category"], category) + self.assertEqual(updated_prefs[0]["notification"], "assignment_changed") # update_multiple_preferences() def test_update_multiple_preferences(self, m): - register_uris({'communication_channel': ['update_multiple_preferences']}, m) + register_uris({"communication_channel": ["update_multiple_preferences"]}, m) notification_preferences = { "assignment_due_date_changed": {"frequency": "daily"}, @@ -127,7 +127,7 @@ def test_update_multiple_preferences(self, m): ) self.assertEqual(len(updated_prefs), 2) - self.assertEqual(updated_prefs[0]['frequency'], "daily") + self.assertEqual(updated_prefs[0]["frequency"], "daily") empty_notification_preferences = {} self.assertFalse( @@ -153,7 +153,7 @@ def test_update_multiple_preferences(self, m): # delete() def test_delete(self, m): register_uris( - {'communication_channel': ['create_comm_channel', 'delete_comm_channel']}, m + {"communication_channel": ["create_comm_channel", "delete_comm_channel"]}, m ) channel = {"type": "email", "address": "username@example.org"} diff --git a/tests/test_content_export.py b/tests/test_content_export.py index 1d57a4de..22887dba 100644 --- a/tests/test_content_export.py +++ b/tests/test_content_export.py @@ -15,9 +15,9 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'single_content_export'], - 'group': ['get_by_id', 'single_content_export'], - 'user': ['get_by_id', 'single_content_export'], + "course": ["get_by_id", "single_content_export"], + "group": ["get_by_id", "single_content_export"], + "user": ["get_by_id", "single_content_export"], } register_uris(requires, m) diff --git a/tests/test_content_migration.py b/tests/test_content_migration.py index ace2e953..59b757fc 100644 --- a/tests/test_content_migration.py +++ b/tests/test_content_migration.py @@ -21,10 +21,10 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_content_migration_single'], - 'group': ['get_by_id', 'get_content_migration_single'], - 'account': ['get_by_id', 'get_content_migration_single'], - 'user': ['get_by_id', 'get_content_migration_single'], + "course": ["get_by_id", "get_content_migration_single"], + "group": ["get_by_id", "get_content_migration_single"], + "account": ["get_by_id", "get_content_migration_single"], + "user": ["get_by_id", "get_content_migration_single"], } register_uris(requires, m) @@ -45,19 +45,19 @@ def test__str__(self, m): # _parent_type def test_parent_type_account(self, m): - self.assertEqual(self.content_migration._parent_type, 'account') + self.assertEqual(self.content_migration._parent_type, "account") def test_parent_type_course(self, m): - self.assertEqual(self.content_migration_course._parent_type, 'course') + self.assertEqual(self.content_migration_course._parent_type, "course") def test_parent_type_group(self, m): - self.assertEqual(self.content_migration_group._parent_type, 'group') + self.assertEqual(self.content_migration_group._parent_type, "group") def test_parent_type_user(self, m): - self.assertEqual(self.content_migration_user._parent_type, 'user') + self.assertEqual(self.content_migration_user._parent_type, "user") def test_parent_type_no_type(self, m): - migration = ContentMigration(self.canvas._Canvas__requester, {'id': 1}) + migration = ContentMigration(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): migration._parent_type @@ -75,87 +75,87 @@ def test_parent_id_user(self, m): self.assertEqual(self.content_migration_user._parent_id, 1) def test_parent_id_no_id(self, m): - migration = ContentMigration(self.canvas._Canvas__requester, {'id': 1}) + migration = ContentMigration(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): migration._parent_id # get_migration_issue() def test_get_migration_issue(self, m): - register_uris({'content_migration': ['get_migration_issue_single']}, m) + register_uris({"content_migration": ["get_migration_issue_single"]}, m) issue = self.content_migration.get_migration_issue(1) self.assertIsInstance(issue, MigrationIssue) - self.assertTrue(hasattr(issue, 'id')) + self.assertTrue(hasattr(issue, "id")) self.assertEqual(issue.id, 1) # get_migration_issues() def test_get_migration_issues(self, m): - register_uris({'content_migration': ['get_migration_issue_multiple']}, m) + register_uris({"content_migration": ["get_migration_issue_multiple"]}, m) issues = self.content_migration.get_migration_issues() self.assertEqual(len(list(issues)), 2) self.assertIsInstance(issues[0], MigrationIssue) - self.assertTrue(hasattr(issues[0], 'id')) + self.assertTrue(hasattr(issues[0], "id")) self.assertEqual(issues[0].id, 1) self.assertIsInstance(issues[1], MigrationIssue) - self.assertTrue(hasattr(issues[1], 'id')) + self.assertTrue(hasattr(issues[1], "id")) self.assertEqual(issues[1].id, 2) # get_parent() def test_get_parent_account(self, m): - register_uris({'content_migration': ['get_parent_account']}, m) + register_uris({"content_migration": ["get_parent_account"]}, m) account = self.content_migration.get_parent() self.assertIsInstance(account, Account) - self.assertTrue(hasattr(account, 'id')) + self.assertTrue(hasattr(account, "id")) self.assertEqual(account.id, 1) def test_get_parent_course(self, m): - register_uris({'content_migration': ['get_parent_course']}, m) + register_uris({"content_migration": ["get_parent_course"]}, m) course = self.content_migration_course.get_parent() self.assertIsInstance(course, Course) - self.assertTrue(hasattr(course, 'id')) + self.assertTrue(hasattr(course, "id")) self.assertEqual(course.id, 1) def test_get_parent_group(self, m): - register_uris({'content_migration': ['get_parent_group']}, m) + register_uris({"content_migration": ["get_parent_group"]}, m) group = self.content_migration_group.get_parent() self.assertIsInstance(group, Group) - self.assertTrue(hasattr(group, 'id')) + self.assertTrue(hasattr(group, "id")) self.assertEqual(group.id, 1) def test_get_parent_user(self, m): - register_uris({'content_migration': ['get_parent_user']}, m) + register_uris({"content_migration": ["get_parent_user"]}, m) user = self.content_migration_user.get_parent() self.assertIsInstance(user, User) - self.assertTrue(hasattr(user, 'id')) + self.assertTrue(hasattr(user, "id")) self.assertEqual(user.id, 1) # get_progress() def test_get_progress(self, m): - register_uris({'content_migration': ['get_progress']}, m) + register_uris({"content_migration": ["get_progress"]}, m) progress = self.content_migration.get_progress() self.assertIsInstance(progress, Progress) - self.assertTrue(hasattr(progress, 'id')) + self.assertTrue(hasattr(progress, "id")) self.assertEqual(progress.id, 1) # update() def test_update(self, m): - register_uris({'content_migration': ['update']}, m) + register_uris({"content_migration": ["update"]}, m) worked = self.content_migration.update() self.assertTrue(worked) - self.assertTrue(hasattr(self.content_migration, 'migration_type')) + self.assertTrue(hasattr(self.content_migration, "migration_type")) self.assertEqual(self.content_migration.migration_type, "dummy_importer") def test_update_fail(self, m): - register_uris({'content_migration': ['update_fail']}, m) + register_uris({"content_migration": ["update_fail"]}, m) worked = self.content_migration.update() self.assertFalse(worked) @@ -168,15 +168,15 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_content_migration_single'], - 'group': ['get_by_id', 'get_content_migration_single'], - 'account': ['get_by_id', 'get_content_migration_single'], - 'user': ['get_by_id', 'get_content_migration_single'], - 'content_migration': [ - 'get_migration_issue_single', - 'get_migration_issue_single_course', - 'get_migration_issue_single_group', - 'get_migration_issue_single_user', + "course": ["get_by_id", "get_content_migration_single"], + "group": ["get_by_id", "get_content_migration_single"], + "account": ["get_by_id", "get_content_migration_single"], + "user": ["get_by_id", "get_content_migration_single"], + "content_migration": [ + "get_migration_issue_single", + "get_migration_issue_single_course", + "get_migration_issue_single_group", + "get_migration_issue_single_user", ], } register_uris(requires, m) @@ -209,15 +209,15 @@ def test__str__(self, m): # update() def test_update(self, m): - register_uris({'content_migration': ['update_issue']}, m) + register_uris({"content_migration": ["update_issue"]}, m) worked = self.migration_issue.update() self.assertTrue(worked) - self.assertTrue(hasattr(self.migration_issue, 'id')) + self.assertTrue(hasattr(self.migration_issue, "id")) self.assertEqual(self.migration_issue.id, 1) def test_update_fail(self, m): - register_uris({'content_migration': ['update_issue_fail']}, m) + register_uris({"content_migration": ["update_issue_fail"]}, m) worked = self.migration_issue.update() self.assertFalse(worked) @@ -230,15 +230,15 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_migration_systems_multiple'], - 'group': ['get_by_id', 'get_migration_systems_multiple'], - 'account': ['get_by_id', 'get_migration_systems_multiple'], - 'user': ['get_by_id', 'get_migration_systems_multiple'], - 'content_migration': [ - 'get_migration_issue_single', - 'get_migration_issue_single_course', - 'get_migration_issue_single_group', - 'get_migration_issue_single_user', + "course": ["get_by_id", "get_migration_systems_multiple"], + "group": ["get_by_id", "get_migration_systems_multiple"], + "account": ["get_by_id", "get_migration_systems_multiple"], + "user": ["get_by_id", "get_migration_systems_multiple"], + "content_migration": [ + "get_migration_issue_single", + "get_migration_issue_single_course", + "get_migration_issue_single_group", + "get_migration_issue_single_user", ], } register_uris(requires, m) diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 9c16a5ef..aeee2167 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -15,7 +15,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'conversation': ['get_by_id']}, m) + register_uris({"conversation": ["get_by_id"]}, m) self.conversation = self.canvas.get_conversation(1) @@ -26,14 +26,14 @@ def test__str__(self, m): # edit() def test_edit(self, m): - register_uris({'conversation': ['edit_conversation']}, m) + register_uris({"conversation": ["edit_conversation"]}, m) new_subject = "conversations api example" success = self.conversation.edit(subject=new_subject) self.assertTrue(success) def test_edit_fail(self, m): - requires = {'conversation': ['get_by_id_2', 'edit_conversation_fail']} + requires = {"conversation": ["get_by_id_2", "edit_conversation_fail"]} register_uris(requires, m) temp_convo = self.canvas.get_conversation(2) @@ -41,13 +41,13 @@ def test_edit_fail(self, m): # delete() def test_delete(self, m): - register_uris({'conversation': ['delete_conversation']}, m) + register_uris({"conversation": ["delete_conversation"]}, m) success = self.conversation.delete() self.assertTrue(success) def test_delete_fail(self, m): - requires = {'conversation': ['get_by_id_2', 'delete_conversation_fail']} + requires = {"conversation": ["get_by_id_2", "delete_conversation_fail"]} register_uris(requires, m) temp_convo = self.canvas.get_conversation(2) @@ -55,34 +55,34 @@ def test_delete_fail(self, m): # add_recipients() def test_add_recipients(self, m): - register_uris({'conversation': ['add_recipients']}, m) + register_uris({"conversation": ["add_recipients"]}, m) - recipients = {'bob': 1, 'joe': 2} + recipients = {"bob": 1, "joe": 2} string_bob = "Bob was added to the conversation by Hank TA" string_joe = "Joe was added to the conversation by Hank TA" result = self.conversation.add_recipients( - [recipients['bob'], recipients['joe']] + [recipients["bob"], recipients["joe"]] ) - self.assertTrue(hasattr(result, 'messages')) + self.assertTrue(hasattr(result, "messages")) self.assertEqual(len(result.messages), 2) self.assertEqual(result.messages[0]["body"], string_bob) self.assertEqual(result.messages[1]["body"], string_joe) # add_message() def test_add_message(self, m): - register_uris({'conversation': ['add_message']}, m) + register_uris({"conversation": ["add_message"]}, m) test_string = "add_message test body" result = self.conversation.add_message(test_string) self.assertIsInstance(result, Conversation) self.assertEqual(len(result.messages), 1) - self.assertEqual(result.messages[0]['id'], 3) + self.assertEqual(result.messages[0]["id"], 3) # delete_message() def test_delete_message(self, m): - register_uris({'conversation': ['delete_message']}, m) + register_uris({"conversation": ["delete_message"]}, m) id_list = [1] result = self.conversation.delete_messages(id_list) - self.assertIn('subject', result) - self.assertEqual(result['id'], 1) + self.assertIn("subject", result) + self.assertEqual(result["id"], 1) diff --git a/tests/test_course.py b/tests/test_course.py index f8d17ae2..44372110 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -49,14 +49,14 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_assignment_by_id', 'get_by_id', 'get_page'], - 'quiz': ['get_by_id'], - 'user': ['get_by_id'], + "course": ["get_assignment_by_id", "get_by_id", "get_page"], + "quiz": ["get_by_id"], + "user": ["get_by_id"], } register_uris(requires, m) self.course = self.canvas.get_course(1) - self.page = self.course.get_page('my-url') + self.page = self.course.get_page("my-url") self.quiz = self.course.get_quiz(1) self.user = self.canvas.get_user(1) self.assignment = self.course.get_assignment(1) @@ -68,25 +68,25 @@ def test__str__(self, m): # conclude() def test_conclude(self, m): - register_uris({'course': ['conclude']}, m) + register_uris({"course": ["conclude"]}, m) success = self.course.conclude() self.assertTrue(success) # create_assignment_overrides() def test_create_assignment_overrides(self, m): - register_uris({'assignment': ['batch_create_assignment_overrides']}, m) + register_uris({"assignment": ["batch_create_assignment_overrides"]}, m) override_list = [ { - 'student_ids': [1, 2, 3], - 'title': 'New Assignment Override', - 'assignment_id': 1, + "student_ids": [1, 2, 3], + "title": "New Assignment Override", + "assignment_id": 1, }, { - 'assignment_id': 2, - 'student_ids': [1, 2, 3], - 'title': 'New Assignment Override 2', + "assignment_id": 2, + "student_ids": [1, 2, 3], + "title": "New Assignment Override 2", }, ] created_overrides = self.course.create_assignment_overrides(override_list) @@ -98,33 +98,33 @@ def test_create_assignment_overrides(self, m): # delete() def test_delete(self, m): - register_uris({'course': ['delete']}, m) + register_uris({"course": ["delete"]}, m) success = self.course.delete() self.assertTrue(success) # update() def test_update(self, m): - register_uris({'course': ['update']}, m) + register_uris({"course": ["update"]}, m) - new_name = 'New Name' - self.course.update(course={'name': new_name}) + new_name = "New Name" + self.course.update(course={"name": new_name}) self.assertEqual(self.course.name, new_name) # update_assignment_overrides() def test_update_assignment_overrides(self, m): - register_uris({'assignment': ['batch_update_assignment_overrides']}, m) + register_uris({"assignment": ["batch_update_assignment_overrides"]}, m) override_list = [ { - 'student_ids': [4, 5, 6], - 'title': 'Updated Assignment Override', - 'assignment_id': 1, + "student_ids": [4, 5, 6], + "title": "Updated Assignment Override", + "assignment_id": 1, }, { - 'assignment_id': 2, - 'student_ids': [6, 7], - 'title': 'Updated Assignment Override 2', + "assignment_id": 2, + "student_ids": [6, 7], + "title": "Updated Assignment Override 2", }, ] updated_overrides = self.course.update_assignment_overrides(override_list) @@ -136,27 +136,27 @@ def test_update_assignment_overrides(self, m): # get_user() def test_get_user(self, m): - register_uris({'course': ['get_user']}, m) + register_uris({"course": ["get_user"]}, m) user_by_id = self.course.get_user(1) self.assertIsInstance(user_by_id, User) - self.assertTrue(hasattr(user_by_id, 'name')) + self.assertTrue(hasattr(user_by_id, "name")) user_by_obj = self.course.get_user(user_by_id) self.assertIsInstance(user_by_obj, User) - self.assertTrue(hasattr(user_by_obj, 'name')) + self.assertTrue(hasattr(user_by_obj, "name")) def test_get_user_id_type(self, m): - register_uris({'course': ['get_user_id_type']}, m) + register_uris({"course": ["get_user_id_type"]}, m) user = self.course.get_user("LOGINID", "login_id") self.assertIsInstance(user, User) - self.assertTrue(hasattr(user, 'name')) + self.assertTrue(hasattr(user, "name")) # get_users() def test_get_users(self, m): - register_uris({'course': ['get_users', 'get_users_p2']}, m) + register_uris({"course": ["get_users", "get_users_p2"]}, m) users = self.course.get_users() user_list = [user for user in users] @@ -166,27 +166,27 @@ def test_get_users(self, m): # enroll_user() def test_enroll_user(self, m): - requires = {'course': ['enroll_user'], 'user': ['get_by_id']} + requires = {"course": ["enroll_user"], "user": ["get_by_id"]} register_uris(requires, m) - enrollment_type = 'TeacherEnrollment' + enrollment_type = "TeacherEnrollment" user_by_id = self.canvas.get_user(1) enrollment_by_id = self.course.enroll_user(user_by_id, enrollment_type) self.assertIsInstance(enrollment_by_id, Enrollment) - self.assertTrue(hasattr(enrollment_by_id, 'type')) + self.assertTrue(hasattr(enrollment_by_id, "type")) self.assertEqual(enrollment_by_id.type, enrollment_type) user_by_obj = self.canvas.get_user(self.user) enrollment_by_obj = self.course.enroll_user(user_by_obj, enrollment_type) self.assertIsInstance(enrollment_by_obj, Enrollment) - self.assertTrue(hasattr(enrollment_by_obj, 'type')) + self.assertTrue(hasattr(enrollment_by_obj, "type")) self.assertEqual(enrollment_by_obj.type, enrollment_type) # get_recent_students() def test_get_recent_students(self, m): - recent = {'course': ['get_recent_students', 'get_recent_students_p2']} + recent = {"course": ["get_recent_students", "get_recent_students_p2"]} register_uris(recent, m) students = self.course.get_recent_students() @@ -194,11 +194,11 @@ def test_get_recent_students(self, m): self.assertEqual(len(student_list), 4) self.assertIsInstance(student_list[0], User) - self.assertTrue(hasattr(student_list[0], 'name')) + self.assertTrue(hasattr(student_list[0], "name")) # preview_html() def test_preview_html(self, m): - register_uris({'course': ['preview_html']}, m) + register_uris({"course": ["preview_html"]}, m) html_str = "

hello

" prev_html = self.course.preview_html(html_str) @@ -208,7 +208,7 @@ def test_preview_html(self, m): # get_settings() def test_get_settings(self, m): - register_uris({'course': ['settings']}, m) + register_uris({"course": ["settings"]}, m) settings = self.course.get_settings() @@ -216,49 +216,49 @@ def test_get_settings(self, m): # update_settings() def test_update_settings(self, m): - register_uris({'course': ['update_settings']}, m) + register_uris({"course": ["update_settings"]}, m) settings = self.course.update_settings() self.assertIsInstance(settings, dict) - self.assertTrue(settings['hide_final_grades']) + self.assertTrue(settings["hide_final_grades"]) # upload() def test_upload(self, m): - register_uris({'course': ['upload', 'upload_final']}, m) + register_uris({"course": ["upload", "upload_final"]}, m) - filename = 'testfile_course_{}'.format(uuid.uuid4().hex) + filename = "testfile_course_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.course.upload(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) # reset() def test_reset(self, m): - register_uris({'course': ['reset']}, m) + register_uris({"course": ["reset"]}, m) course = self.course.reset() self.assertIsInstance(course, Course) - self.assertTrue(hasattr(course, 'name')) + self.assertTrue(hasattr(course, "name")) # create_quiz() def test_create_quiz(self, m): - register_uris({'course': ['create_quiz']}, m) + register_uris({"course": ["create_quiz"]}, m) - title = 'Newer Title' - new_quiz = self.course.create_quiz({'title': title}) + title = "Newer Title" + new_quiz = self.course.create_quiz({"title": title}) self.assertIsInstance(new_quiz, Quiz) - self.assertTrue(hasattr(new_quiz, 'title')) + self.assertTrue(hasattr(new_quiz, "title")) self.assertEqual(new_quiz.title, title) - self.assertTrue(hasattr(new_quiz, 'course_id')) + self.assertTrue(hasattr(new_quiz, "course_id")) self.assertEqual(new_quiz.course_id, self.course.id) def test_create_quiz_fail(self, m): @@ -267,76 +267,76 @@ def test_create_quiz_fail(self, m): # get_quiz() def test_get_quiz(self, m): - register_uris({'course': ['get_quiz']}, m) + register_uris({"course": ["get_quiz"]}, m) target_quiz_by_id = self.course.get_quiz(1) self.assertIsInstance(target_quiz_by_id, Quiz) - self.assertTrue(hasattr(target_quiz_by_id, 'course_id')) + self.assertTrue(hasattr(target_quiz_by_id, "course_id")) self.assertEqual(target_quiz_by_id.course_id, self.course.id) target_quiz_by_obj = self.course.get_quiz(target_quiz_by_id) self.assertIsInstance(target_quiz_by_obj, Quiz) - self.assertTrue(hasattr(target_quiz_by_obj, 'course_id')) + self.assertTrue(hasattr(target_quiz_by_obj, "course_id")) self.assertEqual(target_quiz_by_obj.course_id, self.course.id) def test_get_quiz_fail(self, m): - register_uris({'generic': ['not_found']}, m) + register_uris({"generic": ["not_found"]}, m) with self.assertRaises(ResourceDoesNotExist): self.course.get_quiz(settings.INVALID_ID) # get_quizzes() def test_get_quizzes(self, m): - register_uris({'course': ['list_quizzes', 'list_quizzes2']}, m) + register_uris({"course": ["list_quizzes", "list_quizzes2"]}, m) quizzes = self.course.get_quizzes() quiz_list = [quiz for quiz in quizzes] self.assertEqual(len(quiz_list), 4) self.assertIsInstance(quiz_list[0], Quiz) - self.assertTrue(hasattr(quiz_list[0], 'course_id')) + self.assertTrue(hasattr(quiz_list[0], "course_id")) self.assertEqual(quiz_list[0].course_id, self.course.id) # get_modules() def test_get_modules(self, m): - register_uris({'course': ['list_modules', 'list_modules2']}, m) + register_uris({"course": ["list_modules", "list_modules2"]}, m) modules = self.course.get_modules() module_list = [module for module in modules] self.assertEqual(len(module_list), 4) self.assertIsInstance(module_list[0], Module) - self.assertTrue(hasattr(module_list[0], 'course_id')) + self.assertTrue(hasattr(module_list[0], "course_id")) self.assertEqual(module_list[0].course_id, self.course.id) # get_module() def test_get_module(self, m): - register_uris({'course': ['get_module_by_id']}, m) + register_uris({"course": ["get_module_by_id"]}, m) target_module_by_id = self.course.get_module(1) self.assertIsInstance(target_module_by_id, Module) - self.assertTrue(hasattr(target_module_by_id, 'course_id')) + self.assertTrue(hasattr(target_module_by_id, "course_id")) self.assertEqual(target_module_by_id.course_id, self.course.id) target_module_by_obj = self.course.get_module(target_module_by_id) self.assertIsInstance(target_module_by_obj, Module) - self.assertTrue(hasattr(target_module_by_obj, 'course_id')) + self.assertTrue(hasattr(target_module_by_obj, "course_id")) self.assertEqual(target_module_by_obj.course_id, self.course.id) # create_module() def test_create_module(self, m): - register_uris({'course': ['create_module']}, m) + register_uris({"course": ["create_module"]}, m) - name = 'Name' - new_module = self.course.create_module(module={'name': name}) + name = "Name" + new_module = self.course.create_module(module={"name": name}) self.assertIsInstance(new_module, Module) - self.assertTrue(hasattr(new_module, 'name')) - self.assertTrue(hasattr(new_module, 'course_id')) + self.assertTrue(hasattr(new_module, "name")) + self.assertTrue(hasattr(new_module, "course_id")) self.assertEqual(new_module.course_id, self.course.id) def test_create_module_fail(self, m): @@ -345,7 +345,7 @@ def test_create_module_fail(self, m): # get_enrollments() def test_get_enrollments(self, m): - register_uris({'course': ['list_enrollments', 'list_enrollments_2']}, m) + register_uris({"course": ["list_enrollments", "list_enrollments_2"]}, m) enrollments = self.course.get_enrollments() enrollment_list = [enrollment for enrollment in enrollments] @@ -355,7 +355,7 @@ def test_get_enrollments(self, m): # get_sections() def test_get_sections(self, m): - register_uris({'course': ['get_sections', 'get_sections_p2']}, m) + register_uris({"course": ["get_sections", "get_sections_p2"]}, m) sections = self.course.get_sections() section_list = [section for section in sections] @@ -365,7 +365,7 @@ def test_get_sections(self, m): # get_section def test_get_section(self, m): - register_uris({'course': ['get_section']}, m) + register_uris({"course": ["get_section"]}, m) section_by_id = self.course.get_section(1) self.assertIsInstance(section_by_id, Section) @@ -375,14 +375,14 @@ def test_get_section(self, m): # create_assignment() def test_create_assignment(self, m): - register_uris({'course': ['create_assignment']}, m) + register_uris({"course": ["create_assignment"]}, m) - name = 'Newly Created Assignment' + name = "Newly Created Assignment" - assignment = self.course.create_assignment(assignment={'name': name}) + assignment = self.course.create_assignment(assignment={"name": name}) self.assertIsInstance(assignment, Assignment) - self.assertTrue(hasattr(assignment, 'name')) + self.assertTrue(hasattr(assignment, "name")) self.assertEqual(assignment.name, name) self.assertEqual(assignment.id, 1) @@ -392,29 +392,29 @@ def test_create_assignment_fail(self, m): # get_assignment() def test_get_assignment(self, m): - register_uris({'course': ['get_assignment_by_id']}, m) + register_uris({"course": ["get_assignment_by_id"]}, m) assignment_by_id = self.course.get_assignment(1) self.assertIsInstance(assignment_by_id, Assignment) - self.assertTrue(hasattr(assignment_by_id, 'name')) + self.assertTrue(hasattr(assignment_by_id, "name")) assignment_by_obj = self.course.get_assignment(self.assignment) self.assertIsInstance(assignment_by_obj, Assignment) - self.assertTrue(hasattr(assignment_by_obj, 'name')) + self.assertTrue(hasattr(assignment_by_obj, "name")) # get_assignment_overrides() def test_get_assignment_overrides(self, m): register_uris( { - 'assignment': [ - 'batch_get_assignment_overrides', - 'batch_get_assignment_overrides_p2', + "assignment": [ + "batch_get_assignment_overrides", + "batch_get_assignment_overrides_p2", ] }, m, ) - bulk_select = [{'id': 1, 'assignment_id': 1}, {'id': 20, 'assignment_id': 2}] + bulk_select = [{"id": 1, "assignment_id": 1}, {"id": 20, "assignment_id": 2}] overrides = self.course.get_assignment_overrides(bulk_select) override_list = [override for override in overrides] @@ -424,7 +424,7 @@ def test_get_assignment_overrides(self, m): # get_assignments() def test_get_assignments(self, m): - requires = {'course': ['get_all_assignments', 'get_all_assignments2']} + requires = {"course": ["get_all_assignments", "get_all_assignments2"]} register_uris(requires, m) assignments = self.course.get_assignments() @@ -435,56 +435,56 @@ def test_get_assignments(self, m): # show_front_page() def test_show_front_page(self, m): - register_uris({'course': ['show_front_page']}, m) + register_uris({"course": ["show_front_page"]}, m) front_page = self.course.show_front_page() self.assertIsInstance(front_page, Page) - self.assertTrue(hasattr(front_page, 'url')) - self.assertTrue(hasattr(front_page, 'title')) + self.assertTrue(hasattr(front_page, "url")) + self.assertTrue(hasattr(front_page, "title")) # create_front_page() def test_edit_front_page(self, m): - register_uris({'course': ['edit_front_page']}, m) + register_uris({"course": ["edit_front_page"]}, m) new_front_page = self.course.edit_front_page() self.assertIsInstance(new_front_page, Page) - self.assertTrue(hasattr(new_front_page, 'url')) - self.assertTrue(hasattr(new_front_page, 'title')) + self.assertTrue(hasattr(new_front_page, "url")) + self.assertTrue(hasattr(new_front_page, "title")) # get_page() def test_get_page(self, m): - register_uris({'course': ['get_page']}, m) + register_uris({"course": ["get_page"]}, m) - url = 'my-url' + url = "my-url" page = self.course.get_page(url) self.assertIsInstance(page, Page) # get_pages() def test_get_pages(self, m): - register_uris({'course': ['get_pages', 'get_pages2']}, m) + register_uris({"course": ["get_pages", "get_pages2"]}, m) pages = self.course.get_pages() page_list = [page for page in pages] self.assertEqual(len(page_list), 4) self.assertIsInstance(page_list[0], Page) - self.assertTrue(hasattr(page_list[0], 'course_id')) + self.assertTrue(hasattr(page_list[0], "course_id")) self.assertEqual(page_list[0].course_id, self.course.id) # create_page() def test_create_page(self, m): - register_uris({'course': ['create_page']}, m) + register_uris({"course": ["create_page"]}, m) title = "Newest Page" - new_page = self.course.create_page(wiki_page={'title': title}) + new_page = self.course.create_page(wiki_page={"title": title}) self.assertIsInstance(new_page, Page) - self.assertTrue(hasattr(new_page, 'title')) + self.assertTrue(hasattr(new_page, "title")) self.assertEqual(new_page.title, title) - self.assertTrue(hasattr(new_page, 'course_id')) + self.assertTrue(hasattr(new_page, "course_id")) self.assertEqual(new_page.course_id, self.course.id) def test_create_page_fail(self, m): @@ -493,19 +493,19 @@ def test_create_page_fail(self, m): # get_external_tool() def test_get_external_tool(self, m): - register_uris({'external_tool': ['get_by_id_course']}, m) + register_uris({"external_tool": ["get_by_id_course"]}, m) tool_by_id = self.course.get_external_tool(1) self.assertIsInstance(tool_by_id, ExternalTool) - self.assertTrue(hasattr(tool_by_id, 'name')) + self.assertTrue(hasattr(tool_by_id, "name")) tool_by_obj = self.course.get_external_tool(tool_by_id) self.assertIsInstance(tool_by_obj, ExternalTool) - self.assertTrue(hasattr(tool_by_obj, 'name')) + self.assertTrue(hasattr(tool_by_obj, "name")) # get_external_tools() def test_get_external_tools(self, m): - requires = {'course': ['get_external_tools', 'get_external_tools_p2']} + requires = {"course": ["get_external_tools", "get_external_tools_p2"]} register_uris(requires, m) tools = self.course.get_external_tools() @@ -515,7 +515,7 @@ def test_get_external_tools(self, m): self.assertEqual(len(tool_list), 4) def test_list_sections(self, m): - register_uris({'course': ['get_sections', 'get_sections_p2']}, m) + register_uris({"course": ["get_sections", "get_sections_p2"]}, m) with warnings.catch_warnings(record=True) as warning_list: sections = self.course.list_sections() @@ -528,7 +528,7 @@ def test_list_sections(self, m): self.assertEqual(warning_list[-1].category, DeprecationWarning) def test_create_course_section(self, m): - register_uris({'course': ['create_section']}, m) + register_uris({"course": ["create_section"]}, m) section = self.course.create_course_section() @@ -536,7 +536,7 @@ def test_create_course_section(self, m): # list_groups() def test_list_groups(self, m): - requires = {'course': ['list_groups_context', 'list_groups_context2']} + requires = {"course": ["list_groups_context", "list_groups_context2"]} register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: @@ -551,7 +551,7 @@ def test_list_groups(self, m): # get_groups() def test_get_groups(self, m): - requires = {'course': ['list_groups_context', 'list_groups_context2']} + requires = {"course": ["list_groups_context", "list_groups_context2"]} register_uris(requires, m) groups = self.course.get_groups() @@ -562,7 +562,7 @@ def test_get_groups(self, m): # create_group_category() def test_create_group_category(self, m): - register_uris({'course': ['create_group_category']}, m) + register_uris({"course": ["create_group_category"]}, m) name_str = "Test String" response = self.course.create_group_category(name=name_str) @@ -570,7 +570,7 @@ def test_create_group_category(self, m): # list_group_categories() def test_list_group_categories(self, m): - register_uris({'course': ['list_group_categories']}, m) + register_uris({"course": ["list_group_categories"]}, m) with warnings.catch_warnings(record=True) as warning_list: response = self.course.list_group_categories() @@ -582,7 +582,7 @@ def test_list_group_categories(self, m): # get_group_categories() def test_get_group_categories(self, m): - register_uris({'course': ['list_group_categories']}, m) + register_uris({"course": ["list_group_categories"]}, m) response = self.course.get_group_categories() category_list = [category for category in response] @@ -590,73 +590,73 @@ def test_get_group_categories(self, m): # get_discussion_topic() def test_get_discussion_topic(self, m): - register_uris({'course': ['get_discussion_topic']}, m) + register_uris({"course": ["get_discussion_topic"]}, m) topic_id = 1 discussion_by_id = self.course.get_discussion_topic(topic_id) self.assertIsInstance(discussion_by_id, DiscussionTopic) - self.assertTrue(hasattr(discussion_by_id, 'course_id')) + self.assertTrue(hasattr(discussion_by_id, "course_id")) self.assertEqual(discussion_by_id.course_id, 1) discussion_by_obj = self.course.get_discussion_topic(discussion_by_id) self.assertIsInstance(discussion_by_obj, DiscussionTopic) - self.assertTrue(hasattr(discussion_by_obj, 'course_id')) + self.assertTrue(hasattr(discussion_by_obj, "course_id")) self.assertEqual(discussion_by_obj.course_id, 1) # get_file() def test_get_file(self, m): - register_uris({'course': ['get_file']}, m) + register_uris({"course": ["get_file"]}, m) file_by_id = self.course.get_file(1) self.assertIsInstance(file_by_id, File) - self.assertEqual(file_by_id.display_name, 'Course_File.docx') + self.assertEqual(file_by_id.display_name, "Course_File.docx") self.assertEqual(file_by_id.size, 2048) file_by_obj = self.course.get_file(file_by_id) self.assertIsInstance(file_by_obj, File) - self.assertEqual(file_by_obj.display_name, 'Course_File.docx') + self.assertEqual(file_by_obj.display_name, "Course_File.docx") self.assertEqual(file_by_obj.size, 2048) # get_full_discussion_topic() def test_get_full_discussion_topic(self, m): register_uris( - {'course': ['get_discussion_topics', 'get_full_discussion_topic']}, m + {"course": ["get_discussion_topics", "get_full_discussion_topic"]}, m ) topic_id = 1 discussion_by_id = self.course.get_full_discussion_topic(topic_id) self.assertIsInstance(discussion_by_id, dict) - self.assertIn('view', discussion_by_id) - self.assertIn('participants', discussion_by_id) - self.assertIn('id', discussion_by_id) - self.assertEqual(discussion_by_id['id'], topic_id) + self.assertIn("view", discussion_by_id) + self.assertIn("participants", discussion_by_id) + self.assertIn("id", discussion_by_id) + self.assertEqual(discussion_by_id["id"], topic_id) discussion_topics = self.course.get_discussion_topics() discussion_by_obj = self.course.get_full_discussion_topic(discussion_topics[0]) self.assertIsInstance(discussion_by_obj, dict) - self.assertIn('view', discussion_by_obj) - self.assertIn('participants', discussion_by_obj) - self.assertIn('id', discussion_by_obj) - self.assertEqual(discussion_by_obj['id'], topic_id) + self.assertIn("view", discussion_by_obj) + self.assertIn("participants", discussion_by_obj) + self.assertIn("id", discussion_by_obj) + self.assertEqual(discussion_by_obj["id"], topic_id) # get_discussion_topics() def test_get_discussion_topics(self, m): - register_uris({'course': ['get_discussion_topics']}, m) + register_uris({"course": ["get_discussion_topics"]}, m) response = self.course.get_discussion_topics() discussion_list = [discussion for discussion in response] self.assertIsInstance(discussion_list[0], DiscussionTopic) - self.assertTrue(hasattr(discussion_list[0], 'course_id')) + self.assertTrue(hasattr(discussion_list[0], "course_id")) self.assertEqual(2, len(discussion_list)) # create_discussion_topic() def test_create_discussion_topic(self, m): - register_uris({'course': ['create_discussion_topic']}, m) + register_uris({"course": ["create_discussion_topic"]}, m) title = "Topic 1" discussion = self.course.create_discussion_topic() self.assertIsInstance(discussion, DiscussionTopic) - self.assertTrue(hasattr(discussion, 'course_id')) + self.assertTrue(hasattr(discussion, "course_id")) self.assertEqual(title, discussion.title) self.assertEqual(discussion.course_id, 1) @@ -664,8 +664,8 @@ def test_create_discussion_topic(self, m): def test_reorder_pinned_topics(self, m): # Custom matcher to test that params are set correctly def custom_matcher(request): - match_text = '1,2,3' - if request.text == 'order={}'.format(quote(match_text)): + match_text = "1,2,3" + if request.text == "order={}".format(quote(match_text)): resp = requests.Response() resp._content = b'{"reorder": true, "order": [1, 2, 3]}' resp.status_code = 200 @@ -678,14 +678,14 @@ def custom_matcher(request): self.assertTrue(discussions) def test_reorder_pinned_topics_tuple(self, m): - register_uris({'course': ['reorder_pinned_topics']}, m) + register_uris({"course": ["reorder_pinned_topics"]}, m) order = (1, 2, 3) discussions = self.course.reorder_pinned_topics(order=order) self.assertTrue(discussions) def test_reorder_pinned_topics_comma_separated_string(self, m): - register_uris({'course': ['reorder_pinned_topics']}, m) + register_uris({"course": ["reorder_pinned_topics"]}, m) order = "1,2,3" discussions = self.course.reorder_pinned_topics(order=order) @@ -698,14 +698,14 @@ def test_reorder_pinned_topics_invalid_input(self, m): # get_assignment_group() def test_get_assignment_group(self, m): - register_uris({'assignment': ['get_assignment_group']}, m) + register_uris({"assignment": ["get_assignment_group"]}, m) assignment_group_by_id = self.course.get_assignment_group(5) self.assertIsInstance(assignment_group_by_id, AssignmentGroup) - self.assertTrue(hasattr(assignment_group_by_id, 'id')) - self.assertTrue(hasattr(assignment_group_by_id, 'name')) - self.assertTrue(hasattr(assignment_group_by_id, 'course_id')) + self.assertTrue(hasattr(assignment_group_by_id, "id")) + self.assertTrue(hasattr(assignment_group_by_id, "name")) + self.assertTrue(hasattr(assignment_group_by_id, "course_id")) self.assertEqual(assignment_group_by_id.course_id, 1) assignment_group_by_obj = self.course.get_assignment_group( @@ -713,24 +713,24 @@ def test_get_assignment_group(self, m): ) self.assertIsInstance(assignment_group_by_obj, AssignmentGroup) - self.assertTrue(hasattr(assignment_group_by_obj, 'id')) - self.assertTrue(hasattr(assignment_group_by_obj, 'name')) - self.assertTrue(hasattr(assignment_group_by_obj, 'course_id')) + self.assertTrue(hasattr(assignment_group_by_obj, "id")) + self.assertTrue(hasattr(assignment_group_by_obj, "name")) + self.assertTrue(hasattr(assignment_group_by_obj, "course_id")) self.assertEqual(assignment_group_by_obj.course_id, 1) # list_assignment_groups() def test_list_assignment_groups(self, m): register_uris( - {'assignment': ['list_assignment_groups', 'get_assignment_group']}, m + {"assignment": ["list_assignment_groups", "get_assignment_group"]}, m ) with warnings.catch_warnings(record=True) as warning_list: response = self.course.list_assignment_groups() asnt_group_list = [assignment_group for assignment_group in response] self.assertIsInstance(asnt_group_list[0], AssignmentGroup) - self.assertTrue(hasattr(asnt_group_list[0], 'id')) - self.assertTrue(hasattr(asnt_group_list[0], 'name')) - self.assertTrue(hasattr(asnt_group_list[0], 'course_id')) + self.assertTrue(hasattr(asnt_group_list[0], "id")) + self.assertTrue(hasattr(asnt_group_list[0], "name")) + self.assertTrue(hasattr(asnt_group_list[0], "course_id")) self.assertEqual(asnt_group_list[0].course_id, 1) self.assertEqual(len(warning_list), 1) @@ -739,30 +739,30 @@ def test_list_assignment_groups(self, m): # get_assignment_groups() def test_get_assignment_groups(self, m): register_uris( - {'assignment': ['list_assignment_groups', 'get_assignment_group']}, m + {"assignment": ["list_assignment_groups", "get_assignment_group"]}, m ) response = self.course.get_assignment_groups() asnt_group_list = [assignment_group for assignment_group in response] self.assertIsInstance(asnt_group_list[0], AssignmentGroup) - self.assertTrue(hasattr(asnt_group_list[0], 'id')) - self.assertTrue(hasattr(asnt_group_list[0], 'name')) - self.assertTrue(hasattr(asnt_group_list[0], 'course_id')) + self.assertTrue(hasattr(asnt_group_list[0], "id")) + self.assertTrue(hasattr(asnt_group_list[0], "name")) + self.assertTrue(hasattr(asnt_group_list[0], "course_id")) self.assertEqual(asnt_group_list[0].course_id, 1) # create_assignment_group() def test_create_assignment_group(self, m): - register_uris({'assignment': ['create_assignment_group']}, m) + register_uris({"assignment": ["create_assignment_group"]}, m) response = self.course.create_assignment_group() self.assertIsInstance(response, AssignmentGroup) - self.assertTrue(hasattr(response, 'id')) + self.assertTrue(hasattr(response, "id")) self.assertEqual(response.id, 3) # create_external_tool() def test_create_external_tool(self, m): - register_uris({'external_tool': ['create_tool_course']}, m) + register_uris({"external_tool": ["create_tool_course"]}, m) response = self.course.create_external_tool( name="External Tool - Course", @@ -772,12 +772,12 @@ def test_create_external_tool(self, m): ) self.assertIsInstance(response, ExternalTool) - self.assertTrue(hasattr(response, 'id')) + self.assertTrue(hasattr(response, "id")) self.assertEqual(response.id, 20) # get_course_level_participation_data() def test_get_course_level_participation_data(self, m): - register_uris({'course': ['get_course_level_participation_data']}, m) + register_uris({"course": ["get_course_level_participation_data"]}, m) response = self.course.get_course_level_participation_data() @@ -785,7 +785,7 @@ def test_get_course_level_participation_data(self, m): # get_course_level_assignment_data() def test_get_course_level_assignment_data(self, m): - register_uris({'course': ['get_course_level_assignment_data']}, m) + register_uris({"course": ["get_course_level_assignment_data"]}, m) response = self.course.get_course_level_assignment_data() @@ -793,7 +793,7 @@ def test_get_course_level_assignment_data(self, m): # get_course_level_student_summary_data() def test_get_course_level_student_summary_data(self, m): - register_uris({'course': ['get_course_level_student_summary_data']}, m) + register_uris({"course": ["get_course_level_student_summary_data"]}, m) response = self.course.get_course_level_student_summary_data() @@ -801,7 +801,7 @@ def test_get_course_level_student_summary_data(self, m): # get_user_in_a_course_level_participation_data() def test_get_user_in_a_course_level_participation_data(self, m): - register_uris({'course': ['get_user_in_a_course_level_participation_data']}, m) + register_uris({"course": ["get_user_in_a_course_level_participation_data"]}, m) response = self.course.get_user_in_a_course_level_participation_data(1) self.assertIsInstance(response, list) @@ -811,7 +811,7 @@ def test_get_user_in_a_course_level_participation_data(self, m): # get_user_in_a_course_level_assignment_data() def test_get_user_in_a_course_level_assignment_data(self, m): - register_uris({'course': ['get_user_in_a_course_level_assignment_data']}, m) + register_uris({"course": ["get_user_in_a_course_level_assignment_data"]}, m) response = self.course.get_user_in_a_course_level_assignment_data(1) self.assertIsInstance(response, list) @@ -821,7 +821,7 @@ def test_get_user_in_a_course_level_assignment_data(self, m): # get_user_in_a_course_level_messaging_data() def test_get_user_in_a_course_level_messaging_data(self, m): - register_uris({'course': ['get_user_in_a_course_level_messaging_data']}, m) + register_uris({"course": ["get_user_in_a_course_level_messaging_data"]}, m) response = self.course.get_user_in_a_course_level_messaging_data(1) self.assertIsInstance(response, list) @@ -831,16 +831,16 @@ def test_get_user_in_a_course_level_messaging_data(self, m): # submit_assignment() def test_submit_assignment(self, m): - register_uris({'assignment': ['submit']}, m) + register_uris({"assignment": ["submit"]}, m) with warnings.catch_warnings(record=True) as warning_list: assignment_id = 1 sub_type = "online_upload" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} submission_by_id = self.course.submit_assignment(assignment_id, sub_dict) self.assertIsInstance(submission_by_id, Submission) - self.assertTrue(hasattr(submission_by_id, 'submission_type')) + self.assertTrue(hasattr(submission_by_id, "submission_type")) self.assertEqual(submission_by_id.submission_type, sub_type) self.assertEqual(len(warning_list), 1) @@ -850,7 +850,7 @@ def test_submit_assignment(self, m): submission_by_obj = self.course.submit_assignment(self.assignment, sub_dict) self.assertIsInstance(submission_by_obj, Submission) - self.assertTrue(hasattr(submission_by_obj, 'submission_type')) + self.assertTrue(hasattr(submission_by_obj, "submission_type")) self.assertEqual(submission_by_obj.submission_type, sub_type) self.assertEqual(len(warning_list), 1) @@ -866,7 +866,7 @@ def test_submit_assignment_fail(self, m): # list_submissions() def test_list_submissions(self, m): - register_uris({'submission': ['list_submissions']}, m) + register_uris({"submission": ["list_submissions"]}, m) with warnings.catch_warnings(record=True) as warning_list: assignment_id = 1 @@ -891,7 +891,7 @@ def test_list_submissions(self, m): # list_multiple_submission() def test_list_multiple_submissions(self, m): - register_uris({'course': ['list_multiple_submissions']}, m) + register_uris({"course": ["list_multiple_submissions"]}, m) with warnings.catch_warnings(record=True) as warning_list: submissions = self.course.list_multiple_submissions() @@ -905,7 +905,7 @@ def test_list_multiple_submissions(self, m): # get_multiple_submission() def test_get_multiple_submissions(self, m): - register_uris({'course': ['list_multiple_submissions']}, m) + register_uris({"course": ["list_multiple_submissions"]}, m) submissions = self.course.get_multiple_submissions() submission_list = [submission for submission in submissions] @@ -914,7 +914,7 @@ def test_get_multiple_submissions(self, m): self.assertIsInstance(submission_list[0], Submission) def test_get_multiple_submissions_grouped_true(self, m): - register_uris({'course': ['list_multiple_submissions_grouped']}, m) + register_uris({"course": ["list_multiple_submissions_grouped"]}, m) submissions = self.course.get_multiple_submissions(grouped=True) submission_list = [submission for submission in submissions] @@ -923,7 +923,7 @@ def test_get_multiple_submissions_grouped_true(self, m): self.assertIsInstance(submission_list[0], GroupedSubmission) def test_get_multiple_submissions_grouped_false(self, m): - register_uris({'course': ['list_multiple_submissions']}, m) + register_uris({"course": ["list_multiple_submissions"]}, m) submissions = self.course.get_multiple_submissions(grouped=False) submission_list = [submission for submission in submissions] @@ -933,14 +933,14 @@ def test_get_multiple_submissions_grouped_false(self, m): def test_get_multiple_submissions_grouped_invalid(self, m): with self.assertRaises(ValueError) as cm: - self.course.get_multiple_submissions(grouped='blargh') + self.course.get_multiple_submissions(grouped="blargh") self.assertIn("Parameter `grouped` must", cm.exception.args[0]) # get_submission() def test_get_submission(self, m): register_uris( - {'course': ['get_assignment_by_id'], 'submission': ['get_by_id_course']}, m + {"course": ["get_assignment_by_id"], "submission": ["get_by_id_course"]}, m ) assignment_for_id = 1 @@ -949,7 +949,7 @@ def test_get_submission(self, m): with warnings.catch_warnings(record=True) as warning_list: submission_by_id = self.course.get_submission(assignment_for_id, user_id) self.assertIsInstance(submission_by_id, Submission) - self.assertTrue(hasattr(submission_by_id, 'submission_type')) + self.assertTrue(hasattr(submission_by_id, "submission_type")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -960,7 +960,7 @@ def test_get_submission(self, m): assignment_for_obj, self.user ) self.assertIsInstance(submission_by_obj, Submission) - self.assertTrue(hasattr(submission_by_obj, 'submission_type')) + self.assertTrue(hasattr(submission_by_obj, "submission_type")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -969,8 +969,8 @@ def test_get_submission(self, m): def test_update_submission(self, m): register_uris( { - 'course': ['get_assignment_by_id'], - 'submission': ['edit', 'get_by_id_course'], + "course": ["get_assignment_by_id"], + "submission": ["edit", "get_by_id_course"], }, m, ) @@ -979,10 +979,10 @@ def test_update_submission(self, m): user_id = 1 with warnings.catch_warnings(record=True) as warning_list: submission = self.course.update_submission( - assignment_for_id, user_id, submission={'excuse': True} + assignment_for_id, user_id, submission={"excuse": True} ) self.assertIsInstance(submission, Submission) - self.assertTrue(hasattr(submission, 'excused')) + self.assertTrue(hasattr(submission, "excused")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -990,10 +990,10 @@ def test_update_submission(self, m): assignment_for_obj = self.course.get_assignment(1) with warnings.catch_warnings(record=True) as warning_list: submission = self.course.update_submission( - assignment_for_obj, self.user, submission={'excuse': True} + assignment_for_obj, self.user, submission={"excuse": True} ) self.assertIsInstance(submission, Submission) - self.assertTrue(hasattr(submission, 'excused')) + self.assertTrue(hasattr(submission, "excused")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -1001,7 +1001,7 @@ def test_update_submission(self, m): # list_gradeable_students() def test_list_gradeable_students(self, m): register_uris( - {'course': ['get_assignment_by_id', 'list_gradeable_students']}, m + {"course": ["get_assignment_by_id", "list_gradeable_students"]}, m ) assignment_for_id = 1 @@ -1029,7 +1029,7 @@ def test_list_gradeable_students(self, m): # mark_submission_as_read def test_mark_submission_as_read(self, m): register_uris( - {'course': ['get_assignment_by_id', 'mark_submission_as_read']}, m + {"course": ["get_assignment_by_id", "mark_submission_as_read"]}, m ) assignment_for_id = 1 @@ -1056,7 +1056,7 @@ def test_mark_submission_as_read(self, m): # mark_submission_as_unread def test_mark_submission_as_unread(self, m): register_uris( - {'course': ['get_assignment_by_id', 'mark_submission_as_unread']}, m + {"course": ["get_assignment_by_id", "mark_submission_as_unread"]}, m ) assignment_for_id = 1 @@ -1083,13 +1083,13 @@ def test_mark_submission_as_unread(self, m): # list_external_feeds() def test_list_external_feeds(self, m): - register_uris({'course': ['list_external_feeds']}, m) + register_uris({"course": ["list_external_feeds"]}, m) with warnings.catch_warnings(record=True) as warning_list: feeds = self.course.list_external_feeds() feed_list = [feed for feed in feeds] self.assertEqual(len(feed_list), 2) - self.assertTrue(hasattr(feed_list[0], 'url')) + self.assertTrue(hasattr(feed_list[0], "url")) self.assertIsInstance(feed_list[0], ExternalFeed) self.assertEqual(len(warning_list), 1) @@ -1097,17 +1097,17 @@ def test_list_external_feeds(self, m): # get_external_feeds() def test_get_external_feeds(self, m): - register_uris({'course': ['list_external_feeds']}, m) + register_uris({"course": ["list_external_feeds"]}, m) feeds = self.course.get_external_feeds() feed_list = [feed for feed in feeds] self.assertEqual(len(feed_list), 2) - self.assertTrue(hasattr(feed_list[0], 'url')) + self.assertTrue(hasattr(feed_list[0], "url")) self.assertIsInstance(feed_list[0], ExternalFeed) # create_external_feed() def test_create_external_feed(self, m): - register_uris({'course': ['create_external_feed']}, m) + register_uris({"course": ["create_external_feed"]}, m) url_str = "https://example.com/myblog.rss" response = self.course.create_external_feed(url=url_str) @@ -1115,22 +1115,22 @@ def test_create_external_feed(self, m): # delete_external_feed() def test_delete_external_feed(self, m): - register_uris({'course': ['delete_external_feed']}, m) + register_uris({"course": ["delete_external_feed"]}, m) ef_id = 1 deleted_ef_by_id = self.course.delete_external_feed(ef_id) self.assertIsInstance(deleted_ef_by_id, ExternalFeed) - self.assertTrue(hasattr(deleted_ef_by_id, 'url')) + self.assertTrue(hasattr(deleted_ef_by_id, "url")) self.assertEqual(deleted_ef_by_id.display_name, "My Blog") deleted_ef_by_obj = self.course.delete_external_feed(deleted_ef_by_id) self.assertIsInstance(deleted_ef_by_obj, ExternalFeed) - self.assertTrue(hasattr(deleted_ef_by_obj, 'url')) + self.assertTrue(hasattr(deleted_ef_by_obj, "url")) self.assertEqual(deleted_ef_by_obj.display_name, "My Blog") # list_files() def test_list_files(self, m): - register_uris({'course': ['list_course_files', 'list_course_files2']}, m) + register_uris({"course": ["list_course_files", "list_course_files2"]}, m) with warnings.catch_warnings(record=True) as warning_list: files = self.course.list_files() @@ -1143,7 +1143,7 @@ def test_list_files(self, m): # get_files() def test_get_files(self, m): - register_uris({'course': ['list_course_files', 'list_course_files2']}, m) + register_uris({"course": ["list_course_files", "list_course_files2"]}, m) files = self.course.get_files() file_list = [file for file in files] @@ -1152,7 +1152,7 @@ def test_get_files(self, m): # get_folder() def test_get_folder(self, m): - register_uris({'course': ['get_folder']}, m) + register_uris({"course": ["get_folder"]}, m) folder_by_id = self.course.get_folder(1) self.assertEqual(folder_by_id.name, "Folder 1") @@ -1164,7 +1164,7 @@ def test_get_folder(self, m): # list_folders() def test_list_folders(self, m): - register_uris({'course': ['list_folders']}, m) + register_uris({"course": ["list_folders"]}, m) with warnings.catch_warnings(record=True) as warning_list: folders = self.course.list_folders() @@ -1177,7 +1177,7 @@ def test_list_folders(self, m): # get_folders() def test_get_folders(self, m): - register_uris({'course': ['list_folders']}, m) + register_uris({"course": ["list_folders"]}, m) folders = self.course.get_folders() folder_list = [folder for folder in folders] @@ -1186,7 +1186,7 @@ def test_get_folders(self, m): # create_folder() def test_create_folder(self, m): - register_uris({'course': ['create_folder']}, m) + register_uris({"course": ["create_folder"]}, m) name_str = "Test String" response = self.course.create_folder(name=name_str) @@ -1194,7 +1194,7 @@ def test_create_folder(self, m): # list_tabs() def test_list_tabs(self, m): - register_uris({'course': ['list_tabs']}, m) + register_uris({"course": ["list_tabs"]}, m) with warnings.catch_warnings(record=True) as warning_list: tabs = self.course.list_tabs() @@ -1207,7 +1207,7 @@ def test_list_tabs(self, m): # get_tabs() def test_get_tabs(self, m): - register_uris({'course': ['list_tabs']}, m) + register_uris({"course": ["list_tabs"]}, m) tabs = self.course.get_tabs() tab_list = [tab for tab in tabs] @@ -1216,7 +1216,7 @@ def test_get_tabs(self, m): # update_tab() def test_update_tab(self, m): - register_uris({'course': ['update_tab']}, m) + register_uris({"course": ["update_tab"]}, m) tab_id = "pages" new_position = 3 @@ -1232,7 +1232,7 @@ def test_update_tab(self, m): # get_rubric def test_get_rubric(self, m): - register_uris({'course': ['get_rubric_single']}, m) + register_uris({"course": ["get_rubric_single"]}, m) rubric_id = 1 rubric = self.course.get_rubric(rubric_id) @@ -1243,7 +1243,7 @@ def test_get_rubric(self, m): # list_rubrics def test_list_rubrics(self, m): - register_uris({'course': ['get_rubric_multiple']}, m) + register_uris({"course": ["get_rubric_multiple"]}, m) with warnings.catch_warnings(record=True) as warning_list: rubrics = self.course.list_rubrics() @@ -1262,7 +1262,7 @@ def test_list_rubrics(self, m): # get_rubrics def test_get_rubrics(self, m): - register_uris({'course': ['get_rubric_multiple']}, m) + register_uris({"course": ["get_rubric_multiple"]}, m) rubrics = self.course.get_rubrics() @@ -1277,7 +1277,7 @@ def test_get_rubrics(self, m): # get_root_outcome_group() def test_get_root_outcome_group(self, m): - register_uris({'outcome': ['course_root_outcome_group']}, m) + register_uris({"outcome": ["course_root_outcome_group"]}, m) outcome_group = self.course.get_root_outcome_group() @@ -1287,7 +1287,7 @@ def test_get_root_outcome_group(self, m): # get_outcome_group() def test_get_outcome_group(self, m): - register_uris({'outcome': ['course_get_outcome_group']}, m) + register_uris({"outcome": ["course_get_outcome_group"]}, m) outcome_group_by_id = self.course.get_outcome_group(1) self.assertIsInstance(outcome_group_by_id, OutcomeGroup) @@ -1301,7 +1301,7 @@ def test_get_outcome_group(self, m): # get_outcome_groups_in_context() def test_get_outcome_groups_in_context(self, m): - register_uris({'outcome': ['course_outcome_groups_in_context']}, m) + register_uris({"outcome": ["course_outcome_groups_in_context"]}, m) outcome_group_list = self.course.get_outcome_groups_in_context() @@ -1311,35 +1311,35 @@ def test_get_outcome_groups_in_context(self, m): # get_all_outcome_links_in_context() def test_get_outcome_links_in_context(self, m): - register_uris({'outcome': ['course_outcome_links_in_context']}, m) + register_uris({"outcome": ["course_outcome_links_in_context"]}, m) outcome_link_list = self.course.get_all_outcome_links_in_context() self.assertIsInstance(outcome_link_list[0], OutcomeLink) - self.assertEqual(outcome_link_list[0].outcome_group['id'], 2) - self.assertEqual(outcome_link_list[0].outcome_group['title'], "test outcome") + self.assertEqual(outcome_link_list[0].outcome_group["id"], 2) + self.assertEqual(outcome_link_list[0].outcome_group["title"], "test outcome") # get_outcome_results() def test_get_outcome_results(self, m): - register_uris({'outcome': ['course_get_outcome_results']}, m) + register_uris({"outcome": ["course_get_outcome_results"]}, m) result = self.course.get_outcome_results() self.assertIsInstance(result, dict) - self.assertIsInstance(result['outcome_results'], list) + self.assertIsInstance(result["outcome_results"], list) # get_outcome_result_rollups() def test_get_outcome_result_rollups(self, m): - register_uris({'outcome': ['course_get_outcome_result_rollups']}, m) + register_uris({"outcome": ["course_get_outcome_result_rollups"]}, m) result = self.course.get_outcome_result_rollups() self.assertIsInstance(result, dict) - self.assertIsInstance(result['rollups'], list) + self.assertIsInstance(result["rollups"], list) # add_grading_standards() def test_add_grading_standards(self, m): - register_uris({'course': ['add_grading_standards']}, m) + register_uris({"course": ["add_grading_standards"]}, m) title = "Grading Standard 1" grading_scheme = [] @@ -1350,36 +1350,36 @@ def test_add_grading_standards(self, m): response = self.course.add_grading_standards(title, grading_scheme) self.assertIsInstance(response, GradingStandard) - self.assertTrue(hasattr(response, 'title')) + self.assertTrue(hasattr(response, "title")) self.assertEqual(title, response.title) self.assertTrue(hasattr(response, "grading_scheme")) - self.assertEqual(response.grading_scheme[0].get('name'), "A") - self.assertEqual(response.grading_scheme[0].get('value'), 0.9) + self.assertEqual(response.grading_scheme[0].get("name"), "A") + self.assertEqual(response.grading_scheme[0].get("value"), 0.9) # add_grading_standards() def test_add_grading_standards_empty_list(self, m): - register_uris({'course': ['add_grading_standards']}, m) + register_uris({"course": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): self.course.add_grading_standards("title", []) def test_add_grading_standards_non_dict_list(self, m): - register_uris({'course': ['add_grading_standards']}, m) + register_uris({"course": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): self.course.add_grading_standards("title", [1, 2, 3]) def test_add_grading_standards_missing_value_key(self, m): - register_uris({'course': ['add_grading_standards']}, m) + register_uris({"course": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): - self.course.add_grading_standards("title", [{'name': "test"}]) + self.course.add_grading_standards("title", [{"name": "test"}]) def test_add_grading_standards_missing_name_key(self, m): - register_uris({'course': ['add_grading_standards']}, m) + register_uris({"course": ["add_grading_standards"]}, m) with self.assertRaises(ValueError): - self.course.add_grading_standards("title", [{'value': 2}]) + self.course.add_grading_standards("title", [{"value": 2}]) # get_grading_standards() def test_get_grading_standards(self, m): - register_uris({'course': ['get_grading_standards']}, m) + register_uris({"course": ["get_grading_standards"]}, m) standards = self.course.get_grading_standards() standard_list = [standard for standard in standards] @@ -1389,31 +1389,31 @@ def test_get_grading_standards(self, m): # get_single_grading_standards() def test_get_single_grading_standard(self, m): - register_uris({'course': ['get_single_grading_standard']}, m) + register_uris({"course": ["get_single_grading_standard"]}, m) response = self.course.get_single_grading_standard(1) self.assertIsInstance(response, GradingStandard) - self.assertTrue(hasattr(response, 'id')) + self.assertTrue(hasattr(response, "id")) self.assertEqual(1, response.id) - self.assertTrue(hasattr(response, 'title')) + self.assertTrue(hasattr(response, "title")) self.assertEqual("Grading Standard 1", response.title) self.assertTrue(hasattr(response, "grading_scheme")) - self.assertEqual(response.grading_scheme[0].get('name'), "A") - self.assertEqual(response.grading_scheme[0].get('value'), 0.9) + self.assertEqual(response.grading_scheme[0].get("name"), "A") + self.assertEqual(response.grading_scheme[0].get("value"), 0.9) # create_content_migration def test_create_content_migration(self, m): - register_uris({'course': ['create_content_migration']}, m) + register_uris({"course": ["create_content_migration"]}, m) - content_migration = self.course.create_content_migration('dummy_importer') + content_migration = self.course.create_content_migration("dummy_importer") self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_migrator(self, m): register_uris( - {'course': ['create_content_migration', 'get_migration_systems_multiple']}, + {"course": ["create_content_migration", "get_migration_systems_multiple"]}, m, ) @@ -1421,26 +1421,26 @@ def test_create_content_migration_migrator(self, m): content_migration = self.course.create_content_migration(migrators[0]) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_bad_migration_type(self, m): - register_uris({'course': ['create_content_migration']}, m) + register_uris({"course": ["create_content_migration"]}, m) with self.assertRaises(TypeError): self.course.create_content_migration(1) # get_content_migration def test_get_content_migration(self, m): - register_uris({'course': ['get_content_migration_single']}, m) + register_uris({"course": ["get_content_migration_single"]}, m) content_migration = self.course.get_content_migration(1) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) # get_content_migrations def test_get_content_migrations(self, m): - register_uris({'course': ['get_content_migration_multiple']}, m) + register_uris({"course": ["get_content_migration_multiple"]}, m) content_migrations = self.course.get_content_migrations() @@ -1455,7 +1455,7 @@ def test_get_content_migrations(self, m): # get_migration_systems def test_get_migration_systems(self, m): - register_uris({'course': ['get_migration_systems_multiple']}, m) + register_uris({"course": ["get_migration_systems_multiple"]}, m) migration_systems = self.course.get_migration_systems() @@ -1472,10 +1472,10 @@ def test_get_migration_systems(self, m): # set_quiz_extensions def test_set_quiz_extensions(self, m): - register_uris({'course': ['set_quiz_extensions']}, m) + register_uris({"course": ["set_quiz_extensions"]}, m) extension = self.course.set_quiz_extensions( - [{'user_id': 1, 'extra_time': 60}, {'user_id': 2, 'extra_attempts': 3}] + [{"user_id": 1, "extra_time": 60}, {"user_id": 2, "extra_attempts": 3}] ) self.assertIsInstance(extension, list) @@ -1483,17 +1483,17 @@ def test_set_quiz_extensions(self, m): self.assertIsInstance(extension[0], QuizExtension) self.assertEqual(extension[0].user_id, "1") - self.assertTrue(hasattr(extension[0], 'extra_time')) + self.assertTrue(hasattr(extension[0], "extra_time")) self.assertEqual(extension[0].extra_time, 60) self.assertIsInstance(extension[1], QuizExtension) self.assertEqual(extension[1].user_id, "2") - self.assertTrue(hasattr(extension[1], 'extra_attempts')) + self.assertTrue(hasattr(extension[1], "extra_attempts")) self.assertEqual(extension[1].extra_attempts, 3) def test_set_extensions_not_list(self, m): with self.assertRaises(ValueError): - self.course.set_quiz_extensions({'user_id': 1, 'extra_time': 60}) + self.course.set_quiz_extensions({"user_id": 1, "extra_time": 60}) def test_set_extensions_empty_list(self, m): with self.assertRaises(ValueError): @@ -1501,18 +1501,18 @@ def test_set_extensions_empty_list(self, m): def test_set_extensions_non_dicts(self, m): with self.assertRaises(ValueError): - self.course.set_quiz_extensions([('user_id', 1), ('extra_time', 60)]) + self.course.set_quiz_extensions([("user_id", 1), ("extra_time", 60)]) def test_set_extensions_missing_key(self, m): with self.assertRaises(RequiredFieldMissing): - self.course.set_quiz_extensions([{'extra_time': 60, 'extra_attempts': 3}]) + self.course.set_quiz_extensions([{"extra_time": 60, "extra_attempts": 3}]) # submissions_bulk_update() def test_submissions_bulk_update(self, m): - register_uris({'course': ['update_submissions']}, m) - register_uris({'progress': ['course_progress']}, m) + register_uris({"course": ["update_submissions"]}, m) + register_uris({"progress": ["course_progress"]}, m) progress = self.course.submissions_bulk_update( - grade_data={'1': {'1': {'posted_grade': 97}, '2': {'posted_grade': 98}}} + grade_data={"1": {"1": {"posted_grade": 97}, "2": {"posted_grade": 98}}} ) self.assertIsInstance(progress, Progress) self.assertTrue(progress.context_type == "Course") @@ -1521,20 +1521,20 @@ def test_submissions_bulk_update(self, m): # get_blueprint() def test_get_blueprint(self, m): - register_uris({'course': ['get_blueprint']}, m) + register_uris({"course": ["get_blueprint"]}, m) blueprint = self.course.get_blueprint(1) self.assertIsInstance(blueprint, BlueprintTemplate) self.assertEqual(blueprint.course_id, 1) def test_get_blueprint_default(self, m): - register_uris({'course': ['get_blueprint_default']}, m) + register_uris({"course": ["get_blueprint_default"]}, m) blueprint_default = self.course.get_blueprint() self.assertIsInstance(blueprint_default, BlueprintTemplate) self.assertEqual(blueprint_default.course_id, 1) # list_blueprint_subscriptions() def test_list_blueprint_subscriptions(self, m): - register_uris({'course': ['list_blueprint_subscriptions']}, m) + register_uris({"course": ["list_blueprint_subscriptions"]}, m) blueprint_subscriptions = self.course.list_blueprint_subscriptions() self.assertIsInstance(blueprint_subscriptions, PaginatedList) self.assertIsInstance(blueprint_subscriptions[0], BlueprintSubscription) @@ -1613,7 +1613,7 @@ def test_import_outcome_ioerror(self, m): # get_epub_export def test_get_epub_export(self, m): - register_uris({'course': ['get_epub_export']}, m) + register_uris({"course": ["get_epub_export"]}, m) response = self.course.get_epub_export(1) @@ -1624,12 +1624,12 @@ def test_get_epub_export(self, m): self.assertTrue(hasattr(response, "epub_export")) epub1 = response.epub_export - self.assertEqual(epub1['id'], 1) - self.assertEqual(epub1['workflow_state'], "exported") + self.assertEqual(epub1["id"], 1) + self.assertEqual(epub1["workflow_state"], "exported") # create_epub_export def test_create_epub_export(self, m): - register_uris({'course': ['create_epub_export']}, m) + register_uris({"course": ["create_epub_export"]}, m) response = self.course.create_epub_export() @@ -1640,12 +1640,12 @@ def test_create_epub_export(self, m): self.assertTrue(hasattr(response, "epub_export")) epub1 = response.epub_export - self.assertEqual(epub1['id'], 1) - self.assertEqual(epub1['workflow_state'], "exported") + self.assertEqual(epub1["id"], 1) + self.assertEqual(epub1["workflow_state"], "exported") # list_grading_periods() def test_get_grading_periods(self, m): - register_uris({'course': ['get_grading_periods']}, m) + register_uris({"course": ["get_grading_periods"]}, m) response = self.course.get_grading_periods() @@ -1659,7 +1659,7 @@ def test_get_grading_periods(self, m): # get_grading_period() def test_get_grading_period(self, m): - register_uris({'course': ['get_grading_period']}, m) + register_uris({"course": ["get_grading_period"]}, m) grading_period_id = 1 response = self.course.get_grading_period(grading_period_id) @@ -1670,7 +1670,7 @@ def test_get_grading_period(self, m): # get_content_exports() def test_list_content_exports(self, m): - register_uris({'course': ['multiple_content_exports']}, m) + register_uris({"course": ["multiple_content_exports"]}, m) content_exports = self.course.get_content_exports() content_export_list = [content_export for content_export in content_exports] @@ -1682,21 +1682,21 @@ def test_list_content_exports(self, m): # get_content_export() def test_show_content_export(self, m): - register_uris({'course': ['single_content_export']}, m) + register_uris({"course": ["single_content_export"]}, m) content_export = self.course.get_content_export(11) - self.assertTrue(hasattr(content_export, 'export_type')) + self.assertTrue(hasattr(content_export, "export_type")) self.assertIsInstance(content_export, ContentExport) # export_content() def test_export_content(self, m): - register_uris({'course': ['export_content']}, m) + register_uris({"course": ["export_content"]}, m) - content_export = self.course.export_content('d') + content_export = self.course.export_content("d") self.assertIsInstance(content_export, ContentExport) - self.assertTrue(hasattr(content_export, 'export_type')) + self.assertTrue(hasattr(content_export, "export_type")) @requests_mock.Mocker() @@ -1705,7 +1705,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'user': ['course_nickname']}, m) + register_uris({"user": ["course_nickname"]}, m) self.nickname = self.canvas.get_course_nickname(1) # __str__() @@ -1715,9 +1715,9 @@ def test__str__(self, m): # remove() def test_remove(self, m): - register_uris({'user': ['remove_nickname']}, m) + register_uris({"user": ["remove_nickname"]}, m) deleted_nick = self.nickname.remove() self.assertIsInstance(deleted_nick, CourseNickname) - self.assertTrue(hasattr(deleted_nick, 'nickname')) + self.assertTrue(hasattr(deleted_nick, "nickname")) diff --git a/tests/test_current_user.py b/tests/test_current_user.py index 3bce7e40..09b1ef75 100644 --- a/tests/test_current_user.py +++ b/tests/test_current_user.py @@ -18,7 +18,7 @@ class TestCurrentUser(unittest.TestCase): def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'current_user': ['get_by_id']}, m) + register_uris({"current_user": ["get_by_id"]}, m) self.user = self.canvas.get_current_user() # __str__() @@ -28,7 +28,7 @@ def test__str__(self, m): # list_groups() def test_list_groups(self, m): - register_uris({'current_user': ['list_groups', 'list_groups2']}, m) + register_uris({"current_user": ["list_groups", "list_groups2"]}, m) with warnings.catch_warnings(record=True) as warning_list: groups = self.user.list_groups() @@ -42,7 +42,7 @@ def test_list_groups(self, m): # get_groups() def test_get_groups(self, m): - register_uris({'current_user': ['list_groups', 'list_groups2']}, m) + register_uris({"current_user": ["list_groups", "list_groups2"]}, m) groups = self.user.get_groups() group_list = [group for group in groups] @@ -52,7 +52,7 @@ def test_get_groups(self, m): # list_bookmarks() def test_list_bookmarks(self, m): - register_uris({'bookmark': ['list_bookmarks']}, m) + register_uris({"bookmark": ["list_bookmarks"]}, m) with warnings.catch_warnings(record=True) as warning_list: bookmarks = self.user.list_bookmarks() @@ -65,7 +65,7 @@ def test_list_bookmarks(self, m): # get_bookmarks() def test_get_bookmarks(self, m): - register_uris({'bookmark': ['list_bookmarks']}, m) + register_uris({"bookmark": ["list_bookmarks"]}, m) bookmarks = self.user.get_bookmarks() bookmark_list = [bookmark for bookmark in bookmarks] @@ -74,7 +74,7 @@ def test_get_bookmarks(self, m): # get_bookmark() def test_get_bookmark(self, m): - register_uris({'bookmark': ['get_bookmark']}, m) + register_uris({"bookmark": ["get_bookmark"]}, m) bookmark_by_id = self.user.get_bookmark(45) self.assertIsInstance(bookmark_by_id, Bookmark) @@ -85,7 +85,7 @@ def test_get_bookmark(self, m): # create_bookmark() def test_create_bookmark(self, m): - register_uris({'bookmark': ['create_bookmark']}, m) + register_uris({"bookmark": ["create_bookmark"]}, m) evnt = self.user.create_bookmark( name="Test Bookmark", url="https://www.google.com" ) @@ -95,7 +95,7 @@ def test_create_bookmark(self, m): # get_favorite_courses() def test_get_favorite_courses(self, m): - register_uris({'current_user': ['get_favorite_courses']}, m) + register_uris({"current_user": ["get_favorite_courses"]}, m) fav_courses = self.user.get_favorite_courses() fav_course_list = [course for course in fav_courses] @@ -109,7 +109,7 @@ def test_get_favorite_courses(self, m): # get_favorite_groups() def test_get_favorite_groups(self, m): - register_uris({'current_user': ['get_favorite_groups']}, m) + register_uris({"current_user": ["get_favorite_groups"]}, m) fav_groups = self.user.get_favorite_groups() fav_groups_list = [group for group in fav_groups] @@ -122,7 +122,7 @@ def test_get_favorite_groups(self, m): # add_favorite_course() def test_add_favorite_course(self, m): register_uris( - {'current_user': ['add_favorite_course'], 'course': ['get_by_id']}, m + {"current_user": ["add_favorite_course"], "course": ["get_by_id"]}, m ) fav_by_id = self.user.add_favorite_course(1) @@ -137,9 +137,9 @@ def test_add_favorite_course(self, m): self.assertEqual(fav_by_obj.context_id, 1) def test_add_favorite_course_sis_id(self, m): - register_uris({'current_user': ['add_favorite_course_by_sis_id']}, m) + register_uris({"current_user": ["add_favorite_course_by_sis_id"]}, m) - fav_by_sis = self.user.add_favorite_course('test-sis-id', use_sis_id=True) + fav_by_sis = self.user.add_favorite_course("test-sis-id", use_sis_id=True) self.assertIsInstance(fav_by_sis, Favorite) self.assertEqual(fav_by_sis.context_id, 1) @@ -148,7 +148,7 @@ def test_add_favorite_course_sis_id(self, m): # add_favorite_group() def test_add_favorite_group(self, m): register_uris( - {'current_user': ['add_favorite_group'], 'group': ['get_by_id']}, m + {"current_user": ["add_favorite_group"], "group": ["get_by_id"]}, m ) fav_by_id = self.user.add_favorite_group(1) @@ -163,9 +163,9 @@ def test_add_favorite_group(self, m): self.assertEqual(fav_by_obj.context_id, 1) def test_add_favorite_group_sis_id(self, m): - register_uris({'current_user': ['add_favorite_group_by_sis_id']}, m) + register_uris({"current_user": ["add_favorite_group_by_sis_id"]}, m) - fav_by_sis = self.user.add_favorite_group('test-sis-id', use_sis_id=True) + fav_by_sis = self.user.add_favorite_group("test-sis-id", use_sis_id=True) self.assertIsInstance(fav_by_sis, Favorite) self.assertEqual(fav_by_sis.context_id, 1) @@ -173,14 +173,14 @@ def test_add_favorite_group_sis_id(self, m): # reset_favorite_courses() def test_reset_favorite_courses(self, m): - register_uris({'current_user': ['reset_favorite_courses']}, m) + register_uris({"current_user": ["reset_favorite_courses"]}, m) response = self.user.reset_favorite_courses() self.assertTrue(response) # reset_favorite_groups() def test_reset_favorite_groups(self, m): - register_uris({'current_user': ['reset_favorite_groups']}, m) + register_uris({"current_user": ["reset_favorite_groups"]}, m) response = self.user.reset_favorite_groups() self.assertTrue(response) diff --git a/tests/test_discussion_topic.py b/tests/test_discussion_topic.py index b9031522..1c2a8196 100644 --- a/tests/test_discussion_topic.py +++ b/tests/test_discussion_topic.py @@ -20,8 +20,8 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_discussion_topic'], - 'group': ['get_by_id', 'get_discussion_topic'], + "course": ["get_by_id", "get_discussion_topic"], + "group": ["get_by_id", "get_discussion_topic"], } register_uris(requires, m) @@ -37,30 +37,30 @@ def test__str__(self, m): # delete() def test_delete(self, m): - register_uris({'discussion_topic': ['delete']}, m) + register_uris({"discussion_topic": ["delete"]}, m) response = self.discussion_topic.delete() self.assertTrue(response) # update() def test_update(self, m): - register_uris({'discussion_topic': ['update']}, m) + register_uris({"discussion_topic": ["update"]}, m) discussion = self.discussion_topic.update() self.assertIsInstance(discussion, DiscussionTopic) - self.assertTrue(hasattr(discussion, 'course_id')) + self.assertTrue(hasattr(discussion, "course_id")) self.assertEqual(discussion.course_id, 1) # post_entry() def test_post_entry(self, m): - register_uris({'discussion_topic': ['post_entry']}, m) + register_uris({"discussion_topic": ["post_entry"]}, m) entry = self.discussion_topic.post_entry() self.assertTrue(entry) # list_topic_entries() def test_list_topic_entries(self, m): - register_uris({'discussion_topic': ['list_topic_entries']}, m) + register_uris({"discussion_topic": ["list_topic_entries"]}, m) with warnings.catch_warnings(record=True) as warning_list: entries = self.discussion_topic.list_topic_entries() @@ -68,9 +68,9 @@ def test_list_topic_entries(self, m): self.assertEqual(len(entry_list), 2) self.assertIsInstance(entry_list[0], DiscussionEntry) - self.assertTrue(hasattr(entry_list[0], 'id')) + self.assertTrue(hasattr(entry_list[0], "id")) self.assertEqual(entry_list[0].id, 1) - self.assertTrue(hasattr(entry_list[0], 'user_id')) + self.assertTrue(hasattr(entry_list[0], "user_id")) self.assertEqual(entry_list[0].user_id, 1) self.assertEqual(len(warning_list), 1) @@ -78,21 +78,21 @@ def test_list_topic_entries(self, m): # get_topic_entries() def test_get_topic_entries(self, m): - register_uris({'discussion_topic': ['list_topic_entries']}, m) + register_uris({"discussion_topic": ["list_topic_entries"]}, m) entries = self.discussion_topic.get_topic_entries() entry_list = [entry for entry in entries] self.assertEqual(len(entry_list), 2) self.assertIsInstance(entry_list[0], DiscussionEntry) - self.assertTrue(hasattr(entry_list[0], 'id')) + self.assertTrue(hasattr(entry_list[0], "id")) self.assertEqual(entry_list[0].id, 1) - self.assertTrue(hasattr(entry_list[0], 'user_id')) + self.assertTrue(hasattr(entry_list[0], "user_id")) self.assertEqual(entry_list[0].user_id, 1) # list_entries() def test_list_entries(self, m): - register_uris({'discussion_topic': ['list_entries']}, m) + register_uris({"discussion_topic": ["list_entries"]}, m) with warnings.catch_warnings(record=True) as warning_list: entries_by_id = self.discussion_topic.list_entries([1, 2, 3]) @@ -101,10 +101,10 @@ def test_list_entries(self, m): entry_by_id = entry_list_by_id[-1] self.assertIsInstance(entry_by_id, DiscussionEntry) - self.assertTrue(hasattr(entry_by_id, 'id')) + self.assertTrue(hasattr(entry_by_id, "id")) self.assertEqual(entry_by_id.id, 3) - self.assertTrue(hasattr(entry_by_id, 'message')) - self.assertEqual(entry_by_id.message, 'Lower level entry') + self.assertTrue(hasattr(entry_by_id, "message")) + self.assertEqual(entry_by_id.message, "Lower level entry") self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -116,17 +116,17 @@ def test_list_entries(self, m): entry_by_obj = entry_list_by_obj[-1] self.assertIsInstance(entry_by_obj, DiscussionEntry) - self.assertTrue(hasattr(entry_by_obj, 'id')) + self.assertTrue(hasattr(entry_by_obj, "id")) self.assertEqual(entry_by_obj.id, 3) - self.assertTrue(hasattr(entry_by_obj, 'message')) - self.assertEqual(entry_by_obj.message, 'Lower level entry') + self.assertTrue(hasattr(entry_by_obj, "message")) + self.assertEqual(entry_by_obj.message, "Lower level entry") self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_entries() def test_get_entries(self, m): - register_uris({'discussion_topic': ['list_entries']}, m) + register_uris({"discussion_topic": ["list_entries"]}, m) entries_by_id = self.discussion_topic.get_entries([1, 2, 3]) entry_list_by_id = [entry for entry in entries_by_id] @@ -134,10 +134,10 @@ def test_get_entries(self, m): entry_by_id = entry_list_by_id[-1] self.assertIsInstance(entry_by_id, DiscussionEntry) - self.assertTrue(hasattr(entry_by_id, 'id')) + self.assertTrue(hasattr(entry_by_id, "id")) self.assertEqual(entry_by_id.id, 3) - self.assertTrue(hasattr(entry_by_id, 'message')) - self.assertEqual(entry_by_id.message, 'Lower level entry') + self.assertTrue(hasattr(entry_by_id, "message")) + self.assertEqual(entry_by_id.message, "Lower level entry") entries_by_obj = self.discussion_topic.get_entries(entries_by_id) entry_list_by_obj = [entry for entry in entries_by_obj] @@ -145,20 +145,20 @@ def test_get_entries(self, m): entry_by_obj = entry_list_by_obj[-1] self.assertIsInstance(entry_by_obj, DiscussionEntry) - self.assertTrue(hasattr(entry_by_obj, 'id')) + self.assertTrue(hasattr(entry_by_obj, "id")) self.assertEqual(entry_by_obj.id, 3) - self.assertTrue(hasattr(entry_by_obj, 'message')) - self.assertEqual(entry_by_obj.message, 'Lower level entry') + self.assertTrue(hasattr(entry_by_obj, "message")) + self.assertEqual(entry_by_obj.message, "Lower level entry") # mark_as_read() def test_mark_as_read(self, m): - register_uris({'discussion_topic': ['mark_as_read']}, m) + register_uris({"discussion_topic": ["mark_as_read"]}, m) topic = self.discussion_topic.mark_as_read() self.assertTrue(topic) def test_mark_as_read_403(self, m): - register_uris({'discussion_topic': ['mark_as_read_403']}, m) + register_uris({"discussion_topic": ["mark_as_read_403"]}, m) with self.assertRaises(Forbidden): topic = self.discussion_topic.mark_as_read() @@ -166,13 +166,13 @@ def test_mark_as_read_403(self, m): # mark_as_unread() def test_mark_as_unread(self, m): - register_uris({'discussion_topic': ['mark_as_unread']}, m) + register_uris({"discussion_topic": ["mark_as_unread"]}, m) topic = self.discussion_topic.mark_as_unread() self.assertTrue(topic) def test_mark_as_unread_403(self, m): - register_uris({'discussion_topic': ['mark_as_unread_403']}, m) + register_uris({"discussion_topic": ["mark_as_unread_403"]}, m) with self.assertRaises(Forbidden): topic = self.discussion_topic.mark_as_unread() @@ -180,13 +180,13 @@ def test_mark_as_unread_403(self, m): # mark_entries_as_read() def test_mark_entries_as_read(self, m): - register_uris({'discussion_topic': ['mark_entries_as_read']}, m) + register_uris({"discussion_topic": ["mark_entries_as_read"]}, m) entries = self.discussion_topic.mark_entries_as_read() self.assertTrue(entries) def test_mark_entries_as_read_403(self, m): - register_uris({'discussion_topic': ['mark_entries_as_read_403']}, m) + register_uris({"discussion_topic": ["mark_entries_as_read_403"]}, m) with self.assertRaises(Forbidden): entries = self.discussion_topic.mark_entries_as_read() @@ -194,13 +194,13 @@ def test_mark_entries_as_read_403(self, m): # mark_entries_as_unread() def test_mark_entries_as_unread(self, m): - register_uris({'discussion_topic': ['mark_entries_as_unread']}, m) + register_uris({"discussion_topic": ["mark_entries_as_unread"]}, m) entries = self.discussion_topic.mark_entries_as_unread() self.assertTrue(entries) def test_mark_entries_as_unread_403(self, m): - register_uris({'discussion_topic': ['mark_entries_as_unread_403']}, m) + register_uris({"discussion_topic": ["mark_entries_as_unread_403"]}, m) with self.assertRaises(Forbidden): entries = self.discussion_topic.mark_entries_as_unread() @@ -208,13 +208,13 @@ def test_mark_entries_as_unread_403(self, m): # subscribe() def test_subscribe(self, m): - register_uris({'discussion_topic': ['subscribe']}, m) + register_uris({"discussion_topic": ["subscribe"]}, m) subscribe = self.discussion_topic.subscribe() self.assertTrue(subscribe) def test_subscribe_403(self, m): - register_uris({'discussion_topic': ['subscribe_403']}, m) + register_uris({"discussion_topic": ["subscribe_403"]}, m) with self.assertRaises(Forbidden): subscribe = self.discussion_topic.subscribe() @@ -222,13 +222,13 @@ def test_subscribe_403(self, m): # unsubscribe() def test_unsubscribe(self, m): - register_uris({'discussion_topic': ['unsubscribe']}, m) + register_uris({"discussion_topic": ["unsubscribe"]}, m) unsubscribe = self.discussion_topic.unsubscribe() self.assertTrue(unsubscribe) def test_unsubscribe_403(self, m): - register_uris({'discussion_topic': ['unsubscribe_403']}, m) + register_uris({"discussion_topic": ["unsubscribe_403"]}, m) with self.assertRaises(Forbidden): unsubscribe = self.discussion_topic.unsubscribe() @@ -242,30 +242,30 @@ def test_parent_id_group(self, m): self.assertEqual(self.discussion_topic_group._parent_id, 1) def test_parent_id_no_id(self, m): - discussion = DiscussionTopic(self.canvas._Canvas__requester, {'id': 1}) + discussion = DiscussionTopic(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): discussion._parent_id # _parent_type def test_parent_type_course(self, m): - self.assertEqual(self.discussion_topic._parent_type, 'course') + self.assertEqual(self.discussion_topic._parent_type, "course") def test_parent_type_group(self, m): - self.assertEqual(self.discussion_topic_group._parent_type, 'group') + self.assertEqual(self.discussion_topic_group._parent_type, "group") def test_parent_type_no_id(self, m): - discussion = DiscussionTopic(self.canvas._Canvas__requester, {'id': 1}) + discussion = DiscussionTopic(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): discussion._parent_type # get_parent() def test_get_parent_course(self, m): - register_uris({'course': ['get_by_id']}, m) + register_uris({"course": ["get_by_id"]}, m) self.assertIsInstance(self.discussion_topic.get_parent(), Course) def test_get_parent_group(self, m): - register_uris({'group': ['get_by_id']}, m) + register_uris({"group": ["get_by_id"]}, m) self.assertIsInstance(self.discussion_topic_group.get_parent(), Group) @@ -277,12 +277,12 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_discussion_topic'], - 'discussion_topic': [ - 'list_entries_single', - 'list_entries_single_group', + "course": ["get_by_id", "get_discussion_topic"], + "discussion_topic": [ + "list_entries_single", + "list_entries_single_group", ], - 'group': ['get_by_id', 'get_discussion_topic'], + "group": ["get_by_id", "get_discussion_topic"], } register_uris(requires, m) @@ -308,54 +308,54 @@ def test_discussion_parent_id_group(self, m): self.assertEqual(self.discussion_entry_group._discussion_parent_id, 1) def test_discussion_parent_id_no_id(self, m): - discussion = DiscussionEntry(self.canvas._Canvas__requester, {'id': 1}) + discussion = DiscussionEntry(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): discussion._discussion_parent_id # _discussion_parent_type def test_discussion_parent_type_course(self, m): - self.assertEqual(self.discussion_entry._discussion_parent_type, 'course') + self.assertEqual(self.discussion_entry._discussion_parent_type, "course") def test_discussion_parent_type_group(self, m): - self.assertEqual(self.discussion_entry_group._discussion_parent_type, 'group') + self.assertEqual(self.discussion_entry_group._discussion_parent_type, "group") def test_discussion_parent_type_no_id(self, m): - discussion = DiscussionEntry(self.canvas._Canvas__requester, {'id': 1}) + discussion = DiscussionEntry(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): discussion._discussion_parent_type # get_discussion() def test_get_discussion(self, m): - register_uris({'course': ['get_discussion_topic']}, m) + register_uris({"course": ["get_discussion_topic"]}, m) discussion = self.discussion_entry.get_discussion() self.assertIsInstance(discussion, DiscussionTopic) - self.assertTrue(hasattr(discussion, 'id')) + self.assertTrue(hasattr(discussion, "id")) self.assertEqual(self.discussion_topic.id, discussion.id) - self.assertTrue(hasattr(discussion, 'title')) + self.assertTrue(hasattr(discussion, "title")) self.assertEqual(self.discussion_topic.title, discussion.title) # delete() def test_delete(self, m): - register_uris({'discussion_topic': ['delete_entry']}, m) + register_uris({"discussion_topic": ["delete_entry"]}, m) response = self.discussion_entry.delete() self.assertTrue(response) # post_reply() def test_post_reply(self, m): - register_uris({'discussion_topic': ['post_reply']}, m) + register_uris({"discussion_topic": ["post_reply"]}, m) message = "Reply message 1" reply = self.discussion_entry.post_reply(message=message) self.assertIsInstance(reply, DiscussionEntry) - self.assertTrue(hasattr(reply, 'message')) + self.assertTrue(hasattr(reply, "message")) self.assertEqual(reply.message, message) - self.assertTrue(hasattr(reply, 'created_at')) + self.assertTrue(hasattr(reply, "created_at")) # list_replies() def test_list_replies(self, m): - register_uris({'discussion_topic': ['list_entry_replies']}, m) + register_uris({"discussion_topic": ["list_entry_replies"]}, m) with warnings.catch_warnings(record=True) as warning_list: replies = self.discussion_entry.list_replies() @@ -364,17 +364,17 @@ def test_list_replies(self, m): reply = reply_list[0] self.assertIsInstance(reply, DiscussionEntry) - self.assertTrue(hasattr(reply, 'id')) + self.assertTrue(hasattr(reply, "id")) self.assertEqual(reply.id, 5) - self.assertTrue(hasattr(reply, 'message')) - self.assertEqual(reply.message, 'Reply message 1') + self.assertTrue(hasattr(reply, "message")) + self.assertEqual(reply.message, "Reply message 1") self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_replies() def test_get_replies(self, m): - register_uris({'discussion_topic': ['list_entry_replies']}, m) + register_uris({"discussion_topic": ["list_entry_replies"]}, m) replies = self.discussion_entry.get_replies() reply_list = [reply for reply in replies] @@ -382,33 +382,33 @@ def test_get_replies(self, m): reply = reply_list[0] self.assertIsInstance(reply, DiscussionEntry) - self.assertTrue(hasattr(reply, 'id')) + self.assertTrue(hasattr(reply, "id")) self.assertEqual(reply.id, 5) - self.assertTrue(hasattr(reply, 'message')) - self.assertEqual(reply.message, 'Reply message 1') + self.assertTrue(hasattr(reply, "message")) + self.assertEqual(reply.message, "Reply message 1") # mark_as_read() def test_mark_as_read(self, m): - register_uris({'discussion_topic': ['mark_entry_as_read']}, m) + register_uris({"discussion_topic": ["mark_entry_as_read"]}, m) response = self.discussion_entry.mark_as_read() self.assertTrue(response) def test_mark_as_read_403(self, m): - register_uris({'discussion_topic': ['mark_entry_as_read_403']}, m) + register_uris({"discussion_topic": ["mark_entry_as_read_403"]}, m) with self.assertRaises(Forbidden): self.discussion_entry.mark_as_read() # mark_as_unread() def test_mark_as_unread(self, m): - register_uris({'discussion_topic': ['mark_entry_as_unread']}, m) + register_uris({"discussion_topic": ["mark_entry_as_unread"]}, m) response = self.discussion_entry.mark_as_unread() self.assertTrue(response) def test_mark_as_unread_403(self, m): - register_uris({'discussion_topic': ['mark_entry_as_unread_403']}, m) + register_uris({"discussion_topic": ["mark_entry_as_unread_403"]}, m) with self.assertRaises(Forbidden): response = self.discussion_entry.mark_as_unread() @@ -416,11 +416,11 @@ def test_mark_as_unread_403(self, m): # update() def test_update(self, m): - register_uris({'discussion_topic': ['update_entry']}, m) + register_uris({"discussion_topic": ["update_entry"]}, m) - self.assertEqual(self.discussion_entry.message, 'Top Level Entry') + self.assertEqual(self.discussion_entry.message, "Top Level Entry") - new_message = 'Top Level Entry [Updated]' + new_message = "Top Level Entry [Updated]" response = self.discussion_entry.update(message=new_message) self.assertTrue(response) @@ -429,7 +429,7 @@ def test_update(self, m): # rate() def test_rate(self, m): - register_uris({'discussion_topic': ['rate_entry']}, m) + register_uris({"discussion_topic": ["rate_entry"]}, m) response = self.discussion_entry.rate(1) self.assertTrue(response) diff --git a/tests/test_enrollment.py b/tests/test_enrollment.py index 456deb52..231cf021 100644 --- a/tests/test_enrollment.py +++ b/tests/test_enrollment.py @@ -15,7 +15,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = {'account': ['get_by_id'], 'enrollment': ['get_by_id']} + requires = {"account": ["get_by_id"], "enrollment": ["get_by_id"]} register_uris(requires, m) self.account = self.canvas.get_account(1) @@ -28,19 +28,19 @@ def test__str__(self, m): # deactivate() def test_deactivate(self, m): - register_uris({'enrollment': ['deactivate']}, m) + register_uris({"enrollment": ["deactivate"]}, m) - target_enrollment = self.enrollment.deactivate('conclude') + target_enrollment = self.enrollment.deactivate("conclude") self.assertIsInstance(target_enrollment, Enrollment) def test_deactivate_invalid_task(self, m): with self.assertRaises(ValueError): - self.enrollment.deactivate('finish') + self.enrollment.deactivate("finish") # reactivate() def test_reactivate(self, m): - register_uris({'enrollment': ['reactivate']}, m) + register_uris({"enrollment": ["reactivate"]}, m) target_enrollment = self.enrollment.reactivate() diff --git a/tests/test_enrollment_term.py b/tests/test_enrollment_term.py index 71f6f572..f4c0ef0d 100644 --- a/tests/test_enrollment_term.py +++ b/tests/test_enrollment_term.py @@ -15,7 +15,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'account': ['get_by_id', 'create_enrollment_term']}, m) + register_uris({"account": ["get_by_id", "create_enrollment_term"]}, m) self.account = self.canvas.get_account(1) self.enrollment_term = self.account.create_enrollment_term( @@ -24,25 +24,25 @@ def setUp(self): # delete() def test_delete_enrollment_term(self, m): - register_uris({'enrollment_term': ['delete_enrollment_term']}, m) + register_uris({"enrollment_term": ["delete_enrollment_term"]}, m) deleted_enrollment_term = self.enrollment_term.delete() self.assertIsInstance(deleted_enrollment_term, EnrollmentTerm) - self.assertTrue(hasattr(deleted_enrollment_term, 'name')) - self.assertEqual(deleted_enrollment_term.name, 'Test Enrollment Term') + self.assertTrue(hasattr(deleted_enrollment_term, "name")) + self.assertEqual(deleted_enrollment_term.name, "Test Enrollment Term") # edit() def test_edit_enrollment_term(self, m): - register_uris({'enrollment_term': ['edit_enrollment_term']}, m) + register_uris({"enrollment_term": ["edit_enrollment_term"]}, m) - name = 'New Name' + name = "New Name" edited_enrollment_term = self.enrollment_term.edit( enrollment_term={"name": name} ) self.assertIsInstance(edited_enrollment_term, EnrollmentTerm) - self.assertTrue(hasattr(edited_enrollment_term, 'name')) + self.assertTrue(hasattr(edited_enrollment_term, "name")) self.assertEqual(edited_enrollment_term.name, name) # __str__() diff --git a/tests/test_external_feed.py b/tests/test_external_feed.py index df815c49..c14fb019 100644 --- a/tests/test_external_feed.py +++ b/tests/test_external_feed.py @@ -14,7 +14,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'list_external_feeds']}, m) + register_uris({"course": ["get_by_id", "list_external_feeds"]}, m) self.course = self.canvas.get_course(1) self.external_feed = self.course.get_external_feeds()[0] diff --git a/tests/test_external_tool.py b/tests/test_external_tool.py index a6963972..309bb15f 100644 --- a/tests/test_external_tool.py +++ b/tests/test_external_tool.py @@ -20,9 +20,9 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'account': ['get_by_id'], - 'course': ['get_by_id'], - 'external_tool': ['get_by_id_account', 'get_by_id_course'], + "account": ["get_by_id"], + "course": ["get_by_id"], + "external_tool": ["get_by_id_account", "get_by_id_course"], } register_uris(requires, m) @@ -44,42 +44,42 @@ def test_parent_id_course(self, m): self.assertEqual(self.ext_tool_course.parent_id, 1) def test_parent_id_no_id(self, m): - tool = ExternalTool(self.canvas._Canvas__requester, {'id': 1}) + tool = ExternalTool(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): tool.parent_id # parent_type def test_parent_type_account(self, m): - self.assertEqual(self.ext_tool_account.parent_type, 'account') + self.assertEqual(self.ext_tool_account.parent_type, "account") def test_parent_type_course(self, m): - self.assertEqual(self.ext_tool_course.parent_type, 'course') + self.assertEqual(self.ext_tool_course.parent_type, "course") def test_parent_type_no_id(self, m): - tool = ExternalTool(self.canvas._Canvas__requester, {'id': 1}) + tool = ExternalTool(self.canvas._Canvas__requester, {"id": 1}) with self.assertRaises(ValueError): tool.parent_type # get_parent() def test_get_parent_account(self, m): - register_uris({'account': ['get_by_id']}, m) + register_uris({"account": ["get_by_id"]}, m) self.assertIsInstance(self.ext_tool_account.get_parent(), Account) def test_get_parent_course(self, m): - register_uris({'course': ['get_by_id']}, m) + register_uris({"course": ["get_by_id"]}, m) self.assertIsInstance(self.ext_tool_course.get_parent(), Course) # delete() def test_delete(self, m): - register_uris({'external_tool': ['delete_tool_course']}, m) + register_uris({"external_tool": ["delete_tool_course"]}, m) deleted_tool = self.ext_tool_course.delete() self.assertIsInstance(deleted_tool, ExternalTool) - self.assertTrue(hasattr(deleted_tool, 'name')) + self.assertTrue(hasattr(deleted_tool, "name")) # edit() def test_edit(self, m): - register_uris({'external_tool': ['edit_tool_course']}, m) + register_uris({"external_tool": ["edit_tool_course"]}, m) new_name = "New Tool Name" edited_tool = self.ext_tool_course.edit(name=new_name) @@ -90,7 +90,7 @@ def test_edit(self, m): # get_sessionless_launch_url() def test_get_sessionless_launch_url(self, m): - requires = {'external_tool': ['get_sessionless_launch_url_course']} + requires = {"external_tool": ["get_sessionless_launch_url_course"]} register_uris(requires, m) self.assertIsInstance( @@ -99,8 +99,8 @@ def test_get_sessionless_launch_url(self, m): def test_get_sessionless_launch_url_no_url(self, m): requires = { - 'course': ['get_by_id_2'], - 'external_tool': ['get_by_id_course_2', 'sessionless_launch_no_url'], + "course": ["get_by_id_2"], + "external_tool": ["get_by_id_course_2", "sessionless_launch_no_url"], } register_uris(requires, m) diff --git a/tests/test_favorite.py b/tests/test_favorite.py index 3b5adb7e..71e05440 100644 --- a/tests/test_favorite.py +++ b/tests/test_favorite.py @@ -16,10 +16,10 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'current_user': [ - 'add_favorite_course', - 'add_favorite_group', - 'get_by_id', + "current_user": [ + "add_favorite_course", + "add_favorite_group", + "get_by_id", ] } register_uris(requires, m) @@ -38,7 +38,7 @@ def test__str__(self, m): # remove() def test_remove_favorite_course(self, m): - register_uris({'current_user': ['remove_favorite_course']}, m) + register_uris({"current_user": ["remove_favorite_course"]}, m) evnt = self.favorite_course.remove() self.assertIsInstance(evnt, Favorite) @@ -46,7 +46,7 @@ def test_remove_favorite_course(self, m): self.assertEqual(evnt.context_id, 1) def test_remove_favorite_group(self, m): - register_uris({'current_user': ['remove_favorite_group']}, m) + register_uris({"current_user": ["remove_favorite_group"]}, m) evnt = self.favorite_group.remove() self.assertIsInstance(evnt, Favorite) diff --git a/tests/test_file.py b/tests/test_file.py index a5bd48d8..a5b32d85 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -18,7 +18,7 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( - {'course': ['get_by_id', 'list_course_files', 'list_course_files2']}, m + {"course": ["get_by_id", "list_course_files", "list_course_files2"]}, m ) self.course = self.canvas.get_course(1) @@ -31,27 +31,27 @@ def test__str__(self, m): # delete() def test_delete_file(self, m): - register_uris({'file': ['delete_file']}, m) + register_uris({"file": ["delete_file"]}, m) deleted_file = self.file.delete() self.assertIsInstance(deleted_file, File) - self.assertTrue(hasattr(deleted_file, 'display_name')) + self.assertTrue(hasattr(deleted_file, "display_name")) self.assertEqual(deleted_file.display_name, "Bad File.docx") # download() def test_download_file(self, m): - register_uris({'file': ['file_download']}, m) + register_uris({"file": ["file_download"]}, m) try: - self.file.download('canvasapi_file_download_test.txt') - self.assertTrue(isfile('canvasapi_file_download_test.txt')) - with open('canvasapi_file_download_test.txt') as downloaded_file: + self.file.download("canvasapi_file_download_test.txt") + self.assertTrue(isfile("canvasapi_file_download_test.txt")) + with open("canvasapi_file_download_test.txt") as downloaded_file: self.assertEqual(downloaded_file.read(), '"file contents are here"') finally: - cleanup_file('canvasapi_file_download_test.txt') + cleanup_file("canvasapi_file_download_test.txt") # contents() def test_contents_file(self, m): - register_uris({'file': ['file_contents']}, m) + register_uris({"file": ["file_contents"]}, m) contents = self.file.get_contents() self.assertEqual(contents, '"Hello there"') diff --git a/tests/test_folder.py b/tests/test_folder.py index e6ab2754..c750dc36 100644 --- a/tests/test_folder.py +++ b/tests/test_folder.py @@ -18,7 +18,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'folder': ['get_by_id']}, m) + register_uris({"folder": ["get_by_id"]}, m) self.folder = self.canvas.get_folder(1) @@ -29,7 +29,7 @@ def test__str__(self, m): # list_files() def test_list_files(self, m): - register_uris({'folder': ['list_folder_files', 'list_folder_files2']}, m) + register_uris({"folder": ["list_folder_files", "list_folder_files2"]}, m) with warnings.catch_warnings(record=True) as warning_list: files = self.folder.list_files() @@ -42,7 +42,7 @@ def test_list_files(self, m): # get_files() def test_get_files(self, m): - register_uris({'folder': ['list_folder_files', 'list_folder_files2']}, m) + register_uris({"folder": ["list_folder_files", "list_folder_files2"]}, m) files = self.folder.get_files() file_list = [file for file in files] @@ -51,17 +51,17 @@ def test_get_files(self, m): # delete() def test_delete_file(self, m): - register_uris({'folder': ['delete_folder']}, m) + register_uris({"folder": ["delete_folder"]}, m) deleted_folder = self.folder.delete() self.assertIsInstance(deleted_folder, Folder) - self.assertTrue(hasattr(deleted_folder, 'name')) + self.assertTrue(hasattr(deleted_folder, "name")) self.assertEqual(deleted_folder.full_name, "course_files/Folder 1") # list_folders() def test_list_folders(self, m): - register_uris({'folder': ['list_folders']}, m) + register_uris({"folder": ["list_folders"]}, m) with warnings.catch_warnings(record=True) as warning_list: folders = self.folder.list_folders() @@ -74,7 +74,7 @@ def test_list_folders(self, m): # get_folders() def test_get_folders(self, m): - register_uris({'folder': ['list_folders']}, m) + register_uris({"folder": ["list_folders"]}, m) folders = self.folder.get_folders() folder_list = [folder for folder in folders] @@ -83,7 +83,7 @@ def test_get_folders(self, m): # create_folder() def test_create_folder(self, m): - register_uris({'folder': ['create_folder']}, m) + register_uris({"folder": ["create_folder"]}, m) name_str = "Test String" response = self.folder.create_folder(name=name_str) @@ -91,33 +91,33 @@ def test_create_folder(self, m): # upload() def test_upload(self, m): - register_uris({'folder': ['upload', 'upload_final']}, m) + register_uris({"folder": ["upload", "upload_final"]}, m) - filename = 'testfile_course_{}'.format(uuid.uuid4().hex) + filename = "testfile_course_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.folder.upload(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) # update() def test_update(self, m): - register_uris({'folder': ['update']}, m) + register_uris({"folder": ["update"]}, m) - new_name = 'New Name' + new_name = "New Name" response = self.folder.update(name=new_name) self.assertIsInstance(response, Folder) self.assertEqual(self.folder.name, new_name) # copy_file() def test_copy_file(self, m): - register_uris({'folder': ['copy_file']}, m) + register_uris({"folder": ["copy_file"]}, m) new_file = self.folder.copy_file(1) self.assertIsInstance(new_file, File) - self.assertEqual(new_file.display_name, 'Dummy File-1') + self.assertEqual(new_file.display_name, "Dummy File-1") self.assertEqual(new_file.id, 1) diff --git a/tests/test_grading_period.py b/tests/test_grading_period.py index 76e1b126..baffcc7a 100644 --- a/tests/test_grading_period.py +++ b/tests/test_grading_period.py @@ -27,58 +27,58 @@ def test_str(self, m): # update() def test_update(self, m): - register_uris({'grading_period': ['update']}, m) + register_uris({"grading_period": ["update"]}, m) edited_grading_period = self.grading_period.update( grading_period=[ { - 'start_date': '2019-06-10T06:00:00Z', - 'end_date': '2019-06-15T06:00:00Z', + "start_date": "2019-06-10T06:00:00Z", + "end_date": "2019-06-15T06:00:00Z", } ] ) self.assertIsInstance(edited_grading_period, GradingPeriod) - self.assertTrue(hasattr(edited_grading_period, 'title')) - self.assertTrue(hasattr(edited_grading_period, 'course_id')) - self.assertEqual(edited_grading_period.title, 'Grading period 1') + self.assertTrue(hasattr(edited_grading_period, "title")) + self.assertTrue(hasattr(edited_grading_period, "course_id")) + self.assertEqual(edited_grading_period.title, "Grading period 1") self.assertEqual(edited_grading_period.course_id, 1) - self.assertTrue(hasattr(edited_grading_period, 'start_date')) - self.assertTrue(hasattr(edited_grading_period, 'end_date')) - self.assertEqual(edited_grading_period.start_date, '2019-05-23T06:00:00Z') - self.assertEqual(edited_grading_period.end_date, '2019-08-23T06:00:00Z') + self.assertTrue(hasattr(edited_grading_period, "start_date")) + self.assertTrue(hasattr(edited_grading_period, "end_date")) + self.assertEqual(edited_grading_period.start_date, "2019-05-23T06:00:00Z") + self.assertEqual(edited_grading_period.end_date, "2019-08-23T06:00:00Z") # Check that the appropriate exception is raised when no list is given. def test_update_without_list(self, m): - register_uris({'grading_period': ['update']}, m) + register_uris({"grading_period": ["update"]}, m) with self.assertRaises(RequiredFieldMissing): self.grading_period.update( grading_period={ - 'start_date': '2019-06-10T06:00:00Z', - 'end_date': '2019-06-15T06:00:00Z', + "start_date": "2019-06-10T06:00:00Z", + "end_date": "2019-06-15T06:00:00Z", } ) # Check that the grading_period that is passed has a start date def test_update_without_start_date(self, m): - register_uris({'grading_period': ['update']}, m) + register_uris({"grading_period": ["update"]}, m) with self.assertRaises(RequiredFieldMissing): self.grading_period.update( - grading_period=[{'end_date': '2019-06-15T06:00:00Z'}] + grading_period=[{"end_date": "2019-06-15T06:00:00Z"}] ) # Check that the appropriate exception is raised when no list is given. def test_update_without_end_date(self, m): - register_uris({'grading_period': ['update']}, m) + register_uris({"grading_period": ["update"]}, m) with self.assertRaises(RequiredFieldMissing): self.grading_period.update( - grading_period=[{'start_date': '2019-06-10T06:00:00Z'}] + grading_period=[{"start_date": "2019-06-10T06:00:00Z"}] ) # delete() def test_delete(self, m): - register_uris({'grading_period': ['delete']}, m) + register_uris({"grading_period": ["delete"]}, m) self.assertEqual(self.grading_period.delete(), 204) diff --git a/tests/test_grading_standard.py b/tests/test_grading_standard.py index 3d7f5d26..32fe02df 100644 --- a/tests/test_grading_standard.py +++ b/tests/test_grading_standard.py @@ -14,7 +14,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'get_single_grading_standard']}, m) + register_uris({"course": ["get_by_id", "get_single_grading_standard"]}, m) self.course = self.canvas.get_course(1) self.grading_standard = self.course.get_single_grading_standard(1) diff --git a/tests/test_group.py b/tests/test_group.py index c59fea84..672c6147 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -29,7 +29,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id'], 'group': ['get_by_id']}, m) + register_uris({"course": ["get_by_id"], "group": ["get_by_id"]}, m) self.course = self.canvas.get_course(1) self.group = self.canvas.get_group(1) @@ -41,43 +41,43 @@ def test__str__(self, m): # show_front_page() def test_show_front_page(self, m): - register_uris({'group': ['show_front_page']}, m) + register_uris({"group": ["show_front_page"]}, m) front_page = self.group.show_front_page() self.assertIsInstance(front_page, Page) - self.assertTrue(hasattr(front_page, 'url')) - self.assertTrue(hasattr(front_page, 'title')) + self.assertTrue(hasattr(front_page, "url")) + self.assertTrue(hasattr(front_page, "title")) # create_front_page() def test_edit_front_page(self, m): - register_uris({'group': ['edit_front_page']}, m) + register_uris({"group": ["edit_front_page"]}, m) new_front_page = self.group.edit_front_page() self.assertIsInstance(new_front_page, Page) - self.assertTrue(hasattr(new_front_page, 'url')) - self.assertTrue(hasattr(new_front_page, 'title')) + self.assertTrue(hasattr(new_front_page, "url")) + self.assertTrue(hasattr(new_front_page, "title")) # get_pages() def test_get_pages(self, m): - register_uris({'group': ['get_pages', 'get_pages2']}, m) + register_uris({"group": ["get_pages", "get_pages2"]}, m) pages = self.group.get_pages() page_list = [page for page in pages] self.assertEqual(len(page_list), 4) self.assertIsInstance(page_list[0], Page) - self.assertTrue(hasattr(page_list[0], 'id')) + self.assertTrue(hasattr(page_list[0], "id")) self.assertEqual(page_list[0].group_id, self.group.id) # create_page() def test_create_page(self, m): - register_uris({'group': ['create_page']}, m) + register_uris({"group": ["create_page"]}, m) - title = 'New Page' - new_page = self.group.create_page(wiki_page={'title': title}) + title = "New Page" + new_page = self.group.create_page(wiki_page={"title": title}) self.assertIsInstance(new_page, Page) - self.assertTrue(hasattr(new_page, 'title')) + self.assertTrue(hasattr(new_page, "title")) self.assertEqual(new_page.title, title) - self.assertTrue(hasattr(new_page, 'id')) + self.assertTrue(hasattr(new_page, "id")) self.assertEqual(new_page.group_id, self.group.id) def test_create_page_fail(self, m): @@ -86,34 +86,34 @@ def test_create_page_fail(self, m): # get_page() def test_get_page(self, m): - register_uris({'group': ['get_page']}, m) + register_uris({"group": ["get_page"]}, m) - url = 'my-url' + url = "my-url" page = self.group.get_page(url) self.assertIsInstance(page, Page) # edit() def test_edit(self, m): - register_uris({'group': ['edit']}, m) + register_uris({"group": ["edit"]}, m) new_title = "New Group" response = self.group.edit(description=new_title) self.assertIsInstance(response, Group) - self.assertTrue(hasattr(response, 'description')) + self.assertTrue(hasattr(response, "description")) self.assertEqual(response.description, new_title) # delete() def test_delete(self, m): - register_uris({'group': ['delete']}, m) + register_uris({"group": ["delete"]}, m) group = self.group.delete() self.assertIsInstance(group, Group) - self.assertTrue(hasattr(group, 'name')) - self.assertTrue(hasattr(group, 'description')) + self.assertTrue(hasattr(group, "name")) + self.assertTrue(hasattr(group, "description")) # invite() def test_invite(self, m): - register_uris({'group': ['invite']}, m) + register_uris({"group": ["invite"]}, m) user_list = ["1", "2"] response = self.group.invite(user_list) @@ -123,7 +123,7 @@ def test_invite(self, m): # list_users() def test_list_users(self, m): - register_uris({'group': ['list_users', 'list_users_p2']}, m) + register_uris({"group": ["list_users", "list_users_p2"]}, m) with warnings.catch_warnings(record=True) as warning_list: from canvasapi.user import User @@ -138,7 +138,7 @@ def test_list_users(self, m): # get_users() def test_get_users(self, m): - register_uris({'group': ['list_users', 'list_users_p2']}, m) + register_uris({"group": ["list_users", "list_users_p2"]}, m) from canvasapi.user import User @@ -149,7 +149,7 @@ def test_get_users(self, m): # remove_user() def test_remove_user(self, m): - register_uris({'group': ['list_users', 'list_users_p2', 'remove_user']}, m) + register_uris({"group": ["list_users", "list_users_p2", "remove_user"]}, m) from canvasapi.user import User @@ -162,21 +162,21 @@ def test_remove_user(self, m): # upload() def test_upload(self, m): - register_uris({'group': ['upload', 'upload_final']}, m) + register_uris({"group": ["upload", "upload_final"]}, m) - filename = 'testfile_group_{}'.format(uuid.uuid4().hex) + filename = "testfile_group_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.group.upload(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) # preview_processed_html() def test_preview_processed_html(self, m): - register_uris({'group': ['preview_processed_html']}, m) + register_uris({"group": ["preview_processed_html"]}, m) html_str = "

processed html

" response = self.group.preview_html(html_str) @@ -184,39 +184,39 @@ def test_preview_processed_html(self, m): # get_activity_stream_summary() def test_get_activity_stream_summary(self, m): - register_uris({'group': ['activity_stream_summary']}, m) + register_uris({"group": ["activity_stream_summary"]}, m) response = self.group.get_activity_stream_summary() self.assertEqual(len(response), 2) - self.assertIn('type', response[0]) + self.assertIn("type", response[0]) # list_memberships() def test_list_memberships(self, m): - register_uris({'group': ['list_memberships', 'list_memberships_p2']}, m) + register_uris({"group": ["list_memberships", "list_memberships_p2"]}, m) with warnings.catch_warnings(record=True) as warning_list: response = self.group.list_memberships() membership_list = [membership for membership in response] self.assertEqual(len(membership_list), 4) self.assertIsInstance(membership_list[0], GroupMembership) - self.assertTrue(hasattr(membership_list[0], 'id')) + self.assertTrue(hasattr(membership_list[0], "id")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_memberships() def test_get_memberships(self, m): - register_uris({'group': ['list_memberships', 'list_memberships_p2']}, m) + register_uris({"group": ["list_memberships", "list_memberships_p2"]}, m) response = self.group.get_memberships() membership_list = [membership for membership in response] self.assertEqual(len(membership_list), 4) self.assertIsInstance(membership_list[0], GroupMembership) - self.assertTrue(hasattr(membership_list[0], 'id')) + self.assertTrue(hasattr(membership_list[0], "id")) # get_membership() def test_get_membership(self, m): - register_uris({'group': ['get_membership', 'list_users', 'list_users_p2']}, m) + register_uris({"group": ["get_membership", "list_users", "list_users_p2"]}, m) membership_by_id = self.group.get_membership(1, "users") self.assertIsInstance(membership_by_id, GroupMembership) @@ -228,7 +228,7 @@ def test_get_membership(self, m): # create_membership() def test_create_membership(self, m): register_uris( - {'group': ['create_membership', 'list_users', 'list_users_p2']}, m + {"group": ["create_membership", "list_users", "list_users_p2"]}, m ) response = self.group.create_membership(1) @@ -241,7 +241,7 @@ def test_create_membership(self, m): # update_membership() def test_update_membership(self, m): register_uris( - {'group': ['list_users', 'list_users_p2', 'update_membership_user']}, m + {"group": ["list_users", "list_users_p2", "update_membership_user"]}, m ) updated_membership_by_id = self.group.update_membership(1) @@ -253,74 +253,74 @@ def test_update_membership(self, m): # get_discussion_topic() def test_get_discussion_topic(self, m): - register_uris({'group': ['get_discussion_topic', 'get_discussion_topics']}, m) + register_uris({"group": ["get_discussion_topic", "get_discussion_topics"]}, m) group_id = 1 discussion_by_id = self.group.get_discussion_topic(group_id) self.assertIsInstance(discussion_by_id, DiscussionTopic) - self.assertTrue(hasattr(discussion_by_id, 'group_id')) + self.assertTrue(hasattr(discussion_by_id, "group_id")) self.assertEqual(group_id, discussion_by_id.id) self.assertEqual(discussion_by_id.group_id, 1) discussion_topic = self.group.get_discussion_topics()[0] discussion_by_obj = self.group.get_discussion_topic(discussion_topic) self.assertIsInstance(discussion_by_obj, DiscussionTopic) - self.assertTrue(hasattr(discussion_by_obj, 'group_id')) + self.assertTrue(hasattr(discussion_by_obj, "group_id")) self.assertEqual(group_id, discussion_by_obj.id) self.assertEqual(discussion_by_obj.group_id, 1) # get_file() def test_get_file(self, m): - register_uris({'group': ['get_file']}, m) + register_uris({"group": ["get_file"]}, m) file_by_id = self.group.get_file(1) self.assertIsInstance(file_by_id, File) - self.assertEqual(file_by_id.display_name, 'Group_File.docx') + self.assertEqual(file_by_id.display_name, "Group_File.docx") self.assertEqual(file_by_id.size, 4096) file_by_obj = self.group.get_file(file_by_id) self.assertIsInstance(file_by_obj, File) - self.assertEqual(file_by_obj.display_name, 'Group_File.docx') + self.assertEqual(file_by_obj.display_name, "Group_File.docx") self.assertEqual(file_by_obj.size, 4096) # get_full_discussion_topic def test_get_full_discussion_topic(self, m): register_uris( - {'group': ['get_full_discussion_topic', 'get_discussion_topics']}, m + {"group": ["get_full_discussion_topic", "get_discussion_topics"]}, m ) discussion_by_id = self.group.get_full_discussion_topic(1) self.assertIsInstance(discussion_by_id, dict) - self.assertIn('view', discussion_by_id) - self.assertIn('participants', discussion_by_id) - self.assertIn('id', discussion_by_id) - self.assertEqual(discussion_by_id['id'], 1) + self.assertIn("view", discussion_by_id) + self.assertIn("participants", discussion_by_id) + self.assertIn("id", discussion_by_id) + self.assertEqual(discussion_by_id["id"], 1) discussion_topic = self.group.get_discussion_topics()[0] discussion_by_obj = self.group.get_full_discussion_topic(discussion_topic) self.assertIsInstance(discussion_by_obj, dict) - self.assertIn('view', discussion_by_obj) - self.assertIn('participants', discussion_by_obj) - self.assertIn('id', discussion_by_obj) - self.assertEqual(discussion_by_obj['id'], 1) + self.assertIn("view", discussion_by_obj) + self.assertIn("participants", discussion_by_obj) + self.assertIn("id", discussion_by_obj) + self.assertEqual(discussion_by_obj["id"], 1) # get_discussion_topics() def test_get_discussion_topics(self, m): - register_uris({'group': ['get_discussion_topics']}, m) + register_uris({"group": ["get_discussion_topics"]}, m) response = self.group.get_discussion_topics() discussion_list = [discussion for discussion in response] self.assertIsInstance(discussion_list[0], DiscussionTopic) - self.assertTrue(hasattr(discussion_list[0], 'group_id')) + self.assertTrue(hasattr(discussion_list[0], "group_id")) self.assertEqual(2, len(discussion_list)) # create_discussion_topic() def test_create_discussion_topic(self, m): - register_uris({'group': ['create_discussion_topic']}, m) + register_uris({"group": ["create_discussion_topic"]}, m) title = "Topic 1" discussion = self.group.create_discussion_topic() - self.assertTrue(hasattr(discussion, 'group_id')) + self.assertTrue(hasattr(discussion, "group_id")) self.assertIsInstance(discussion, DiscussionTopic) self.assertEqual(discussion.title, title) self.assertEqual(discussion.group_id, 1) @@ -329,8 +329,8 @@ def test_create_discussion_topic(self, m): def test_reorder_pinned_topics(self, m): # Custom matcher to test that params are set correctly def custom_matcher(request): - match_text = '1,2,3' - if request.text == 'order={}'.format(quote(match_text)): + match_text = "1,2,3" + if request.text == "order={}".format(quote(match_text)): resp = requests.Response() resp._content = b'{"reorder": true, "order": [1, 2, 3]}' resp.status_code = 200 @@ -343,14 +343,14 @@ def custom_matcher(request): self.assertTrue(discussions) def test_reorder_pinned_topics_tuple(self, m): - register_uris({'group': ['reorder_pinned_topics']}, m) + register_uris({"group": ["reorder_pinned_topics"]}, m) order = (1, 2, 3) discussions = self.group.reorder_pinned_topics(order=order) self.assertTrue(discussions) def test_reorder_pinned_topics_comma_separated_string(self, m): - register_uris({'group': ['reorder_pinned_topics']}, m) + register_uris({"group": ["reorder_pinned_topics"]}, m) order = "1,2,3" discussions = self.group.reorder_pinned_topics(order=order) @@ -363,13 +363,13 @@ def test_reorder_pinned_topics_invalid_input(self, m): # list_external_feeds() def test_list_external_feeds(self, m): - register_uris({'group': ['list_external_feeds']}, m) + register_uris({"group": ["list_external_feeds"]}, m) with warnings.catch_warnings(record=True) as warning_list: feeds = self.group.list_external_feeds() feed_list = [feed for feed in feeds] self.assertEqual(len(feed_list), 2) - self.assertTrue(hasattr(feed_list[0], 'url')) + self.assertTrue(hasattr(feed_list[0], "url")) self.assertIsInstance(feed_list[0], ExternalFeed) self.assertEqual(len(warning_list), 1) @@ -377,17 +377,17 @@ def test_list_external_feeds(self, m): # get_external_feeds() def test_get_external_feeds(self, m): - register_uris({'group': ['list_external_feeds']}, m) + register_uris({"group": ["list_external_feeds"]}, m) feeds = self.group.get_external_feeds() feed_list = [feed for feed in feeds] self.assertEqual(len(feed_list), 2) - self.assertTrue(hasattr(feed_list[0], 'url')) + self.assertTrue(hasattr(feed_list[0], "url")) self.assertIsInstance(feed_list[0], ExternalFeed) # create_external_feed() def test_create_external_feed(self, m): - register_uris({'group': ['create_external_feed']}, m) + register_uris({"group": ["create_external_feed"]}, m) url_str = "https://example.com/myblog.rss" response = self.group.create_external_feed(url=url_str) @@ -395,23 +395,23 @@ def test_create_external_feed(self, m): # delete_external_feed() def test_delete_external_feed(self, m): - register_uris({'group': ['delete_external_feed']}, m) + register_uris({"group": ["delete_external_feed"]}, m) deleted_ef_by_id = self.group.delete_external_feed(1) self.assertIsInstance(deleted_ef_by_id, ExternalFeed) - self.assertTrue(hasattr(deleted_ef_by_id, 'url')) + self.assertTrue(hasattr(deleted_ef_by_id, "url")) self.assertEqual(deleted_ef_by_id.display_name, "My Blog") deleted_ef_by_obj = self.group.delete_external_feed(deleted_ef_by_id) self.assertIsInstance(deleted_ef_by_obj, ExternalFeed) - self.assertTrue(hasattr(deleted_ef_by_obj, 'url')) + self.assertTrue(hasattr(deleted_ef_by_obj, "url")) self.assertEqual(deleted_ef_by_obj.display_name, "My Blog") # list_files() def test_list_files(self, m): - register_uris({'group': ['list_group_files', 'list_group_files2']}, m) + register_uris({"group": ["list_group_files", "list_group_files2"]}, m) with warnings.catch_warnings(record=True) as warning_list: files = self.group.list_files() @@ -424,7 +424,7 @@ def test_list_files(self, m): # get_files() def test_get_files(self, m): - register_uris({'group': ['list_group_files', 'list_group_files2']}, m) + register_uris({"group": ["list_group_files", "list_group_files2"]}, m) files = self.group.get_files() file_list = [file for file in files] @@ -433,7 +433,7 @@ def test_get_files(self, m): # get_folder() def test_get_folder(self, m): - register_uris({'group': ['get_folder']}, m) + register_uris({"group": ["get_folder"]}, m) folder_by_id = self.group.get_folder(1) self.assertEqual(folder_by_id.name, "Folder 1") @@ -445,7 +445,7 @@ def test_get_folder(self, m): # list_folders() def test_list_folders(self, m): - register_uris({'group': ['list_folders']}, m) + register_uris({"group": ["list_folders"]}, m) with warnings.catch_warnings(record=True) as warning_list: folders = self.group.list_folders() @@ -458,7 +458,7 @@ def test_list_folders(self, m): # get_folders() def test_get_folders(self, m): - register_uris({'group': ['list_folders']}, m) + register_uris({"group": ["list_folders"]}, m) folders = self.group.get_folders() folder_list = [folder for folder in folders] @@ -467,7 +467,7 @@ def test_get_folders(self, m): # create_folder() def test_create_folder(self, m): - register_uris({'group': ['create_folder']}, m) + register_uris({"group": ["create_folder"]}, m) name_str = "Test String" response = self.group.create_folder(name=name_str) @@ -475,7 +475,7 @@ def test_create_folder(self, m): # list_tabs() def test_list_tabs(self, m): - register_uris({'group': ['list_tabs']}, m) + register_uris({"group": ["list_tabs"]}, m) with warnings.catch_warnings(record=True) as warning_list: tabs = self.group.list_tabs() @@ -488,7 +488,7 @@ def test_list_tabs(self, m): # get_tabs() def test_get_tabs(self, m): - register_uris({'group': ['list_tabs']}, m) + register_uris({"group": ["list_tabs"]}, m) tabs = self.group.get_tabs() tab_list = [tab for tab in tabs] @@ -497,42 +497,42 @@ def test_get_tabs(self, m): # create_content_migration def test_create_content_migration(self, m): - register_uris({'group': ['create_content_migration']}, m) + register_uris({"group": ["create_content_migration"]}, m) - content_migration = self.group.create_content_migration('dummy_importer') + content_migration = self.group.create_content_migration("dummy_importer") self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_migrator(self, m): register_uris( - {'group': ['create_content_migration', 'get_migration_systems_multiple']}, m + {"group": ["create_content_migration", "get_migration_systems_multiple"]}, m ) migrators = self.group.get_migration_systems() content_migration = self.group.create_content_migration(migrators[0]) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_bad_migration_type(self, m): - register_uris({'group': ['create_content_migration']}, m) + register_uris({"group": ["create_content_migration"]}, m) with self.assertRaises(TypeError): self.group.create_content_migration(1) # get_content_migration def test_get_content_migration(self, m): - register_uris({'group': ['get_content_migration_single']}, m) + register_uris({"group": ["get_content_migration_single"]}, m) content_migration = self.group.get_content_migration(1) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) # get_content_migrations def test_get_content_migrations(self, m): - register_uris({'group': ['get_content_migration_multiple']}, m) + register_uris({"group": ["get_content_migration_multiple"]}, m) content_migrations = self.group.get_content_migrations() @@ -547,7 +547,7 @@ def test_get_content_migrations(self, m): # get_migration_systems def test_get_migration_systems(self, m): - register_uris({'group': ['get_migration_systems_multiple']}, m) + register_uris({"group": ["get_migration_systems_multiple"]}, m) migration_systems = self.group.get_migration_systems() @@ -564,7 +564,7 @@ def test_get_migration_systems(self, m): # get_assignment_override def test_get_assignment_override(self, m): - register_uris({'assignment': ['override_group_alias']}, m) + register_uris({"assignment": ["override_group_alias"]}, m) override = self.group.get_assignment_override(1) @@ -573,7 +573,7 @@ def test_get_assignment_override(self, m): # get_content_exports() def test_list_content_exports(self, m): - register_uris({'group': ['multiple_content_exports']}, m) + register_uris({"group": ["multiple_content_exports"]}, m) content_exports = self.group.get_content_exports() content_export_list = [content_export for content_export in content_exports] @@ -585,21 +585,21 @@ def test_list_content_exports(self, m): # get_content_export() def test_show_content_export(self, m): - register_uris({'group': ['single_content_export']}, m) + register_uris({"group": ["single_content_export"]}, m) content_export = self.group.get_content_export(11) - self.assertTrue(hasattr(content_export, 'export_type')) + self.assertTrue(hasattr(content_export, "export_type")) self.assertIsInstance(content_export, ContentExport) # export_content() def test_export_content(self, m): - register_uris({'group': ['export_content']}, m) + register_uris({"group": ["export_content"]}, m) - content_export = self.group.export_content('d') + content_export = self.group.export_content("d") self.assertIsInstance(content_export, ContentExport) - self.assertTrue(hasattr(content_export, 'export_type')) + self.assertTrue(hasattr(content_export, "export_type")) @requests_mock.Mocker() @@ -608,7 +608,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'group': ['get_by_id', 'get_membership']}, m) + register_uris({"group": ["get_by_id", "get_membership"]}, m) self.group = self.canvas.get_group(1) self.membership = self.group.get_membership(1, "users") @@ -620,14 +620,14 @@ def test__str__(self, m): # update() def test_update(self, m): - register_uris({'group': ['update_membership_membership']}, m) + register_uris({"group": ["update_membership_membership"]}, m) response = self.membership.update(mem_id=1, moderator=False) self.assertIsInstance(response, GroupMembership) # remove_user() def test_remove_user(self, m): - register_uris({'group': ['remove_user'], 'user': ['get_by_id']}, m) + register_uris({"group": ["remove_user"], "user": ["get_by_id"]}, m) response_by_id = self.membership.remove_user(1) self.assertIsInstance(response_by_id, dict) @@ -640,7 +640,7 @@ def test_remove_user(self, m): # remove_self() def test_remove_self(self, m): - register_uris({'group': ['remove_self']}, m) + register_uris({"group": ["remove_self"]}, m) response = self.membership.remove_self() @@ -653,7 +653,7 @@ class TestGroupCategory(unittest.TestCase): def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'create_group_category']}, m) + register_uris({"course": ["get_by_id", "create_group_category"]}, m) self.course = self.canvas.get_course(1) self.group_category = self.course.create_group_category("Test String") @@ -665,17 +665,17 @@ def test__str__(self, m): # create_group() def test_create_group(self, m): - register_uris({'group': ['category_create_group']}, m) + register_uris({"group": ["category_create_group"]}, m) test_str = "Test Create Group" response = self.group_category.create_group(name=test_str) self.assertIsInstance(response, Group) - self.assertTrue(hasattr(response, 'name')) + self.assertTrue(hasattr(response, "name")) self.assertEqual(response.name, test_str) # update() def test_update(self, m): - register_uris({'group': ['category_update']}, m) + register_uris({"group": ["category_update"]}, m) new_name = "Test Update Category" response = self.group_category.update(name=new_name) @@ -683,7 +683,7 @@ def test_update(self, m): # delete_category() def test_delete_category(self, m): - register_uris({'group': ['category_delete_category']}, m) + register_uris({"group": ["category_delete_category"]}, m) response = self.group_category.delete() @@ -692,40 +692,40 @@ def test_delete_category(self, m): # list_groups() def test_list_groups(self, m): - register_uris({'group': ['category_list_groups']}, m) + register_uris({"group": ["category_list_groups"]}, m) with warnings.catch_warnings(record=True) as warning_list: response = self.group_category.list_groups() group_list = [group for group in response] self.assertEqual(len(group_list), 2) self.assertIsInstance(group_list[0], Group) - self.assertTrue(hasattr(group_list[0], 'id')) + self.assertTrue(hasattr(group_list[0], "id")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) # get_groups() def test_get_groups(self, m): - register_uris({'group': ['category_list_groups']}, m) + register_uris({"group": ["category_list_groups"]}, m) response = self.group_category.get_groups() group_list = [group for group in response] self.assertEqual(len(group_list), 2) self.assertIsInstance(group_list[0], Group) - self.assertTrue(hasattr(group_list[0], 'id')) + self.assertTrue(hasattr(group_list[0], "id")) # list_users() def test_list_users(self, m): from canvasapi.user import User - register_uris({'group': ['category_list_users']}, m) + register_uris({"group": ["category_list_users"]}, m) with warnings.catch_warnings(record=True) as warning_list: response = self.group_category.list_users() user_list = [user for user in response] self.assertEqual(len(user_list), 4) self.assertIsInstance(user_list[0], User) - self.assertTrue(hasattr(user_list[0], 'user_id')) + self.assertTrue(hasattr(user_list[0], "user_id")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -734,13 +734,13 @@ def test_list_users(self, m): def test_get_users(self, m): from canvasapi.user import User - register_uris({'group': ['category_list_users']}, m) + register_uris({"group": ["category_list_users"]}, m) response = self.group_category.get_users() user_list = [user for user in response] self.assertEqual(len(user_list), 4) self.assertIsInstance(user_list[0], User) - self.assertTrue(hasattr(user_list[0], 'user_id')) + self.assertTrue(hasattr(user_list[0], "user_id")) # assign_members() def test_assign_members(self, m): @@ -748,7 +748,7 @@ def test_assign_members(self, m): from canvasapi.paginated_list import PaginatedList requires = { - 'group': ['category_assign_members_true', 'category_assign_members_false'] + "group": ["category_assign_members_true", "category_assign_members_false"] } register_uris(requires, m) diff --git a/tests/test_login.py b/tests/test_login.py index 1a38489f..2921481b 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -15,34 +15,34 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'account': ['get_by_id'], 'login': ['create_user_login']}, m) + register_uris({"account": ["get_by_id"], "login": ["create_user_login"]}, m) self.account = self.canvas.get_account(1) self.login = self.account.create_user_login( - user={'id': 1}, login={'unique_id': 'belieber@example.com'} + user={"id": 1}, login={"unique_id": "belieber@example.com"} ) # delete() def test_delete_user_login(self, m): - register_uris({'login': ['delete_user_login']}, m) + register_uris({"login": ["delete_user_login"]}, m) deleted_user_login = self.login.delete() self.assertIsInstance(deleted_user_login, Login) - self.assertTrue(hasattr(deleted_user_login, 'unique_id')) - self.assertEqual(deleted_user_login.unique_id, 'belieber@example.com') + self.assertTrue(hasattr(deleted_user_login, "unique_id")) + self.assertEqual(deleted_user_login.unique_id, "belieber@example.com") # edit() def test_edit_user_login(self, m): - register_uris({'login': ['edit_user_login']}, m) + register_uris({"login": ["edit_user_login"]}, m) - unique_id = 'newemail@example.com' + unique_id = "newemail@example.com" edited_user_login = self.login.edit( - user={'id': 1}, login={'unique_id': unique_id} + user={"id": 1}, login={"unique_id": unique_id} ) self.assertIsInstance(edited_user_login, Login) - self.assertTrue(hasattr(edited_user_login, 'unique_id')) + self.assertTrue(hasattr(edited_user_login, "unique_id")) self.assertEqual(edited_user_login.unique_id, unique_id) # __str__() diff --git a/tests/test_module.py b/tests/test_module.py index 0a654f60..9c4210b9 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -17,47 +17,47 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'get_module_by_id']}, m) + register_uris({"course": ["get_by_id", "get_module_by_id"]}, m) self.course = self.canvas.get_course(1) self.module = self.course.get_module(1) # edit() def test_edit_module(self, m): - register_uris({'module': ['edit']}, m) + register_uris({"module": ["edit"]}, m) - name = 'New Name' - edited_module = self.module.edit(module={'name': name}) + name = "New Name" + edited_module = self.module.edit(module={"name": name}) self.assertIsInstance(edited_module, Module) - self.assertTrue(hasattr(edited_module, 'name')) + self.assertTrue(hasattr(edited_module, "name")) self.assertEqual(edited_module.name, name) - self.assertTrue(hasattr(edited_module, 'course_id')) + self.assertTrue(hasattr(edited_module, "course_id")) self.assertEqual(edited_module.course_id, self.course.id) # delete() def test_delete_module(self, m): - register_uris({'module': ['delete']}, m) + register_uris({"module": ["delete"]}, m) deleted_module = self.module.delete() self.assertIsInstance(deleted_module, Module) - self.assertTrue(hasattr(deleted_module, 'course_id')) + self.assertTrue(hasattr(deleted_module, "course_id")) self.assertEqual(deleted_module.course_id, self.course.id) # relock() def test_relock(self, m): - register_uris({'module': ['relock']}, m) + register_uris({"module": ["relock"]}, m) relocked_module = self.module.relock() self.assertIsInstance(relocked_module, Module) - self.assertTrue(hasattr(relocked_module, 'course_id')) + self.assertTrue(hasattr(relocked_module, "course_id")) self.assertEqual(relocked_module.course_id, self.course.id) # list_module_items() def test_list_module_items(self, m): - register_uris({'module': ['list_module_items', 'list_module_items2']}, m) + register_uris({"module": ["list_module_items", "list_module_items2"]}, m) with warnings.catch_warnings(record=True) as warning_list: module_items = self.module.list_module_items() @@ -65,7 +65,7 @@ def test_list_module_items(self, m): self.assertEqual(len(module_item_list), 4) self.assertIsInstance(module_item_list[0], ModuleItem) - self.assertTrue(hasattr(module_item_list[0], 'course_id')) + self.assertTrue(hasattr(module_item_list[0], "course_id")) self.assertEqual(module_item_list[0].course_id, self.course.id) self.assertEqual(len(warning_list), 1) @@ -73,50 +73,50 @@ def test_list_module_items(self, m): # get_module_items() def test_get_module_items(self, m): - register_uris({'module': ['list_module_items', 'list_module_items2']}, m) + register_uris({"module": ["list_module_items", "list_module_items2"]}, m) module_items = self.module.get_module_items() module_item_list = [module_item for module_item in module_items] self.assertEqual(len(module_item_list), 4) self.assertIsInstance(module_item_list[0], ModuleItem) - self.assertTrue(hasattr(module_item_list[0], 'course_id')) + self.assertTrue(hasattr(module_item_list[0], "course_id")) self.assertEqual(module_item_list[0].course_id, self.course.id) # get_module_item() def test_get_module_item(self, m): - register_uris({'module': ['get_module_item_by_id']}, m) + register_uris({"module": ["get_module_item_by_id"]}, m) module_item_by_id = self.module.get_module_item(1) self.assertIsInstance(module_item_by_id, ModuleItem) - self.assertTrue(hasattr(module_item_by_id, 'course_id')) + self.assertTrue(hasattr(module_item_by_id, "course_id")) self.assertEqual(module_item_by_id.course_id, self.course.id) module_item_by_obj = self.module.get_module_item(module_item_by_id) self.assertIsInstance(module_item_by_obj, ModuleItem) - self.assertTrue(hasattr(module_item_by_obj, 'course_id')) + self.assertTrue(hasattr(module_item_by_obj, "course_id")) self.assertEqual(module_item_by_obj.course_id, self.course.id) # create_module_item() def test_create_module_item(self, m): - register_uris({'module': ['create_module_item']}, m) + register_uris({"module": ["create_module_item"]}, m) module_item = self.module.create_module_item( - module_item={'type': 'Page', 'content_id': 1} + module_item={"type": "Page", "content_id": 1} ) self.assertIsInstance(module_item, ModuleItem) - self.assertTrue(hasattr(module_item, 'course_id')) + self.assertTrue(hasattr(module_item, "course_id")) self.assertEqual(module_item.course_id, self.course.id) def test_create_module_item_fail1(self, m): with self.assertRaises(RequiredFieldMissing): - self.module.create_module_item(module_item={'content_id': 1}) + self.module.create_module_item(module_item={"content_id": 1}) def test_create_module_item_fail2(self, m): with self.assertRaises(RequiredFieldMissing): - self.module.create_module_item(module_item={'type': 'Page'}) + self.module.create_module_item(module_item={"type": "Page"}) # __str__ def test__str__(self, m): @@ -131,8 +131,8 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_module_by_id'], - 'module': ['get_module_item_by_id'], + "course": ["get_by_id", "get_module_by_id"], + "module": ["get_module_item_by_id"], } register_uris(requires, m) @@ -142,47 +142,47 @@ def setUp(self): # edit() def test_edit_module_item(self, m): - register_uris({'module': ['edit_module_item']}, m) + register_uris({"module": ["edit_module_item"]}, m) - title = 'New Title' - edited_module_item = self.module_item.edit(module_item={'title': title}) + title = "New Title" + edited_module_item = self.module_item.edit(module_item={"title": title}) self.assertIsInstance(edited_module_item, ModuleItem) - self.assertTrue(hasattr(edited_module_item, 'title')) + self.assertTrue(hasattr(edited_module_item, "title")) self.assertEqual(edited_module_item.title, title) - self.assertTrue(hasattr(edited_module_item, 'course_id')) + self.assertTrue(hasattr(edited_module_item, "course_id")) self.assertEqual(edited_module_item.course_id, self.course.id) # delete() def test_delete(self, m): - register_uris({'module': ['delete_module_item']}, m) + register_uris({"module": ["delete_module_item"]}, m) deleted_module_item = self.module_item.delete() self.assertIsInstance(deleted_module_item, ModuleItem) - self.assertTrue(hasattr(deleted_module_item, 'course_id')) + self.assertTrue(hasattr(deleted_module_item, "course_id")) self.assertEqual(deleted_module_item.course_id, self.course.id) # complete(course_id, True) def test_complete(self, m): - register_uris({'module': ['complete_module_item']}, m) + register_uris({"module": ["complete_module_item"]}, m) completed_module_item = self.module_item.complete() self.assertIsInstance(completed_module_item, ModuleItem) - self.assertTrue(hasattr(completed_module_item, 'completion_requirement')) - self.assertTrue(hasattr(completed_module_item, 'course_id')) + self.assertTrue(hasattr(completed_module_item, "completion_requirement")) + self.assertTrue(hasattr(completed_module_item, "course_id")) self.assertEqual(completed_module_item.course_id, self.course.id) # complete(course_id, False) def test_uncomplete(self, m): - register_uris({'module': ['uncomplete_module_item']}, m) + register_uris({"module": ["uncomplete_module_item"]}, m) completed_module_item = self.module_item.uncomplete() self.assertIsInstance(completed_module_item, ModuleItem) - self.assertTrue(hasattr(completed_module_item, 'completion_requirement')) - self.assertTrue(hasattr(completed_module_item, 'course_id')) + self.assertTrue(hasattr(completed_module_item, "completion_requirement")) + self.assertTrue(hasattr(completed_module_item, "course_id")) self.assertEqual(completed_module_item.course_id, self.course.id) def test__str__(self, m): diff --git a/tests/test_notification_preference.py b/tests/test_notification_preference.py index c834bee6..b2dab2df 100644 --- a/tests/test_notification_preference.py +++ b/tests/test_notification_preference.py @@ -16,15 +16,15 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'user': ['get_by_id', 'list_comm_channels'], - 'communication_channel': ['get_preference'], + "user": ["get_by_id", "list_comm_channels"], + "communication_channel": ["get_preference"], }, m, ) self.user = self.canvas.get_user(1) self.comm_chan = self.user.get_communication_channels()[0] - self.notif_pref = self.comm_chan.get_preference('new_announcement') + self.notif_pref = self.comm_chan.get_preference("new_announcement") # __str__() def test__str__(self, m): diff --git a/tests/test_outcome.py b/tests/test_outcome.py index 99d99e85..0f20a7d3 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -18,13 +18,13 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'course': ['get_by_id'], - 'outcome': [ - 'account_root_outcome_group', - 'canvas_root_outcome_group', - 'course_root_outcome_group', - 'course_outcome_links_in_context', - 'outcome_example', + "course": ["get_by_id"], + "outcome": [ + "account_root_outcome_group", + "canvas_root_outcome_group", + "course_root_outcome_group", + "course_outcome_links_in_context", + "outcome_example", ], }, m, @@ -41,8 +41,8 @@ def test__str__(self, m): # update() def test_update(self, m): - register_uris({'outcome': ['outcome_update']}, m) - self.assertEqual(self.example_outcome.title, 'Outcome Show Example') + register_uris({"outcome": ["outcome_update"]}, m) + self.assertEqual(self.example_outcome.title, "Outcome Show Example") result = self.example_outcome.update(title="new_title") self.assertTrue(result) self.assertIsInstance(self.example_outcome, Outcome) @@ -57,11 +57,11 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'account': ['get_by_id'], - 'course': ['get_by_id'], - 'outcome': [ - 'account_outcome_links_in_context', - 'course_outcome_links_in_context', + "account": ["get_by_id"], + "course": ["get_by_id"], + "outcome": [ + "account_outcome_links_in_context", + "course_outcome_links_in_context", ], }, m, @@ -74,14 +74,14 @@ def setUp(self): # __str__() def test__str__(self, m): - register_uris({'outcome': ['course_outcome_links_in_context']}, m) + register_uris({"outcome": ["course_outcome_links_in_context"]}, m) string = str(self.course_outcome_links[0]) self.assertIsInstance(string, str) # get_outcome() def test_get_outcome(self, m): register_uris( - {'outcome': ['outcome_example', 'course_outcome_links_in_context']}, m + {"outcome": ["outcome_example", "course_outcome_links_in_context"]}, m ) result = self.course_outcome_links[0].get_outcome() self.assertIsInstance(result, Outcome) @@ -90,11 +90,11 @@ def test_get_outcome(self, m): def test_get_outcome_group(self, m): register_uris( { - 'outcome': [ - 'outcome_group_example_account', - 'account_outcome_links_in_context', - 'outcome_group_example_course', - 'course_outcome_links_in_context', + "outcome": [ + "outcome_group_example_account", + "account_outcome_links_in_context", + "outcome_group_example_course", + "course_outcome_links_in_context", ] }, m, @@ -113,14 +113,14 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'account': ['get_by_id'], - 'course': ['get_by_id'], - 'outcome': [ - 'account_root_outcome_group', - 'canvas_root_outcome_group', - 'course_root_outcome_group', - 'course_outcome_links_in_context', - 'outcome_example', + "account": ["get_by_id"], + "course": ["get_by_id"], + "outcome": [ + "account_root_outcome_group", + "canvas_root_outcome_group", + "course_root_outcome_group", + "course_outcome_links_in_context", + "outcome_example", ], }, m, @@ -149,10 +149,10 @@ def test__str__(self, m): def test_update(self, m): register_uris( { - 'outcome': [ - 'outcome_group_update_global', - 'outcome_group_update_account', - 'outcome_group_update_course', + "outcome": [ + "outcome_group_update_global", + "outcome_group_update_account", + "outcome_group_update_course", ] }, m, @@ -160,19 +160,19 @@ def test_update(self, m): new_title = "New Outcome Group Title" - self.assertEqual(self.account_outcome_group.title, 'ROOT') + self.assertEqual(self.account_outcome_group.title, "ROOT") result = self.account_outcome_group.update(title=new_title) self.assertTrue(result) self.assertIsInstance(self.account_outcome_group, OutcomeGroup) self.assertEqual(self.account_outcome_group.title, new_title) - self.assertEqual(self.canvas_outcome_group.title, 'ROOT') + self.assertEqual(self.canvas_outcome_group.title, "ROOT") result = self.canvas_outcome_group.update(title=new_title) self.assertTrue(result) self.assertIsInstance(self.canvas_outcome_group, OutcomeGroup) self.assertEqual(self.canvas_outcome_group.title, new_title) - self.assertEqual(self.course_outcome_group.title, 'ROOT') + self.assertEqual(self.course_outcome_group.title, "ROOT") result = self.course_outcome_group.update(title=new_title) self.assertTrue(result) self.assertIsInstance(self.course_outcome_group, OutcomeGroup) @@ -182,24 +182,24 @@ def test_update(self, m): def test_delete(self, m): register_uris( { - 'outcome': [ - 'outcome_group_delete_global', - 'outcome_group_delete_account', - 'outcome_group_delete_course', + "outcome": [ + "outcome_group_delete_global", + "outcome_group_delete_account", + "outcome_group_delete_course", ] }, m, ) - self.assertEqual(self.account_outcome_group.title, 'ROOT') + self.assertEqual(self.account_outcome_group.title, "ROOT") result = self.account_outcome_group.delete() self.assertTrue(result) - self.assertEqual(self.canvas_outcome_group.title, 'ROOT') + self.assertEqual(self.canvas_outcome_group.title, "ROOT") result = self.canvas_outcome_group.delete() self.assertTrue(result) - self.assertEqual(self.course_outcome_group.title, 'ROOT') + self.assertEqual(self.course_outcome_group.title, "ROOT") result = self.course_outcome_group.delete() self.assertTrue(result) @@ -207,10 +207,10 @@ def test_delete(self, m): def test_list_linked_outcomes(self, m): register_uris( { - 'outcome': [ - 'outcome_group_list_linked_outcomes_account', - 'outcome_group_list_linked_outcomes_global', - 'outcome_group_list_linked_outcomes_courses', + "outcome": [ + "outcome_group_list_linked_outcomes_account", + "outcome_group_list_linked_outcomes_global", + "outcome_group_list_linked_outcomes_courses", ] }, m, @@ -219,9 +219,9 @@ def test_list_linked_outcomes(self, m): with warnings.catch_warnings(record=True) as warning_list: result = self.account_outcome_group.list_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) - self.assertEqual(result[0].outcome_group['id'], 2) + self.assertEqual(result[0].outcome_group["id"], 2) self.assertEqual( - result[0].outcome_group['title'], "Account Test Outcome Group" + result[0].outcome_group["title"], "Account Test Outcome Group" ) self.assertEqual(len(warning_list), 1) @@ -230,9 +230,9 @@ def test_list_linked_outcomes(self, m): with warnings.catch_warnings(record=True) as warning_list: result = self.canvas_outcome_group.list_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) - self.assertEqual(result[0].outcome_group['id'], 2) + self.assertEqual(result[0].outcome_group["id"], 2) self.assertEqual( - result[0].outcome_group['title'], "Global Test Outcome Group" + result[0].outcome_group["title"], "Global Test Outcome Group" ) self.assertEqual(len(warning_list), 1) @@ -241,9 +241,9 @@ def test_list_linked_outcomes(self, m): with warnings.catch_warnings(record=True) as warning_list: result = self.course_outcome_group.list_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) - self.assertEqual(result[0].outcome_group['id'], 2) + self.assertEqual(result[0].outcome_group["id"], 2) self.assertEqual( - result[0].outcome_group['title'], "Course Test Outcome Group" + result[0].outcome_group["title"], "Course Test Outcome Group" ) self.assertEqual(len(warning_list), 1) @@ -253,10 +253,10 @@ def test_list_linked_outcomes(self, m): def test_get_linked_outcomes(self, m): register_uris( { - 'outcome': [ - 'outcome_group_list_linked_outcomes_account', - 'outcome_group_list_linked_outcomes_global', - 'outcome_group_list_linked_outcomes_courses', + "outcome": [ + "outcome_group_list_linked_outcomes_account", + "outcome_group_list_linked_outcomes_global", + "outcome_group_list_linked_outcomes_courses", ] }, m, @@ -264,28 +264,28 @@ def test_get_linked_outcomes(self, m): result = self.account_outcome_group.get_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) - self.assertEqual(result[0].outcome_group['id'], 2) - self.assertEqual(result[0].outcome_group['title'], "Account Test Outcome Group") + self.assertEqual(result[0].outcome_group["id"], 2) + self.assertEqual(result[0].outcome_group["title"], "Account Test Outcome Group") result = self.canvas_outcome_group.get_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) - self.assertEqual(result[0].outcome_group['id'], 2) - self.assertEqual(result[0].outcome_group['title'], "Global Test Outcome Group") + self.assertEqual(result[0].outcome_group["id"], 2) + self.assertEqual(result[0].outcome_group["title"], "Global Test Outcome Group") result = self.course_outcome_group.get_linked_outcomes() self.assertIsInstance(result[0], OutcomeLink) - self.assertEqual(result[0].outcome_group['id'], 2) - self.assertEqual(result[0].outcome_group['title'], "Course Test Outcome Group") + self.assertEqual(result[0].outcome_group["id"], 2) + self.assertEqual(result[0].outcome_group["title"], "Course Test Outcome Group") # link_existing() def test_link_existing(self, m): register_uris( { - 'outcome': [ - 'outcome_example', - 'outcome_group_link_existing_global', - 'outcome_group_link_existing_account', - 'outcome_group_link_existing_course', + "outcome": [ + "outcome_example", + "outcome_group_link_existing_global", + "outcome_group_link_existing_account", + "outcome_group_link_existing_course", ] }, m, @@ -293,36 +293,36 @@ def test_link_existing(self, m): result = self.canvas_outcome_group.link_existing(self.example_outcome) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 2) + self.assertEqual(result.outcome_group["id"], 2) result = self.account_outcome_group.link_existing(self.example_outcome) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 2) + self.assertEqual(result.outcome_group["id"], 2) result = self.course_outcome_group.link_existing(self.example_outcome) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 2) + self.assertEqual(result.outcome_group["id"], 2) result = self.canvas_outcome_group.link_existing(3) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 2) + self.assertEqual(result.outcome_group["id"], 2) result = self.account_outcome_group.link_existing(3) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 2) + self.assertEqual(result.outcome_group["id"], 2) result = self.course_outcome_group.link_existing(3) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 2) + self.assertEqual(result.outcome_group["id"], 2) # link_new() def test_link_new(self, m): register_uris( { - 'outcome': [ - 'outcome_group_link_new_global', - 'outcome_group_link_new_account', - 'outcome_group_link_new_course', + "outcome": [ + "outcome_group_link_new_global", + "outcome_group_link_new_account", + "outcome_group_link_new_course", ] }, m, @@ -332,31 +332,31 @@ def test_link_new(self, m): result = self.canvas_outcome_group.link_new(title=new_title) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 1) - self.assertEqual(result.outcome['id'], 2) - self.assertEqual(result.outcome['context_type'], None) + self.assertEqual(result.outcome_group["id"], 1) + self.assertEqual(result.outcome["id"], 2) + self.assertEqual(result.outcome["context_type"], None) result = self.account_outcome_group.link_new(title=new_title) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 1) - self.assertEqual(result.outcome['id'], 2) - self.assertEqual(result.outcome['context_type'], 'Account') + self.assertEqual(result.outcome_group["id"], 1) + self.assertEqual(result.outcome["id"], 2) + self.assertEqual(result.outcome["context_type"], "Account") result = self.course_outcome_group.link_new(title=new_title) self.assertIsInstance(result, OutcomeLink) - self.assertEqual(result.outcome_group['id'], 1) - self.assertEqual(result.outcome['id'], 2) - self.assertEqual(result.outcome['context_type'], 'Course') + self.assertEqual(result.outcome_group["id"], 1) + self.assertEqual(result.outcome["id"], 2) + self.assertEqual(result.outcome["context_type"], "Course") # unlink_outcome() def test_unlink_outcome(self, m): register_uris( { - 'outcome': [ - 'outcome_example', - 'outcome_group_unlink_outcome_global', - 'outcome_group_unlink_outcome_account', - 'outcome_group_unlink_outcome_course', + "outcome": [ + "outcome_example", + "outcome_group_unlink_outcome_global", + "outcome_group_unlink_outcome_account", + "outcome_group_unlink_outcome_course", ] }, m, @@ -384,10 +384,10 @@ def test_unlink_outcome(self, m): def test_list_subgroups(self, m): register_uris( { - 'outcome': [ - 'outcome_group_list_subgroups_global', - 'outcome_group_list_subgroups_account', - 'outcome_group_list_subgroups_course', + "outcome": [ + "outcome_group_list_subgroups_global", + "outcome_group_list_subgroups_account", + "outcome_group_list_subgroups_course", ] }, m, @@ -433,10 +433,10 @@ def test_list_subgroups(self, m): def test_get_subgroups(self, m): register_uris( { - 'outcome': [ - 'outcome_group_list_subgroups_global', - 'outcome_group_list_subgroups_account', - 'outcome_group_list_subgroups_course', + "outcome": [ + "outcome_group_list_subgroups_global", + "outcome_group_list_subgroups_account", + "outcome_group_list_subgroups_course", ] }, m, @@ -446,58 +446,58 @@ def test_get_subgroups(self, m): self.assertIsInstance(result[0], OutcomeGroup) self.assertEqual(result[0].id, 2) self.assertEqual(result[0].title, "Global Listed Subgroup Title 1") - self.assertTrue(hasattr(result[0], 'context_type')) + self.assertTrue(hasattr(result[0], "context_type")) self.assertEqual(result[0].context_type, None) - self.assertTrue(hasattr(result[0], 'context_id')) + self.assertTrue(hasattr(result[0], "context_id")) self.assertEqual(result[0].context_id, None) self.assertIsInstance(result[1], OutcomeGroup) self.assertEqual(result[1].id, 3) self.assertEqual(result[1].title, "Global Listed Subgroup Title 2") - self.assertTrue(hasattr(result[0], 'context_type')) + self.assertTrue(hasattr(result[0], "context_type")) self.assertEqual(result[0].context_type, None) - self.assertTrue(hasattr(result[0], 'context_id')) + self.assertTrue(hasattr(result[0], "context_id")) self.assertEqual(result[0].context_id, None) result = self.account_outcome_group.get_subgroups() self.assertIsInstance(result[0], OutcomeGroup) self.assertEqual(result[0].id, 2) self.assertEqual(result[0].title, "Account Listed Subgroup Title 1") - self.assertTrue(hasattr(result[0], 'context_type')) - self.assertEqual(result[0].context_type, 'Account') - self.assertTrue(hasattr(result[0], 'context_id')) + self.assertTrue(hasattr(result[0], "context_type")) + self.assertEqual(result[0].context_type, "Account") + self.assertTrue(hasattr(result[0], "context_id")) self.assertEqual(result[0].context_id, self.account.id) self.assertIsInstance(result[1], OutcomeGroup) self.assertEqual(result[1].id, 3) self.assertEqual(result[1].title, "Account Listed Subgroup Title 2") - self.assertTrue(hasattr(result[0], 'context_type')) - self.assertEqual(result[0].context_type, 'Account') - self.assertTrue(hasattr(result[0], 'context_id')) + self.assertTrue(hasattr(result[0], "context_type")) + self.assertEqual(result[0].context_type, "Account") + self.assertTrue(hasattr(result[0], "context_id")) self.assertEqual(result[0].context_id, self.account.id) result = self.course_outcome_group.get_subgroups() self.assertIsInstance(result[0], OutcomeGroup) self.assertEqual(result[0].id, 2) self.assertEqual(result[0].title, "Course Listed Subgroup Title 1") - self.assertTrue(hasattr(result[0], 'context_type')) - self.assertEqual(result[0].context_type, 'Course') - self.assertTrue(hasattr(result[0], 'context_id')) + self.assertTrue(hasattr(result[0], "context_type")) + self.assertEqual(result[0].context_type, "Course") + self.assertTrue(hasattr(result[0], "context_id")) self.assertEqual(result[0].context_id, self.course.id) self.assertIsInstance(result[1], OutcomeGroup) self.assertEqual(result[1].id, 3) self.assertEqual(result[1].title, "Course Listed Subgroup Title 2") - self.assertTrue(hasattr(result[0], 'context_type')) - self.assertEqual(result[0].context_type, 'Course') - self.assertTrue(hasattr(result[0], 'context_id')) + self.assertTrue(hasattr(result[0], "context_type")) + self.assertEqual(result[0].context_type, "Course") + self.assertTrue(hasattr(result[0], "context_id")) self.assertEqual(result[0].context_id, self.course.id) # create_subgroup() def test_create_subgroup(self, m): register_uris( { - 'outcome': [ - 'outcome_group_create_subgroup_global', - 'outcome_group_create_subgroup_account', - 'outcome_group_create_subgroup_course', + "outcome": [ + "outcome_group_create_subgroup_global", + "outcome_group_create_subgroup_account", + "outcome_group_create_subgroup_course", ] }, m, @@ -507,33 +507,33 @@ def test_create_subgroup(self, m): result = self.canvas_outcome_group.create_subgroup(new_title) self.assertEqual( - self.canvas_outcome_group.id, result.parent_outcome_group['id'] + self.canvas_outcome_group.id, result.parent_outcome_group["id"] ) - self.assertEqual(result.parent_outcome_group['title'], "Parent of Subgroup") + self.assertEqual(result.parent_outcome_group["title"], "Parent of Subgroup") self.assertEqual(result.title, "New Subgroup Title") result = self.account_outcome_group.create_subgroup(new_title) self.assertEqual( - self.canvas_outcome_group.id, result.parent_outcome_group['id'] + self.canvas_outcome_group.id, result.parent_outcome_group["id"] ) - self.assertEqual(result.parent_outcome_group['title'], "Parent of Subgroup") + self.assertEqual(result.parent_outcome_group["title"], "Parent of Subgroup") self.assertEqual(result.title, "New Subgroup Title") result = self.course_outcome_group.create_subgroup(new_title) self.assertEqual( - self.canvas_outcome_group.id, result.parent_outcome_group['id'] + self.canvas_outcome_group.id, result.parent_outcome_group["id"] ) - self.assertEqual(result.parent_outcome_group['title'], "Parent of Subgroup") + self.assertEqual(result.parent_outcome_group["title"], "Parent of Subgroup") self.assertEqual(result.title, "New Subgroup Title") # import_outcome_group() def test_import_outcome_group(self, m): register_uris( { - 'outcome': [ - 'outcome_group_import_outcome_group_global', - 'outcome_group_import_outcome_group_account', - 'outcome_group_import_outcome_group_course', + "outcome": [ + "outcome_group_import_outcome_group_global", + "outcome_group_import_outcome_group_account", + "outcome_group_import_outcome_group_course", ] }, m, @@ -543,38 +543,38 @@ def test_import_outcome_group(self, m): self.assertEqual(result.id, 4) self.assertEqual(result.title, "Global Imported Subgroup Title") self.assertEqual( - result.parent_outcome_group['id'], self.canvas_outcome_group.id + result.parent_outcome_group["id"], self.canvas_outcome_group.id ) self.assertEqual( - result.parent_outcome_group['title'], self.canvas_outcome_group.title + result.parent_outcome_group["title"], self.canvas_outcome_group.title ) result = self.account_outcome_group.import_outcome_group(3) self.assertEqual(result.id, 4) self.assertEqual(result.title, "Account Imported Subgroup Title") self.assertEqual( - result.parent_outcome_group['id'], self.account_outcome_group.id + result.parent_outcome_group["id"], self.account_outcome_group.id ) self.assertEqual( - result.parent_outcome_group['title'], self.account_outcome_group.title + result.parent_outcome_group["title"], self.account_outcome_group.title ) result = self.course_outcome_group.import_outcome_group(3) self.assertEqual(result.id, 4) self.assertEqual(result.title, "Course Imported Subgroup Title") self.assertEqual( - result.parent_outcome_group['id'], self.course_outcome_group.id + result.parent_outcome_group["id"], self.course_outcome_group.id ) self.assertEqual( - result.parent_outcome_group['title'], self.course_outcome_group.title + result.parent_outcome_group["title"], self.course_outcome_group.title ) result_by_obj = self.course_outcome_group.import_outcome_group(result) self.assertEqual(result_by_obj.id, 4) self.assertEqual(result_by_obj.title, "Course Imported Subgroup Title") self.assertEqual( - result_by_obj.parent_outcome_group['id'], self.course_outcome_group.id + result_by_obj.parent_outcome_group["id"], self.course_outcome_group.id ) self.assertEqual( - result_by_obj.parent_outcome_group['title'], self.course_outcome_group.title + result_by_obj.parent_outcome_group["title"], self.course_outcome_group.title ) diff --git a/tests/test_page.py b/tests/test_page.py index f0565e05..e0699453 100644 --- a/tests/test_page.py +++ b/tests/test_page.py @@ -19,16 +19,16 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id'], - 'group': ['get_by_id', 'pages_get_page'], - 'page': ['get_page'], + "course": ["get_by_id"], + "group": ["get_by_id", "pages_get_page"], + "page": ["get_page"], } register_uris(requires, m) self.course = self.canvas.get_course(1) self.group = self.canvas.get_group(1) - self.page_course = self.course.get_page('my-url') - self.page_group = self.group.get_page('my-url') + self.page_course = self.course.get_page("my-url") + self.page_group = self.group.get_page("my-url") # __str__() def test__str__(self, m): @@ -36,17 +36,17 @@ def test__str__(self, m): self.assertIsInstance(string, str) def test_edit(self, m): - register_uris({'page': ['edit']}, m) + register_uris({"page": ["edit"]}, m) new_title = "New Page" - self.page_course.edit(page={'title': new_title}) + self.page_course.edit(page={"title": new_title}) self.assertIsInstance(self.page_course, Page) - self.assertTrue(hasattr(self.page_course, 'title')) + self.assertTrue(hasattr(self.page_course, "title")) self.assertEqual(self.page_course.title, new_title) def test_delete(self, m): - register_uris({'page': ['delete_page']}, m) + register_uris({"page": ["delete_page"]}, m) page = self.page_course deleted_page = page.delete() @@ -55,7 +55,7 @@ def test_delete(self, m): # list_revisions() def test_list_revisions(self, m): - register_uris({'page': ['list_revisions', 'list_revisions2']}, m) + register_uris({"page": ["list_revisions", "list_revisions2"]}, m) with warnings.catch_warnings(record=True) as warning_list: revisions = self.page_course.list_revisions() @@ -69,7 +69,7 @@ def test_list_revisions(self, m): # get_revisions() def test_get_revisions(self, m): - register_uris({'page': ['list_revisions', 'list_revisions2']}, m) + register_uris({"page": ["list_revisions", "list_revisions2"]}, m) revisions = self.page_course.get_revisions() rev_list = [rev for rev in revisions] @@ -78,14 +78,14 @@ def test_get_revisions(self, m): self.assertIsInstance(rev_list[0], PageRevision) def test_show_latest_revision(self, m): - register_uris({'page': ['latest_revision']}, m) + register_uris({"page": ["latest_revision"]}, m) revision = self.page_course.show_latest_revision() self.assertIsInstance(revision, PageRevision) def test_get_revision_by_id_course(self, m): - register_uris({'page': ['get_latest_rev_by_id']}, m) + register_uris({"page": ["get_latest_rev_by_id"]}, m) revision_by_id = self.page_course.get_revision_by_id(2) self.assertIsInstance(revision_by_id, PageRevision) @@ -94,7 +94,7 @@ def test_get_revision_by_id_course(self, m): self.assertIsInstance(revision_by_obj, PageRevision) def test_get_revision_by_id_group(self, m): - register_uris({'page': ['get_latest_rev_by_id_group']}, m) + register_uris({"page": ["get_latest_rev_by_id_group"]}, m) revision_by_id = self.page_group.get_revision_by_id(2) self.assertIsInstance(revision_by_id, PageRevision) @@ -103,14 +103,14 @@ def test_get_revision_by_id_group(self, m): self.assertIsInstance(revision_by_obj, PageRevision) def test_revert_to_revision_course(self, m): - register_uris({'page': ['revert_to_revision']}, m) + register_uris({"page": ["revert_to_revision"]}, m) revision = self.page_course.revert_to_revision(3) self.assertIsInstance(revision, PageRevision) def test_revert_to_revision_group(self, m): - register_uris({'page': ['revert_to_revision_group']}, m) + register_uris({"page": ["revert_to_revision_group"]}, m) revision = self.page_group.revert_to_revision(3) @@ -124,30 +124,30 @@ def test_parent_id_group(self, m): self.assertEqual(self.page_group.parent_id, 1) def test_parent_id_no_id(self, m): - page = Page(self.canvas._Canvas__requester, {'url': 'my-url'}) + page = Page(self.canvas._Canvas__requester, {"url": "my-url"}) with self.assertRaises(ValueError): page.parent_id # parent_type def test_parent_type_course(self, m): - self.assertEqual(self.page_course.parent_type, 'course') + self.assertEqual(self.page_course.parent_type, "course") def test_parent_type_group(self, m): - self.assertEqual(self.page_group.parent_type, 'group') + self.assertEqual(self.page_group.parent_type, "group") def test_parent_type_no_id(self, m): - page = Page(self.canvas._Canvas__requester, {'url': 'my-url'}) + page = Page(self.canvas._Canvas__requester, {"url": "my-url"}) with self.assertRaises(ValueError): page.parent_type # get_parent() def test_get_parent_course(self, m): - register_uris({'course': ['get_by_id']}, m) + register_uris({"course": ["get_by_id"]}, m) self.assertIsInstance(self.page_course.get_parent(), Course) def test_get_parent_group(self, m): - register_uris({'group': ['get_by_id']}, m) + register_uris({"group": ["get_by_id"]}, m) self.assertIsInstance(self.page_group.get_parent(), Group) @@ -159,16 +159,16 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_page'], - 'group': ['get_by_id', 'pages_get_page'], - 'page': ['get_latest_rev_by_id', 'get_latest_rev_by_id_group'], + "course": ["get_by_id", "get_page"], + "group": ["get_by_id", "pages_get_page"], + "page": ["get_latest_rev_by_id", "get_latest_rev_by_id_group"], } register_uris(requires, m) self.course = self.canvas.get_course(1) self.group = self.canvas.get_group(1) - self.page_course = self.course.get_page('my-url') - self.page_group = self.group.get_page('my-url') + self.page_course = self.course.get_page("my-url") + self.page_group = self.group.get_page("my-url") self.revision = self.page_course.get_revision_by_id(2) self.group_revision = self.page_group.get_revision_by_id(2) @@ -182,29 +182,29 @@ def test_parent_id_course(self, m): self.assertEqual(self.revision.parent_id, 1) def test_parent_id_no_id(self, m): - page = PageRevision(self.canvas._Canvas__requester, {'url': 'my-url'}) + page = PageRevision(self.canvas._Canvas__requester, {"url": "my-url"}) with self.assertRaises(ValueError): page.parent_id # parent_type def test_parent_type_course(self, m): - self.assertEqual(self.page_course.parent_type, 'course') + self.assertEqual(self.page_course.parent_type, "course") def test_parent_type_group(self, m): - self.assertEqual(self.page_group.parent_type, 'group') + self.assertEqual(self.page_group.parent_type, "group") def test_parent_type_no_id(self, m): - page = PageRevision(self.canvas._Canvas__requester, {'url': 'my-url'}) + page = PageRevision(self.canvas._Canvas__requester, {"url": "my-url"}) with self.assertRaises(ValueError): page.parent_type # get_parent() def test_get_parent_course(self, m): - register_uris({'course': ['get_by_id']}, m) + register_uris({"course": ["get_by_id"]}, m) self.assertIsInstance(self.revision.get_parent(), Course) def test_get_parent_group(self, m): - register_uris({'group': ['get_by_id']}, m) + register_uris({"group": ["get_by_id"]}, m) self.assertIsInstance(self.group_revision.get_parent(), Group) diff --git a/tests/test_page_view.py b/tests/test_page_view.py index 04dee047..b253146d 100644 --- a/tests/test_page_view.py +++ b/tests/test_page_view.py @@ -14,7 +14,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'user': ['get_by_id', 'page_views', 'page_views_p2']}, m) + register_uris({"user": ["get_by_id", "page_views", "page_views_p2"]}, m) self.user = self.canvas.get_user(1) pageviews = self.user.get_page_views() diff --git a/tests/test_paginated_list.py b/tests/test_paginated_list.py index 73fa48f8..570faa87 100644 --- a/tests/test_paginated_list.py +++ b/tests/test_paginated_list.py @@ -19,154 +19,154 @@ def setUp(self): # various length lists def test_paginated_list_empty(self, m): - register_uris({'paginated_list': ['empty']}, m) + register_uris({"paginated_list": ["empty"]}, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'empty_list') + pag_list = PaginatedList(User, self.requester, "GET", "empty_list") item_list = [item for item in pag_list] self.assertEqual(len(item_list), 0) def test_paginated_list_single(self, m): - register_uris({'paginated_list': ['single']}, m) + register_uris({"paginated_list": ["single"]}, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'single_item') + pag_list = PaginatedList(User, self.requester, "GET", "single_item") item_list = [item for item in pag_list] self.assertEqual(len(item_list), 1) self.assertIsInstance(item_list[0], User) def test_paginated_list_two_one_page(self, m): - register_uris({'paginated_list': ['2_1_page']}, m) + register_uris({"paginated_list": ["2_1_page"]}, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'two_objects_one_page') + pag_list = PaginatedList(User, self.requester, "GET", "two_objects_one_page") item_list = [item for item in pag_list] self.assertEqual(len(item_list), 2) self.assertIsInstance(item_list[0], User) def test_paginated_list_four_two_pages(self, m): - register_uris({'paginated_list': ['4_2_pages_p1', '4_2_pages_p2']}, m) + register_uris({"paginated_list": ["4_2_pages_p1", "4_2_pages_p2"]}, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'four_objects_two_pages') + pag_list = PaginatedList(User, self.requester, "GET", "four_objects_two_pages") item_list = [item for item in pag_list] self.assertEqual(len(item_list), 4) self.assertIsInstance(item_list[0], User) def test_paginated_list_six_three_pages(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") item_list = [item for item in pag_list] self.assertEqual(len(item_list), 6) self.assertIsInstance(item_list[0], User) # reusing iterator def test_iterator(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") list_1 = [item for item in pag_list] list_2 = [item for item in pag_list] self.assertEqual(list_1, list_2) # get item def test_getitem_first(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") first_item = pag_list[0] self.assertIsInstance(first_item, User) def test_getitem_second_page(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") third_item = pag_list[2] self.assertIsInstance(third_item, User) # slicing def test_slice_beginning(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") first_two_items = pag_list[:2] item_list = [item for item in first_two_items] self.assertEqual(len(item_list), 2) self.assertIsInstance(item_list[0], User) - self.assertTrue(hasattr(item_list[0], 'id')) - self.assertEqual(item_list[0].id, '1') + self.assertTrue(hasattr(item_list[0], "id")) + self.assertEqual(item_list[0].id, "1") def test_slice_middle(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") middle_two_items = pag_list[2:4] item_list = [item for item in middle_two_items] self.assertEqual(len(item_list), 2) self.assertIsInstance(item_list[0], User) - self.assertTrue(hasattr(item_list[0], 'id')) - self.assertEqual(item_list[0].id, '3') + self.assertTrue(hasattr(item_list[0], "id")) + self.assertEqual(item_list[0].id, "3") def test_slice_end(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") middle_two_items = pag_list[4:6] item_list = [item for item in middle_two_items] self.assertEqual(len(item_list), 2) self.assertIsInstance(item_list[0], User) - self.assertTrue(hasattr(item_list[0], 'id')) - self.assertEqual(item_list[0].id, '5') + self.assertTrue(hasattr(item_list[0], "id")) + self.assertEqual(item_list[0].id, "5") def test_slice_oversize(self, m): - requires = {'paginated_list': ['4_2_pages_p1', '4_2_pages_p2']} + requires = {"paginated_list": ["4_2_pages_p1", "4_2_pages_p2"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'four_objects_two_pages') + pag_list = PaginatedList(User, self.requester, "GET", "four_objects_two_pages") oversized_slice = pag_list[0:10] item_list = [item for item in oversized_slice] self.assertEqual(len(item_list), 4) def test_slice_out_of_bounds(self, m): - requires = {'paginated_list': ['4_2_pages_p1', '4_2_pages_p2']} + requires = {"paginated_list": ["4_2_pages_p1", "4_2_pages_p2"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'four_objects_two_pages') + pag_list = PaginatedList(User, self.requester, "GET", "four_objects_two_pages") out_of_bounds = pag_list[4:5] item_list = [item for item in out_of_bounds] self.assertEqual(len(item_list), 0) # __repr__() def test_repr(self, m): - requires = {'paginated_list': ['6_3_pages_p1', '6_3_pages_p2', '6_3_pages_p3']} + requires = {"paginated_list": ["6_3_pages_p1", "6_3_pages_p2", "6_3_pages_p3"]} register_uris(requires, m) - pag_list = PaginatedList(User, self.requester, 'GET', 'six_objects_three_pages') - self.assertEqual(pag_list.__repr__(), '') + pag_list = PaginatedList(User, self.requester, "GET", "six_objects_three_pages") + self.assertEqual(pag_list.__repr__(), "") def test_root_element_incorrect(self, m): - register_uris({'account': ['get_enrollment_terms']}, m) + register_uris({"account": ["get_enrollment_terms"]}, m) pag_list = PaginatedList( - EnrollmentTerm, self.requester, 'GET', 'accounts/1/terms', _root='wrong' + EnrollmentTerm, self.requester, "GET", "accounts/1/terms", _root="wrong" ) with self.assertRaises(ValueError): pag_list[0] def test_root_element(self, m): - register_uris({'account': ['get_enrollment_terms']}, m) + register_uris({"account": ["get_enrollment_terms"]}, m) pag_list = PaginatedList( EnrollmentTerm, self.requester, - 'GET', - 'accounts/1/terms', - _root='enrollment_terms', + "GET", + "accounts/1/terms", + _root="enrollment_terms", ) self.assertIsInstance(pag_list[0], EnrollmentTerm) diff --git a/tests/test_peer_review.py b/tests/test_peer_review.py index 1cddb71c..9217efaa 100644 --- a/tests/test_peer_review.py +++ b/tests/test_peer_review.py @@ -15,8 +15,8 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'get_assignment_by_id'], - 'assignment': ['list_peer_reviews'], + "course": ["get_by_id", "get_assignment_by_id"], + "assignment": ["list_peer_reviews"], } register_uris(requires, m) diff --git a/tests/test_planner.py b/tests/test_planner.py index d87829b3..5890c659 100644 --- a/tests/test_planner.py +++ b/tests/test_planner.py @@ -16,7 +16,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'planner': ['single_planner_note']}, m) + register_uris({"planner": ["single_planner_note"]}, m) self.note = self.canvas.get_planner_note(1) # __str__() @@ -26,30 +26,30 @@ def test__str__(self, m): # get_planner_notes() def test_get_planner_notes(self, m): - register_uris({'planner': ['multiple_planner_notes']}, m) + register_uris({"planner": ["multiple_planner_notes"]}, m) notes = self.canvas.get_planner_notes() self.assertEqual(len(list(notes)), 2) - self.assertEqual(notes[0].title, 'Breathe') + self.assertEqual(notes[0].title, "Breathe") self.assertIsInstance(notes[0], PlannerNote) - self.assertTrue(hasattr(notes[1], 'todo_date')) + self.assertTrue(hasattr(notes[1], "todo_date")) # get_planner_note() def test_get_planner_note(self, m): - register_uris({'planner': ['single_planner_note']}, m) + register_uris({"planner": ["single_planner_note"]}, m) note_by_id = self.canvas.get_planner_note(1) self.assertIsInstance(note_by_id, PlannerNote) self.assertEqual(note_by_id.id, 1) - self.assertEqual(note_by_id.title, 'Take a nap') - self.assertEqual(note_by_id.todo_date, '2018-05-09T10:12:00Z') + self.assertEqual(note_by_id.title, "Take a nap") + self.assertEqual(note_by_id.todo_date, "2018-05-09T10:12:00Z") note_by_obj = self.canvas.get_planner_note(note_by_id) self.assertIsInstance(note_by_obj, PlannerNote) self.assertEqual(note_by_obj.id, 1) - self.assertEqual(note_by_obj.title, 'Take a nap') - self.assertEqual(note_by_obj.todo_date, '2018-05-09T10:12:00Z') + self.assertEqual(note_by_obj.title, "Take a nap") + self.assertEqual(note_by_obj.todo_date, "2018-05-09T10:12:00Z") # get_planner_note() def test_get_planner_note_fail(self, m): @@ -58,43 +58,43 @@ def test_get_planner_note_fail(self, m): # create_planner_note() def test_create_planner_note(self, m): - register_uris({'planner': ['create_planner_note']}, m) + register_uris({"planner": ["create_planner_note"]}, m) - note_create_1 = self.canvas.create_planner_note(title='Perform photosynthesis') + note_create_1 = self.canvas.create_planner_note(title="Perform photosynthesis") self.assertIsInstance(note_create_1, PlannerNote) - self.assertTrue(hasattr(note_create_1, 'title')) + self.assertTrue(hasattr(note_create_1, "title")) note_create_2 = self.canvas.create_planner_note( - title='Perform photosynthesis', todo_date='2019-09-05T12:10:30Z' + title="Perform photosynthesis", todo_date="2019-09-05T12:10:30Z" ) self.assertIsInstance(note_create_2, PlannerNote) - self.assertTrue(hasattr(note_create_2, 'title')) - self.assertEqual(note_create_2.todo_date, '2019-09-05T12:10:30Z') + self.assertTrue(hasattr(note_create_2, "title")) + self.assertEqual(note_create_2.todo_date, "2019-09-05T12:10:30Z") # update() def test_update(self, m): - register_uris({'planner': ['update_planner_note']}, m) + register_uris({"planner": ["update_planner_note"]}, m) - note_update_1 = self.note.update(title='Go to restroom') + note_update_1 = self.note.update(title="Go to restroom") self.assertIsInstance(note_update_1, PlannerNote) - self.assertEqual(note_update_1.title, 'Go to restroom') + self.assertEqual(note_update_1.title, "Go to restroom") note_update_2 = self.note.update( - title='Go to restroom', todo_date='2020-01-07T15:16:18Z' + title="Go to restroom", todo_date="2020-01-07T15:16:18Z" ) self.assertIsInstance(note_update_2, PlannerNote) - self.assertEqual(note_update_2.title, 'Go to restroom') - self.assertEqual(note_update_2.todo_date, '2020-01-07T15:16:18Z') + self.assertEqual(note_update_2.title, "Go to restroom") + self.assertEqual(note_update_2.todo_date, "2020-01-07T15:16:18Z") # delete_poll() def test_delete(self, m): - register_uris({'planner': ['delete_planner_note']}, m) + register_uris({"planner": ["delete_planner_note"]}, m) note_delete = self.note.delete() self.assertIsInstance(note_delete, PlannerNote) self.assertEqual(note_delete.id, 1) - self.assertEqual(note_delete.title, 'Go to restroom') - self.assertEqual(note_delete.todo_date, '2020-01-07T15:16:18Z') + self.assertEqual(note_delete.title, "Go to restroom") + self.assertEqual(note_delete.todo_date, "2020-01-07T15:16:18Z") @requests_mock.Mocker() @@ -103,7 +103,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'planner': ['single_planner_override']}, m) + register_uris({"planner": ["single_planner_override"]}, m) self.override = self.canvas.get_planner_override(1) # __str__() @@ -113,18 +113,18 @@ def test__str__(self, m): # get_planner_overrides() def test_get_planner_overrides(self, m): - register_uris({'planner': ['multiple_planner_overrides']}, m) + register_uris({"planner": ["multiple_planner_overrides"]}, m) overrides = self.canvas.get_planner_overrides() self.assertEqual(len(list(overrides)), 2) self.assertEqual(overrides[0].plannable_id, 22) self.assertIsInstance(overrides[0], PlannerOverride) - self.assertTrue(hasattr(overrides[1], 'marked_complete')) + self.assertTrue(hasattr(overrides[1], "marked_complete")) # get_planner_override() def test_get_planner_override(self, m): - register_uris({'planner': ['single_planner_override']}, m) + register_uris({"planner": ["single_planner_override"]}, m) override_by_id = self.canvas.get_planner_override(1) self.assertIsInstance(override_by_id, PlannerOverride) @@ -144,13 +144,13 @@ def test_get_planner_override_fail(self, m): # create_planner_override() def test_create_planner_override(self, m): - register_uris({'planner': ['create_planner_override']}, m) + register_uris({"planner": ["create_planner_override"]}, m) override_create = self.canvas.create_planner_override( - plannable_type='assignment', plannable_id=69 + plannable_type="assignment", plannable_id=69 ) self.assertIsInstance(override_create, PlannerOverride) - self.assertTrue(hasattr(override_create, 'plannable_id')) + self.assertTrue(hasattr(override_create, "plannable_id")) # create_planner_override() def test_create_planner_override_fail_1(self, m): @@ -161,12 +161,12 @@ def test_create_planner_override_fail_1(self, m): def test_create_planner_override_fail_2(self, m): with self.assertRaises(RequiredFieldMissing): self.canvas.create_planner_override( - plannable_type='assignment', plannable_id=None + plannable_type="assignment", plannable_id=None ) # update() def test_update(self, m): - register_uris({'planner': ['update_planner_override']}, m) + register_uris({"planner": ["update_planner_override"]}, m) override_update = self.override.update(marked_complete=True) self.assertIsInstance(override_update, PlannerOverride) @@ -174,7 +174,7 @@ def test_update(self, m): # delete_poll() def test_delete(self, m): - register_uris({'planner': ['delete_planner_override']}, m) + register_uris({"planner": ["delete_planner_override"]}, m) override_delete = self.override.delete() self.assertIsInstance(override_delete, PlannerOverride) diff --git a/tests/test_poll.py b/tests/test_poll.py index 9282b5c5..1fbd7811 100644 --- a/tests/test_poll.py +++ b/tests/test_poll.py @@ -16,7 +16,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'poll': ['get_poll']}, m) + register_uris({"poll": ["get_poll"]}, m) self.poll = self.canvas.get_poll(1) # __str__() @@ -26,7 +26,7 @@ def test__str__(self, m): # get_polls() def test_get_polls(self, m): - register_uris({'poll': ['get_polls']}, m) + register_uris({"poll": ["get_polls"]}, m) polls_list = self.canvas.get_polls() @@ -35,34 +35,34 @@ def test_get_polls(self, m): # get_poll() def test_get_poll(self, m): - register_uris({'poll': ['get_poll']}, m) + register_uris({"poll": ["get_poll"]}, m) poll_by_id = self.canvas.get_poll(1) self.assertIsInstance(poll_by_id, Poll) - self.assertEqual(poll_by_id.question, 'Is this a question?') - self.assertEqual(poll_by_id.description, 'This is a test.') - self.assertEqual(poll_by_id.created_at, '2014-01-07T13:10:19Z') + self.assertEqual(poll_by_id.question, "Is this a question?") + self.assertEqual(poll_by_id.description, "This is a test.") + self.assertEqual(poll_by_id.created_at, "2014-01-07T13:10:19Z") poll_by_obj = self.canvas.get_poll(poll_by_id) self.assertIsInstance(poll_by_obj, Poll) - self.assertEqual(poll_by_obj.question, 'Is this a question?') - self.assertEqual(poll_by_obj.description, 'This is a test.') - self.assertEqual(poll_by_obj.created_at, '2014-01-07T13:10:19Z') + self.assertEqual(poll_by_obj.question, "Is this a question?") + self.assertEqual(poll_by_obj.description, "This is a test.") + self.assertEqual(poll_by_obj.created_at, "2014-01-07T13:10:19Z") # create_poll() def test_create_poll(self, m): - register_uris({'poll': ['create_poll']}, m) + register_uris({"poll": ["create_poll"]}, m) - new_poll_q = self.canvas.create_poll([{'question': 'Is this a question?'}]) + new_poll_q = self.canvas.create_poll([{"question": "Is this a question?"}]) self.assertIsInstance(new_poll_q, Poll) - self.assertTrue(hasattr(new_poll_q, 'question')) + self.assertTrue(hasattr(new_poll_q, "question")) new_poll_q_d = self.canvas.create_poll( - [{'question': 'Is this a question?'}, {'description': 'This is a test.'}] + [{"question": "Is this a question?"}, {"description": "This is a test."}] ) self.assertIsInstance(new_poll_q_d, Poll) - self.assertTrue(hasattr(new_poll_q_d, 'question')) - self.assertTrue(hasattr(new_poll_q_d, 'description')) + self.assertTrue(hasattr(new_poll_q_d, "question")) + self.assertTrue(hasattr(new_poll_q_d, "description")) # create_poll() def test_create_poll_fail(self, m): @@ -71,21 +71,21 @@ def test_create_poll_fail(self, m): # update() def test_update(self, m): - register_uris({'poll': ['update']}, m) + register_uris({"poll": ["update"]}, m) - updated_poll_q = self.poll.update([{'question': 'Is this not a question?'}]) + updated_poll_q = self.poll.update([{"question": "Is this not a question?"}]) self.assertIsInstance(updated_poll_q, Poll) - self.assertEqual(updated_poll_q.question, 'Is this not a question?') + self.assertEqual(updated_poll_q.question, "Is this not a question?") updated_poll_q_and_d = self.poll.update( [ - {'question': 'Is this not a question?'}, - {'description': 'This is not a test.'}, + {"question": "Is this not a question?"}, + {"description": "This is not a test."}, ] ) self.assertIsInstance(updated_poll_q_and_d, Poll) - self.assertEqual(updated_poll_q_and_d.question, 'Is this not a question?') - self.assertEqual(updated_poll_q_and_d.description, 'This is not a test.') + self.assertEqual(updated_poll_q_and_d.question, "Is this not a question?") + self.assertEqual(updated_poll_q_and_d.description, "This is not a test.") # update def test_update_fail(self, m): @@ -94,7 +94,7 @@ def test_update_fail(self, m): # delete_poll() def test_delete(self, m): - register_uris({'poll': ['delete']}, m) + register_uris({"poll": ["delete"]}, m) result = self.poll.delete() self.assertTrue(result) diff --git a/tests/test_poll_choice.py b/tests/test_poll_choice.py index b6b40e90..cdf5bed1 100644 --- a/tests/test_poll_choice.py +++ b/tests/test_poll_choice.py @@ -16,7 +16,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = {'poll_choice': ['get_choice'], 'poll': ['get_poll']} + requires = {"poll_choice": ["get_choice"], "poll": ["get_poll"]} register_uris(requires, m) self.poll = self.canvas.get_poll(1) self.poll.poll_choice = self.poll.get_choice(1) @@ -28,7 +28,7 @@ def test__str__(self, m): # get_choices() def test_get_choices(self, m): - register_uris({'poll_choice': ['get_choices']}, m) + register_uris({"poll_choice": ["get_choices"]}, m) choices_list = self.poll.get_choices() @@ -37,49 +37,49 @@ def test_get_choices(self, m): # get_choice() def test_get_choice(self, m): - register_uris({'poll_choice': ['get_choice']}, m) + register_uris({"poll_choice": ["get_choice"]}, m) choice_by_id = self.poll.get_choice(1) self.assertIsInstance(choice_by_id, PollChoice) self.assertTrue(choice_by_id.is_correct) - self.assertEqual(choice_by_id.text, 'Example choice') + self.assertEqual(choice_by_id.text, "Example choice") self.assertEqual(choice_by_id.position, 1) choice_by_obj = self.poll.get_choice(choice_by_id) self.assertIsInstance(choice_by_obj, PollChoice) self.assertTrue(choice_by_obj.is_correct) - self.assertEqual(choice_by_obj.text, 'Example choice') + self.assertEqual(choice_by_obj.text, "Example choice") self.assertEqual(choice_by_obj.position, 1) # create_choice() def test_create_choice(self, m): - register_uris({'poll_choice': ['create_choice']}, m) + register_uris({"poll_choice": ["create_choice"]}, m) - new_choice_t = self.poll.create_choice([{'text': 'Example choice'}]) + new_choice_t = self.poll.create_choice([{"text": "Example choice"}]) self.assertIsInstance(new_choice_t, PollChoice) - self.assertTrue(hasattr(new_choice_t, 'text')) + self.assertTrue(hasattr(new_choice_t, "text")) new_choice_t_ic = self.poll.create_choice( - [{'text': 'Example choice'}, {'is_correct': True}] + [{"text": "Example choice"}, {"is_correct": True}] ) self.assertIsInstance(new_choice_t_ic, PollChoice) - self.assertTrue(hasattr(new_choice_t_ic, 'text')) - self.assertTrue(hasattr(new_choice_t_ic, 'is_correct')) + self.assertTrue(hasattr(new_choice_t_ic, "text")) + self.assertTrue(hasattr(new_choice_t_ic, "is_correct")) new_choice_t_p = self.poll.create_choice( - [{'text': 'Example choice'}, {'position': 1}] + [{"text": "Example choice"}, {"position": 1}] ) self.assertIsInstance(new_choice_t_p, PollChoice) - self.assertTrue(hasattr(new_choice_t_p, 'text')) - self.assertTrue(hasattr(new_choice_t_p, 'position')) + self.assertTrue(hasattr(new_choice_t_p, "text")) + self.assertTrue(hasattr(new_choice_t_p, "position")) new_choice_t_ic_p = self.poll.create_choice( - [{'text': 'Example choice'}, {'is_correct': True}, {'position': 1}] + [{"text": "Example choice"}, {"is_correct": True}, {"position": 1}] ) self.assertIsInstance(new_choice_t_ic_p, PollChoice) - self.assertTrue(hasattr(new_choice_t_ic_p, 'text')) - self.assertTrue(hasattr(new_choice_t_ic_p, 'is_correct')) - self.assertTrue(hasattr(new_choice_t_ic_p, 'position')) + self.assertTrue(hasattr(new_choice_t_ic_p, "text")) + self.assertTrue(hasattr(new_choice_t_ic_p, "is_correct")) + self.assertTrue(hasattr(new_choice_t_ic_p, "position")) # create_choice() def test_create_choice_fail(self, m): @@ -88,31 +88,31 @@ def test_create_choice_fail(self, m): # update() def test_update(self, m): - register_uris({'poll_choice': ['update']}, m) + register_uris({"poll_choice": ["update"]}, m) - updated_choice_t = self.poll.poll_choice.update([{'text': 'Changed example'}]) + updated_choice_t = self.poll.poll_choice.update([{"text": "Changed example"}]) self.assertIsInstance(updated_choice_t, PollChoice) - self.assertEqual(updated_choice_t.text, 'Changed example') + self.assertEqual(updated_choice_t.text, "Changed example") updated_choice_t_ic = self.poll.poll_choice.update( - [{'text': 'Changed example'}, {'is_correct': False}] + [{"text": "Changed example"}, {"is_correct": False}] ) self.assertIsInstance(updated_choice_t_ic, PollChoice) - self.assertEqual(updated_choice_t_ic.text, 'Changed example') + self.assertEqual(updated_choice_t_ic.text, "Changed example") self.assertFalse(updated_choice_t_ic.is_correct) updated_choice_t_p = self.poll.poll_choice.update( - [{'text': 'Changed example'}, {'position': 2}] + [{"text": "Changed example"}, {"position": 2}] ) self.assertIsInstance(updated_choice_t_p, PollChoice) - self.assertEqual(updated_choice_t_p.text, 'Changed example') + self.assertEqual(updated_choice_t_p.text, "Changed example") self.assertEqual(updated_choice_t_p.position, 2) updated_choice_t_ic_p = self.poll.poll_choice.update( - [{'text': 'Changed example'}, {'is_correct': False}, {'position': 2}] + [{"text": "Changed example"}, {"is_correct": False}, {"position": 2}] ) self.assertIsInstance(updated_choice_t_ic_p, PollChoice) - self.assertEqual(updated_choice_t_ic_p.text, 'Changed example') + self.assertEqual(updated_choice_t_ic_p.text, "Changed example") self.assertFalse(updated_choice_t_ic.is_correct) self.assertEqual(updated_choice_t_p.position, 2) @@ -123,7 +123,7 @@ def test_update_choice_fail(self, m): # delete() def test_delete(self, m): - register_uris({'poll_choice': ['delete']}, m) + register_uris({"poll_choice": ["delete"]}, m) result = self.poll.poll_choice.delete() self.assertTrue(result) diff --git a/tests/test_poll_session.py b/tests/test_poll_session.py index 35178620..4790fb7e 100644 --- a/tests/test_poll_session.py +++ b/tests/test_poll_session.py @@ -17,9 +17,9 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'user': ['get_by_id'], - 'poll': ['get_poll'], - 'poll_session': ['get_session'], + "user": ["get_by_id"], + "poll": ["get_poll"], + "poll_session": ["get_session"], } register_uris(requires, m) @@ -34,7 +34,7 @@ def test__str__(self, m): # get_sessions() def test_get_sessions(self, m): - register_uris({'poll_session': ['get_sessions']}, m) + register_uris({"poll_session": ["get_sessions"]}, m) session_list = self.poll.get_sessions() @@ -43,13 +43,13 @@ def test_get_sessions(self, m): # get_session() def test_get_session(self, m): - register_uris({'poll_session': ['get_session']}, m) + register_uris({"poll_session": ["get_session"]}, m) choice_by_id = self.poll.get_session(1) self.assertIsInstance(choice_by_id, PollSession) self.assertTrue(choice_by_id.is_published) self.assertFalse(choice_by_id.has_public_results) - self.assertEqual(choice_by_id.created_at, '2014-01-07T15:16:18Z') + self.assertEqual(choice_by_id.created_at, "2014-01-07T15:16:18Z") self.assertEqual(len(choice_by_id.results), 3) self.assertEqual(choice_by_id.poll_submissions, None) @@ -57,34 +57,34 @@ def test_get_session(self, m): self.assertIsInstance(choice_by_obj, PollSession) self.assertTrue(choice_by_obj.is_published) self.assertFalse(choice_by_obj.has_public_results) - self.assertEqual(choice_by_obj.created_at, '2014-01-07T15:16:18Z') + self.assertEqual(choice_by_obj.created_at, "2014-01-07T15:16:18Z") self.assertEqual(len(choice_by_obj.results), 3) self.assertEqual(choice_by_obj.poll_submissions, None) # create_session() def test_create_session(self, m): - register_uris({'poll_session': ['create_session']}, m) + register_uris({"poll_session": ["create_session"]}, m) - new_session_cid = self.poll.create_session([{'course_id': 1}]) + new_session_cid = self.poll.create_session([{"course_id": 1}]) self.assertIsInstance(new_session_cid, PollSession) self.assertEqual(new_session_cid.course_id, 1) new_session_cid_sid = self.poll.create_session( - [{'course_id': 1}, {'course_section_id': 1}] + [{"course_id": 1}, {"course_section_id": 1}] ) self.assertIsInstance(new_session_cid_sid, PollSession) self.assertEqual(new_session_cid_sid.course_id, 1) self.assertEqual(new_session_cid_sid.course_section_id, 1) new_session_cid_hpr = self.poll.create_session( - [{'course_id': 1}, {'has_public_results': False}] + [{"course_id": 1}, {"has_public_results": False}] ) self.assertIsInstance(new_session_cid_hpr, PollSession) self.assertEqual(new_session_cid_hpr.course_id, 1) self.assertFalse(new_session_cid_hpr.has_public_results) new_session_cid_sid_hpr = self.poll.create_session( - [{'course_id': 1}, {'course_section_id': 1}, {'has_public_results': False}] + [{"course_id": 1}, {"course_section_id": 1}, {"has_public_results": False}] ) self.assertIsInstance(new_session_cid_sid_hpr, PollSession) self.assertEqual(new_session_cid_sid_hpr.course_id, 1) @@ -98,28 +98,28 @@ def test_create_session_fail(self, m): # update() def test_update(self, m): - register_uris({'poll_session': ['update']}, m) + register_uris({"poll_session": ["update"]}, m) - updated_session_cid = self.poll.poll_session.update([{'course_id': 2}]) + updated_session_cid = self.poll.poll_session.update([{"course_id": 2}]) self.assertIsInstance(updated_session_cid, PollSession) self.assertEqual(updated_session_cid.course_id, 2) updated_session_cid_sid = self.poll.poll_session.update( - [{'course_id': 2}, {'course_section_id': 2}] + [{"course_id": 2}, {"course_section_id": 2}] ) self.assertIsInstance(updated_session_cid_sid, PollSession) self.assertEqual(updated_session_cid_sid.course_id, 2) self.assertEqual(updated_session_cid_sid.course_section_id, 2) updated_session_cid_hpr = self.poll.poll_session.update( - [{'course_id': 2}, {'has_public_results': True}] + [{"course_id": 2}, {"has_public_results": True}] ) self.assertIsInstance(updated_session_cid_hpr, PollSession) self.assertEqual(updated_session_cid_hpr.course_id, 2) self.assertTrue(updated_session_cid_hpr.has_public_results) updated_session_cid_sid_hpr = self.poll.poll_session.update( - [{'course_id': 2}, {'course_section_id': 2}, {'has_public_results': True}] + [{"course_id": 2}, {"course_section_id": 2}, {"has_public_results": True}] ) self.assertIsInstance(updated_session_cid_sid_hpr, PollSession) self.assertEqual(updated_session_cid_sid_hpr.course_id, 2) @@ -133,14 +133,14 @@ def test_update_fail(self, m): # delete() def test_delete(self, m): - register_uris({'poll_session': ['delete']}, m) + register_uris({"poll_session": ["delete"]}, m) result = self.poll.poll_session.delete() self.assertTrue(result) # open() def test_open(self, m): - register_uris({'poll_session': ['open']}, m) + register_uris({"poll_session": ["open"]}, m) opened_session = self.poll.poll_session.open() @@ -149,7 +149,7 @@ def test_open(self, m): # close() def test_close(self, m): - register_uris({'poll_session': ['close']}, m) + register_uris({"poll_session": ["close"]}, m) closed_session = self.poll.poll_session.close() @@ -158,7 +158,7 @@ def test_close(self, m): # get_open_poll_sessions() def test_get_open_poll_sessions(self, m): - register_uris({'poll_session': ['get_open_poll_sessions']}, m) + register_uris({"poll_session": ["get_open_poll_sessions"]}, m) open_sessions = self.user.get_open_poll_sessions() @@ -170,7 +170,7 @@ def test_get_open_poll_sessions(self, m): # get_closed_poll_sessions() def test_get_closed_poll_sessions(self, m): - register_uris({'poll_session': ['get_closed_poll_sessions']}, m) + register_uris({"poll_session": ["get_closed_poll_sessions"]}, m) closed_sessions = self.user.get_closed_poll_sessions() diff --git a/tests/test_poll_submission.py b/tests/test_poll_submission.py index 27bed326..d11a3559 100644 --- a/tests/test_poll_submission.py +++ b/tests/test_poll_submission.py @@ -17,9 +17,9 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'poll': ['get_poll'], - 'poll_session': ['get_session'], - 'poll_submission': ['get_submission'], + "poll": ["get_poll"], + "poll_session": ["get_session"], + "poll_submission": ["get_submission"], } register_uris(requires, m) @@ -36,28 +36,28 @@ def test__str__(self, m): # get_submission() def test_get_submission(self, m): - register_uris({'poll_submission': ['get_submission']}, m) + register_uris({"poll_submission": ["get_submission"]}, m) choice_by_id = self.poll.poll_session.get_submission(1) self.assertIsInstance(choice_by_id, PollSubmission) - self.assertTrue(hasattr(choice_by_id, 'id')) - self.assertTrue(hasattr(choice_by_id, 'poll_choice_id')) - self.assertTrue(hasattr(choice_by_id, 'user_id')) - self.assertTrue(hasattr(choice_by_id, 'created_at')) + self.assertTrue(hasattr(choice_by_id, "id")) + self.assertTrue(hasattr(choice_by_id, "poll_choice_id")) + self.assertTrue(hasattr(choice_by_id, "user_id")) + self.assertTrue(hasattr(choice_by_id, "created_at")) choice_by_obj = self.poll.poll_session.get_submission(choice_by_id) self.assertIsInstance(choice_by_obj, PollSubmission) - self.assertTrue(hasattr(choice_by_obj, 'id')) - self.assertTrue(hasattr(choice_by_obj, 'poll_choice_id')) - self.assertTrue(hasattr(choice_by_obj, 'user_id')) - self.assertTrue(hasattr(choice_by_obj, 'created_at')) + self.assertTrue(hasattr(choice_by_obj, "id")) + self.assertTrue(hasattr(choice_by_obj, "poll_choice_id")) + self.assertTrue(hasattr(choice_by_obj, "user_id")) + self.assertTrue(hasattr(choice_by_obj, "created_at")) # create_submission() def test_create_submission(self, m): - register_uris({'poll_submission': ['create_submission']}, m) + register_uris({"poll_submission": ["create_submission"]}, m) new_submission = self.poll.poll_session.create_submission( - [{'poll_choice_id': 1}] + [{"poll_choice_id": 1}] ) self.assertIsInstance(new_submission, PollSubmission) self.assertEqual(new_submission.poll_choice_id, 1) diff --git a/tests/test_progress.py b/tests/test_progress.py index b96a2d4e..b2fb9304 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -16,8 +16,8 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'course': ['get_by_id', 'create_group_category'], - 'group': ['category_assign_members_false'], + "course": ["get_by_id", "create_group_category"], + "group": ["category_assign_members_false"], } register_uris(requires, m) @@ -33,7 +33,7 @@ def test__str__(self, m): # query() def test_query(self, m): - register_uris({'progress': ['progress_query']}, m) + register_uris({"progress": ["progress_query"]}, m) response = self.progress.query() self.assertIsInstance(response, Progress) diff --git a/tests/test_quiz_group.py b/tests/test_quiz_group.py index 490fc527..2ae601d6 100644 --- a/tests/test_quiz_group.py +++ b/tests/test_quiz_group.py @@ -16,7 +16,7 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( - {'course': ['get_by_id'], 'quiz': ['get_by_id', 'get_quiz_group']}, m + {"course": ["get_by_id"], "quiz": ["get_by_id", "get_quiz_group"]}, m ) self.course = self.canvas.get_course(1) @@ -29,9 +29,9 @@ def test__str__(self, m): # update_question_group() def test_update(self, m): - register_uris({'quiz_group': ['update']}, m) + register_uris({"quiz_group": ["update"]}, m) - quiz_group = [{'name': 'Test Group', 'pick_count': 1, 'question_points': 2}] + quiz_group = [{"name": "Test Group", "pick_count": 1, "question_points": 2}] result = self.quiz_group.update(1, quiz_group) self.assertIsInstance(result, bool) @@ -39,14 +39,14 @@ def test_update(self, m): self.assertEqual(self.quiz_group.id, 1) self.assertEqual(self.quiz_group.quiz_id, 1) - self.assertEqual(self.quiz_group.name, quiz_group[0].get('name')) - self.assertEqual(self.quiz_group.pick_count, quiz_group[0].get('pick_count')) + self.assertEqual(self.quiz_group.name, quiz_group[0].get("name")) + self.assertEqual(self.quiz_group.pick_count, quiz_group[0].get("pick_count")) self.assertEqual( - self.quiz_group.question_points, quiz_group[0].get('question_points') + self.quiz_group.question_points, quiz_group[0].get("question_points") ) def test_update_empty_list(self, m): - register_uris({'quiz_group': ['update']}, m) + register_uris({"quiz_group": ["update"]}, m) quiz_group = [] @@ -54,7 +54,7 @@ def test_update_empty_list(self, m): self.quiz_group.update(1, quiz_group) def test_update_incorrect_param(self, m): - register_uris({'quiz_group': ['update']}, m) + register_uris({"quiz_group": ["update"]}, m) quiz_group = [1] @@ -62,7 +62,7 @@ def test_update_incorrect_param(self, m): self.quiz_group.update(1, quiz_group) def test_update_incorrect_dict(self, m): - register_uris({'quiz_group': ['update']}, m) + register_uris({"quiz_group": ["update"]}, m) quiz_group = [{}] @@ -71,7 +71,7 @@ def test_update_incorrect_dict(self, m): # delete_question_group() def test_delete(self, m): - register_uris({'quiz_group': ['delete']}, m) + register_uris({"quiz_group": ["delete"]}, m) result = self.quiz_group.delete(1) @@ -79,15 +79,15 @@ def test_delete(self, m): # reorder_question_group() def test_reorder_question_group(self, m): - register_uris({'quiz_group': ['reorder_question_group']}, m) + register_uris({"quiz_group": ["reorder_question_group"]}, m) - newOrdering = [{'id': 2}, {'id': 1, 'type': 'question'}] + newOrdering = [{"id": 2}, {"id": 1, "type": "question"}] result = self.quiz_group.reorder_question_group(1, newOrdering) self.assertTrue(result) def test_reorderquestion_group_empty_list(self, m): - register_uris({'quiz_group': ['reorder_question_group']}, m) + register_uris({"quiz_group": ["reorder_question_group"]}, m) order = [] @@ -95,7 +95,7 @@ def test_reorderquestion_group_empty_list(self, m): self.quiz_group.reorder_question_group(1, order) def test_reorderquestion_group_incorrect_param(self, m): - register_uris({'quiz_group': ['reorder_question_group']}, m) + register_uris({"quiz_group": ["reorder_question_group"]}, m) order = [1] @@ -103,7 +103,7 @@ def test_reorderquestion_group_incorrect_param(self, m): self.quiz_group.reorder_question_group(1, order) def test_reorderquestion_group_incorrect_dict(self, m): - register_uris({'quiz_group': ['reorder_question_group']}, m) + register_uris({"quiz_group": ["reorder_question_group"]}, m) order = [{"something": 2}] diff --git a/tests/test_requester.py b/tests/test_requester.py index a1b3a4a1..bd17c116 100644 --- a/tests/test_requester.py +++ b/tests/test_requester.py @@ -27,16 +27,16 @@ def setUp(self): # request() def test_request_get(self, m): - register_uris({'requests': ['get']}, m) + register_uris({"requests": ["get"]}, m) - response = self.requester.request('GET', 'fake_get_request') + response = self.requester.request("GET", "fake_get_request") self.assertEqual(response.status_code, 200) def test_request_get_datetime(self, m): date = datetime.today() def custom_matcher(request): - match_query = 'date={}'.format(quote(date.isoformat()).lower()) + match_query = "date={}".format(quote(date.isoformat()).lower()) if request.query == match_query: resp = requests.Response() resp.status_code = 200 @@ -44,20 +44,20 @@ def custom_matcher(request): m.add_matcher(custom_matcher) - response = self.requester.request('GET', 'test', date=date) + response = self.requester.request("GET", "test", date=date) self.assertEqual(response.status_code, 200) def test_request_post(self, m): - register_uris({'requests': ['post']}, m) + register_uris({"requests": ["post"]}, m) - response = self.requester.request('POST', 'fake_post_request') + response = self.requester.request("POST", "fake_post_request") self.assertEqual(response.status_code, 200) def test_request_post_datetime(self, m): date = datetime.today() def custom_matcher(request): - match_text = 'date={}'.format(quote(date.isoformat())) + match_text = "date={}".format(quote(date.isoformat())) if request.text == match_text: resp = requests.Response() resp.status_code = 200 @@ -65,100 +65,100 @@ def custom_matcher(request): m.add_matcher(custom_matcher) - response = self.requester.request('POST', 'test', date=date) + response = self.requester.request("POST", "test", date=date) self.assertEqual(response.status_code, 200) def test_request_delete(self, m): - register_uris({'requests': ['delete']}, m) + register_uris({"requests": ["delete"]}, m) - response = self.requester.request('DELETE', 'fake_delete_request') + response = self.requester.request("DELETE", "fake_delete_request") self.assertEqual(response.status_code, 200) def test_request_patch(self, m): - register_uris({'requests': ['patch']}, m) + register_uris({"requests": ["patch"]}, m) - response = self.requester.request('PATCH', 'fake_patch_request') + response = self.requester.request("PATCH", "fake_patch_request") self.assertEqual(response.status_code, 200) def test_request_put(self, m): - register_uris({'requests': ['put']}, m) + register_uris({"requests": ["put"]}, m) - response = self.requester.request('PUT', 'fake_put_request') + response = self.requester.request("PUT", "fake_put_request") self.assertEqual(response.status_code, 200) def test_request_cache(self, m): - register_uris({'requests': ['get']}, m) + register_uris({"requests": ["get"]}, m) - response = self.requester.request('GET', 'fake_get_request') + response = self.requester.request("GET", "fake_get_request") self.assertEqual(response, self.requester._cache[0]) def test_request_cache_clear_after_5(self, m): - register_uris({'requests': ['get', 'post']}, m) + register_uris({"requests": ["get", "post"]}, m) for i in range(5): - self.requester.request('GET', 'fake_get_request') + self.requester.request("GET", "fake_get_request") - response = self.requester.request('POST', 'fake_post_request') + response = self.requester.request("POST", "fake_post_request") self.assertLessEqual(len(self.requester._cache), 5) self.assertEqual(response, self.requester._cache[0]) def test_request_lowercase_boolean(self, m): def custom_matcher(request): - if 'test=true' in request.text and 'test2=false' in request.text: + if "test=true" in request.text and "test2=false" in request.text: resp = requests.Response() resp.status_code = 200 return resp m.add_matcher(custom_matcher) - response = self.requester.request('POST', 'test', test=True, test2=False) + response = self.requester.request("POST", "test", test=True, test2=False) self.assertEqual(response.status_code, 200) def test_request_400(self, m): - register_uris({'requests': ['400']}, m) + register_uris({"requests": ["400"]}, m) with self.assertRaises(BadRequest): - self.requester.request('GET', '400') + self.requester.request("GET", "400") def test_request_401_InvalidAccessToken(self, m): - register_uris({'requests': ['401_invalid_access_token']}, m) + register_uris({"requests": ["401_invalid_access_token"]}, m) with self.assertRaises(InvalidAccessToken): - self.requester.request('GET', '401_invalid_access_token') + self.requester.request("GET", "401_invalid_access_token") def test_request_401_Unauthorized(self, m): - register_uris({'requests': ['401_unauthorized']}, m) + register_uris({"requests": ["401_unauthorized"]}, m) with self.assertRaises(Unauthorized): - self.requester.request('GET', '401_unauthorized') + self.requester.request("GET", "401_unauthorized") def test_request_404(self, m): - register_uris({'requests': ['404']}, m) + register_uris({"requests": ["404"]}, m) with self.assertRaises(ResourceDoesNotExist): - self.requester.request('GET', '404') + self.requester.request("GET", "404") def test_request_409(self, m): - register_uris({'requests': ['409']}, m) + register_uris({"requests": ["409"]}, m) with self.assertRaises(Conflict): - self.requester.request('GET', '409') + self.requester.request("GET", "409") def test_request_500(self, m): - register_uris({'requests': ['500']}, m) + register_uris({"requests": ["500"]}, m) with self.assertRaises(CanvasException): - self.requester.request('GET', '500') + self.requester.request("GET", "500") def test_request_generic(self, m): - register_uris({'requests': ['502', '503', 'absurd']}, m) + register_uris({"requests": ["502", "503", "absurd"]}, m) with self.assertRaises(CanvasException): - self.requester.request('GET', '502') + self.requester.request("GET", "502") with self.assertRaises(CanvasException): - self.requester.request('GET', '503') + self.requester.request("GET", "503") with self.assertRaises(CanvasException): - self.requester.request('GET', 'absurd') + self.requester.request("GET", "absurd") diff --git a/tests/test_rubric.py b/tests/test_rubric.py index 8843b9d4..285ee7c8 100644 --- a/tests/test_rubric.py +++ b/tests/test_rubric.py @@ -14,7 +14,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'course': ['get_by_id', 'get_rubric_single']}, m) + register_uris({"course": ["get_by_id", "get_rubric_single"]}, m) self.course = self.canvas.get_course(1) self.rubric = self.course.get_rubric(1) diff --git a/tests/test_section.py b/tests/test_section.py index ccc35704..140adc13 100644 --- a/tests/test_section.py +++ b/tests/test_section.py @@ -21,7 +21,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'section': ['get_by_id']}, m) + register_uris({"section": ["get_by_id"]}, m) self.section = self.canvas.get_section(1) @@ -32,7 +32,7 @@ def test__str__(self, m): # get_assignment_override def test_get_assignment_override(self, m): - register_uris({'assignment': ['override_section_alias']}, m) + register_uris({"assignment": ["override_section_alias"]}, m) override = self.section.get_assignment_override(1) @@ -41,7 +41,7 @@ def test_get_assignment_override(self, m): # get_enrollments() def test_get_enrollments(self, m): - register_uris({'section': ['list_enrollments', 'list_enrollments_2']}, m) + register_uris({"section": ["list_enrollments", "list_enrollments_2"]}, m) enrollments = self.section.get_enrollments() enrollment_list = [enrollment for enrollment in enrollments] @@ -50,7 +50,7 @@ def test_get_enrollments(self, m): self.assertIsInstance(enrollment_list[0], Enrollment) def test_cross_list_section(self, m): - register_uris({'course': ['get_by_id_2'], 'section': ['crosslist_section']}, m) + register_uris({"course": ["get_by_id_2"], "section": ["crosslist_section"]}, m) section_by_id = self.section.cross_list_section(2) self.assertIsInstance(section_by_id, Section) @@ -60,21 +60,21 @@ def test_cross_list_section(self, m): self.assertIsInstance(section_by_obj, Section) def test_decross_list_section(self, m): - register_uris({'section': ['decross_section']}, m) + register_uris({"section": ["decross_section"]}, m) section = self.section.decross_list_section() self.assertIsInstance(section, Section) def test_edit(self, m): - register_uris({'section': ['edit']}, m) + register_uris({"section": ["edit"]}, m) edit = self.section.edit() self.assertIsInstance(edit, Section) def test_delete(self, m): - register_uris({'section': ['delete']}, m) + register_uris({"section": ["delete"]}, m) deleted_section = self.section.delete() @@ -84,21 +84,21 @@ def test_delete(self, m): def test_submit_assignment(self, m): register_uris( { - 'assignment': ['submit'], - 'submission': ['get_by_id_section'], - 'user': ['get_by_id', 'get_user_assignments'], + "assignment": ["submit"], + "submission": ["get_by_id_section"], + "user": ["get_by_id", "get_user_assignments"], }, m, ) assignment_id = 1 sub_type = "online_upload" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} with warnings.catch_warnings(record=True) as warning_list: assignment_by_id = self.section.submit_assignment(assignment_id, sub_dict) self.assertIsInstance(assignment_by_id, Submission) - self.assertTrue(hasattr(assignment_by_id, 'submission_type')) + self.assertTrue(hasattr(assignment_by_id, "submission_type")) self.assertEqual(assignment_by_id.submission_type, sub_type) self.assertEqual(len(warning_list), 1) @@ -107,14 +107,14 @@ def test_submit_assignment(self, m): user_obj = self.canvas.get_user(1) assignments_obj = user_obj.get_assignments(1) sub_type = "online_upload" - sub_dict = {'submission_type': sub_type} + sub_dict = {"submission_type": sub_type} with warnings.catch_warnings(record=True) as warning_list: assignment_by_obj = self.section.submit_assignment( assignments_obj[0], sub_dict ) self.assertIsInstance(assignment_by_obj, Submission) - self.assertTrue(hasattr(assignment_by_obj, 'submission_type')) + self.assertTrue(hasattr(assignment_by_obj, "submission_type")) self.assertEqual(assignment_by_obj.submission_type, sub_type) self.assertEqual(len(warning_list), 1) @@ -131,8 +131,8 @@ def test_subit_assignment_fail(self, m): def test_list_submissions(self, m): register_uris( { - 'submission': ['list_submissions'], - 'user': ['get_by_id', 'get_user_assignments'], + "submission": ["list_submissions"], + "user": ["get_by_id", "get_user_assignments"], }, m, ) @@ -162,7 +162,7 @@ def test_list_submissions(self, m): # list_multiple_submission() def test_list_multiple_submissions(self, m): - register_uris({'section': ['list_multiple_submissions']}, m) + register_uris({"section": ["list_multiple_submissions"]}, m) with warnings.catch_warnings(record=True) as warning_list: submissions = self.section.list_multiple_submissions() @@ -176,7 +176,7 @@ def test_list_multiple_submissions(self, m): # get_multiple_submission() def test_get_multiple_submissions(self, m): - register_uris({'section': ['list_multiple_submissions']}, m) + register_uris({"section": ["list_multiple_submissions"]}, m) submissions = self.section.get_multiple_submissions() submission_list = [submission for submission in submissions] @@ -185,7 +185,7 @@ def test_get_multiple_submissions(self, m): self.assertIsInstance(submission_list[0], Submission) def test_get_multiple_submissions_grouped_true(self, m): - register_uris({'section': ['list_multiple_submissions_grouped']}, m) + register_uris({"section": ["list_multiple_submissions_grouped"]}, m) submissions = self.section.get_multiple_submissions(grouped=True) submission_list = [submission for submission in submissions] @@ -194,7 +194,7 @@ def test_get_multiple_submissions_grouped_true(self, m): self.assertIsInstance(submission_list[0], GroupedSubmission) def test_get_multiple_submissions_grouped_false(self, m): - register_uris({'section': ['list_multiple_submissions']}, m) + register_uris({"section": ["list_multiple_submissions"]}, m) submissions = self.section.get_multiple_submissions(grouped=False) submission_list = [submission for submission in submissions] @@ -204,7 +204,7 @@ def test_get_multiple_submissions_grouped_false(self, m): def test_get_multiple_submissions_grouped_invalid(self, m): with self.assertRaises(ValueError) as cm: - self.section.get_multiple_submissions(grouped='blargh') + self.section.get_multiple_submissions(grouped="blargh") self.assertIn("Parameter `grouped` must", cm.exception.args[0]) @@ -212,8 +212,8 @@ def test_get_multiple_submissions_grouped_invalid(self, m): def test_get_submission(self, m): register_uris( { - 'submission': ['get_by_id_course'], - 'user': ['get_by_id', 'get_user_assignments'], + "submission": ["get_by_id_course"], + "user": ["get_by_id", "get_user_assignments"], }, m, ) @@ -224,7 +224,7 @@ def test_get_submission(self, m): submission_by_id = self.section.get_submission(assignment_id, user_id) self.assertIsInstance(submission_by_id, Submission) - self.assertTrue(hasattr(submission_by_id, 'submission_type')) + self.assertTrue(hasattr(submission_by_id, "submission_type")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -237,7 +237,7 @@ def test_get_submission(self, m): ) self.assertIsInstance(submission_by_obj, Submission) - self.assertTrue(hasattr(submission_by_obj, 'submission_type')) + self.assertTrue(hasattr(submission_by_obj, "submission_type")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -246,8 +246,8 @@ def test_get_submission(self, m): def test_update_submission(self, m): register_uris( { - 'submission': ['get_by_id_section', 'edit'], - 'user': ['get_by_id', 'get_user_assignments'], + "submission": ["get_by_id_section", "edit"], + "user": ["get_by_id", "get_user_assignments"], }, m, ) @@ -256,11 +256,11 @@ def test_update_submission(self, m): user_id = 1 with warnings.catch_warnings(record=True) as warning_list: submission_by_id = self.section.update_submission( - assignment_id, user_id, submission={'excuse': True} + assignment_id, user_id, submission={"excuse": True} ) self.assertIsInstance(submission_by_id, Submission) - self.assertTrue(hasattr(submission_by_id, 'excused')) + self.assertTrue(hasattr(submission_by_id, "excused")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -270,11 +270,11 @@ def test_update_submission(self, m): with warnings.catch_warnings(record=True) as warning_list: submission_by_obj = self.section.update_submission( - assignments_obj[0], user_obj, submission={'excuse': True} + assignments_obj[0], user_obj, submission={"excuse": True} ) self.assertIsInstance(submission_by_obj, Submission) - self.assertTrue(hasattr(submission_by_obj, 'excused')) + self.assertTrue(hasattr(submission_by_obj, "excused")) self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) @@ -283,9 +283,9 @@ def test_update_submission(self, m): def test_mark_submission_as_read(self, m): register_uris( { - 'course': ['mark_submission_as_read'], - 'submission': ['get_by_id_section'], - 'user': ['get_by_id', 'get_user_assignments'], + "course": ["mark_submission_as_read"], + "submission": ["get_by_id_section"], + "user": ["get_by_id", "get_user_assignments"], }, m, ) @@ -318,9 +318,9 @@ def test_mark_submission_as_read(self, m): def test_mark_submission_as_unread(self, m): register_uris( { - 'course': ['mark_submission_as_unread'], - 'submission': ['get_by_id_section'], - 'user': ['get_by_id', 'get_user_assignments'], + "course": ["mark_submission_as_unread"], + "submission": ["get_by_id_section"], + "user": ["get_by_id", "get_user_assignments"], }, m, ) @@ -348,10 +348,10 @@ def test_mark_submission_as_unread(self, m): self.assertEqual(warning_list[-1].category, DeprecationWarning) def test_submissions_bulk_update(self, m): - register_uris({'section': ['update_submissions']}, m) - register_uris({'progress': ['course_progress']}, m) + register_uris({"section": ["update_submissions"]}, m) + register_uris({"progress": ["course_progress"]}, m) progress = self.section.submissions_bulk_update( - grade_data={'1': {'1': {'posted_grade': 97}, '2': {'posted_grade': 98}}} + grade_data={"1": {"1": {"posted_grade": 97}, "2": {"posted_grade": 98}}} ) self.assertIsInstance(progress, Progress) self.assertTrue(progress.context_type == "Course") diff --git a/tests/test_sis_import.py b/tests/test_sis_import.py index 34d2abf6..b5177758 100644 --- a/tests/test_sis_import.py +++ b/tests/test_sis_import.py @@ -17,8 +17,8 @@ def setUp(self): with requests_mock.Mocker() as m: requires = { - 'account': ['get_by_id', 'get_role'], - 'sis_import': ['get_by_id'], + "account": ["get_by_id", "get_role"], + "sis_import": ["get_by_id"], } register_uris(requires, m) @@ -27,7 +27,7 @@ def setUp(self): # abort() def test_abort_sis_import(self, m): - register_uris({'sis_import': ['abort_sis_import']}, m) + register_uris({"sis_import": ["abort_sis_import"]}, m) aborted_sis_import = self.sis_import.abort() @@ -41,11 +41,11 @@ def test_abort_sis_import(self, m): # restore_states() def test_restore_states(self, m): - register_uris({'sis_import': ['restore_sis_import_states']}, m) + register_uris({"sis_import": ["restore_sis_import_states"]}, m) restore_state_progress = self.sis_import.restore_states() self.assertIsInstance(restore_state_progress, Progress) self.assertEqual(restore_state_progress.context_id, self.sis_import.id) - self.assertEqual(restore_state_progress.context_type, 'SisBatch') - self.assertEqual(restore_state_progress.tag, 'sis_batch_state_restore') + self.assertEqual(restore_state_progress.context_type, "SisBatch") + self.assertEqual(restore_state_progress.tag, "sis_batch_state_restore") diff --git a/tests/test_submission.py b/tests/test_submission.py index f3928b11..9daa067a 100644 --- a/tests/test_submission.py +++ b/tests/test_submission.py @@ -20,9 +20,9 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'course': ['get_by_id', 'get_assignment_by_id'], - 'section': ['get_by_id'], - 'submission': ['get_by_id_course', 'get_by_id_section'], + "course": ["get_by_id", "get_assignment_by_id"], + "section": ["get_by_id"], + "submission": ["get_by_id_course", "get_by_id_section"], }, m, ) @@ -45,7 +45,7 @@ def test__str__(self, m): # create_submission_peer_review() def test_create_submission_peer_review(self, m): - register_uris({'submission': ['create_submission_peer_review']}, m) + register_uris({"submission": ["create_submission_peer_review"]}, m) created_peer_review = self.submission_course.create_submission_peer_review(1) @@ -54,7 +54,7 @@ def test_create_submission_peer_review(self, m): # delete_submission_peer_review() def test_delete_submission_peer_review(self, m): - register_uris({'submission': ['delete_submission_peer_review']}, m) + register_uris({"submission": ["delete_submission_peer_review"]}, m) deleted_peer_review = self.submission_course.delete_submission_peer_review(1) @@ -63,19 +63,19 @@ def test_delete_submission_peer_review(self, m): # edit() def test_edit(self, m): - register_uris({'submission': ['edit']}, m) + register_uris({"submission": ["edit"]}, m) - self.assertFalse(hasattr(self.submission_course, 'excused')) + self.assertFalse(hasattr(self.submission_course, "excused")) - self.submission_course.edit(submission={'excuse': True}) + self.submission_course.edit(submission={"excuse": True}) self.assertIsInstance(self.submission_course, Submission) - self.assertTrue(hasattr(self.submission_course, 'excused')) + self.assertTrue(hasattr(self.submission_course, "excused")) self.assertTrue(self.submission_course.excused) # get_submission_peer_reviews() def test_get_submission_peer_reviews(self, m): - register_uris({'submission': ['list_submission_peer_reviews']}, m) + register_uris({"submission": ["list_submission_peer_reviews"]}, m) submission_peer_reviews = self.submission_course.get_submission_peer_reviews() submission_peer_review_list = [ @@ -88,35 +88,35 @@ def test_get_submission_peer_reviews(self, m): # upload_comment() def test_upload_comment(self, m): register_uris( - {'submission': ['upload_comment', 'upload_comment_final', 'edit']}, m + {"submission": ["upload_comment", "upload_comment_final", "edit"]}, m ) - filename = 'testfile_submission_{}'.format(uuid.uuid4().hex) + filename = "testfile_submission_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.submission_course.upload_comment(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) def test_upload_comment_section(self, m): register_uris( - {'submission': ['upload_comment', 'upload_comment_final', 'edit']}, m + {"submission": ["upload_comment", "upload_comment_final", "edit"]}, m ) - filename = 'testfile_submission_{}'.format(uuid.uuid4().hex) + filename = "testfile_submission_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.submission_section.upload_comment(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) @@ -128,12 +128,12 @@ def setUp(self): self.grouped_submission = GroupedSubmission( self.canvas._Canvas__requester, { - 'user_id': 1, - 'submissions': [ + "user_id": 1, + "submissions": [ { - 'id': 1, - 'assignment_id': 1, - 'user_id': 1, + "id": 1, + "assignment_id": 1, + "user_id": 1, "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload", } @@ -144,11 +144,11 @@ def setUp(self): # __init__() def test__init__no_submission_key(self): grouped_submission = GroupedSubmission( - self.canvas._Canvas__requester, {'user_id': 1} + self.canvas._Canvas__requester, {"user_id": 1} ) self.assertIsInstance(grouped_submission, GroupedSubmission) - self.assertTrue(hasattr(grouped_submission, 'submissions')) + self.assertTrue(hasattr(grouped_submission, "submissions")) self.assertIsInstance(grouped_submission.submissions, list) self.assertEqual(len(grouped_submission.submissions), 0) @@ -156,4 +156,4 @@ def test__init__no_submission_key(self): def test__str__(self): string = str(self.grouped_submission) self.assertIsInstance(string, str) - self.assertEqual(string, '1 submission(s) for User #1') + self.assertEqual(string, "1 submission(s) for User #1") diff --git a/tests/test_tab.py b/tests/test_tab.py index dfecd6ac..8cc5b956 100644 --- a/tests/test_tab.py +++ b/tests/test_tab.py @@ -17,8 +17,8 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'course': ['get_by_id', 'list_tabs'], - 'group': ['get_by_id', 'list_tabs'], + "course": ["get_by_id", "list_tabs"], + "group": ["get_by_id", "list_tabs"], }, m, ) @@ -39,7 +39,7 @@ def test__str__(self, m): # update() def test_update_course(self, m): - register_uris({'course': ['update_tab']}, m) + register_uris({"course": ["update_tab"]}, m) new_position = 3 self.tab.update(position=new_position) diff --git a/tests/test_uploader.py b/tests/test_uploader.py index d6288fa7..1cd96cd8 100644 --- a/tests/test_uploader.py +++ b/tests/test_uploader.py @@ -16,8 +16,8 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) self.requester = self.canvas._Canvas__requester - self.filename = 'testfile_uploader_{}'.format(uuid.uuid4().hex) - self.file = open(self.filename, 'w+') + self.filename = "testfile_uploader_{}".format(uuid.uuid4().hex) + self.file = open(self.filename, "w+") def tearDown(self): self.file.close() @@ -25,55 +25,55 @@ def tearDown(self): # start() def test_start(self, m): - requires = {'uploader': ['upload_response', 'upload_response_upload_url']} + requires = {"uploader": ["upload_response", "upload_response_upload_url"]} register_uris(requires, m) - uploader = Uploader(self.requester, 'upload_response', self.file) + uploader = Uploader(self.requester, "upload_response", self.file) result = uploader.start() self.assertTrue(result[0]) self.assertIsInstance(result[1], dict) - self.assertIn('url', result[1]) + self.assertIn("url", result[1]) def test_start_path(self, m): - requires = {'uploader': ['upload_response', 'upload_response_upload_url']} + requires = {"uploader": ["upload_response", "upload_response_upload_url"]} register_uris(requires, m) - uploader = Uploader(self.requester, 'upload_response', self.filename) + uploader = Uploader(self.requester, "upload_response", self.filename) result = uploader.start() self.assertTrue(result[0]) self.assertIsInstance(result[1], dict) - self.assertIn('url', result[1]) + self.assertIn("url", result[1]) def test_start_file_does_not_exist(self, m): with self.assertRaises(IOError): - Uploader(self.requester, 'upload_response', 'test_file_not_real.xyz') + Uploader(self.requester, "upload_response", "test_file_not_real.xyz") # upload() def test_upload_no_upload_url(self, m): - register_uris({'uploader': ['upload_response_no_upload_url']}, m) + register_uris({"uploader": ["upload_response_no_upload_url"]}, m) with self.assertRaises(ValueError): Uploader( - self.requester, 'upload_response_no_upload_url', self.filename + self.requester, "upload_response_no_upload_url", self.filename ).start() def test_upload_no_upload_params(self, m): - register_uris({'uploader': ['upload_response_no_upload_params']}, m) + register_uris({"uploader": ["upload_response_no_upload_params"]}, m) with self.assertRaises(ValueError): Uploader( - self.requester, 'upload_response_no_upload_params', self.filename + self.requester, "upload_response_no_upload_params", self.filename ).start() def test_upload_fail(self, m): - requires = {'uploader': ['upload_fail', 'upload_response_fail']} + requires = {"uploader": ["upload_fail", "upload_response_fail"]} register_uris(requires, m) - uploader = Uploader(self.requester, 'upload_response_fail', self.file) + uploader = Uploader(self.requester, "upload_response_fail", self.file) result = uploader.start() self.assertFalse(result[0]) self.assertIsInstance(result[1], dict) - self.assertNotIn('url', result[1]) + self.assertNotIn("url", result[1]) diff --git a/tests/test_user.py b/tests/test_user.py index f750fb1d..ef92ea75 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -29,7 +29,7 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - register_uris({'user': ['get_by_id']}, m) + register_uris({"user": ["get_by_id"]}, m) self.user = self.canvas.get_user(1) @@ -40,16 +40,16 @@ def test__str__(self, m): # get_profile() def test_get_profile(self, m): - register_uris({'user': ['profile']}, m) + register_uris({"user": ["profile"]}, m) profile = self.user.get_profile() self.assertIsInstance(profile, dict) - self.assertIn('name', profile) + self.assertIn("name", profile) # get_page_views() def test_get_page_views(self, m): - register_uris({'user': ['page_views', 'page_views_p2']}, m) + register_uris({"user": ["page_views", "page_views_p2"]}, m) page_views = self.user.get_page_views() page_view_list = [view for view in page_views] @@ -59,7 +59,7 @@ def test_get_page_views(self, m): # get_courses() def test_get_courses(self, m): - register_uris({'user': ['courses', 'courses_p2']}, m) + register_uris({"user": ["courses", "courses_p2"]}, m) courses = self.user.get_courses() course_list = [course for course in courses] @@ -69,7 +69,7 @@ def test_get_courses(self, m): # get_missing_submissions() def test_get_missing_submissions(self, m): - register_uris({'user': ['missing_sub', 'missing_sub_p2']}, m) + register_uris({"user": ["missing_sub", "missing_sub_p2"]}, m) missing_assigments = self.user.get_missing_submissions() assignment_list = [assignment for assignment in missing_assigments] @@ -79,89 +79,89 @@ def test_get_missing_submissions(self, m): # update_settings() def test_update_settings(self, m): - register_uris({'user': ['update_settings']}, m) + register_uris({"user": ["update_settings"]}, m) settings = self.user.update_settings(manual_mark_as_read=True) self.assertIsInstance(settings, dict) - self.assertIn('manual_mark_as_read', settings) - self.assertTrue(settings['manual_mark_as_read']) + self.assertIn("manual_mark_as_read", settings) + self.assertTrue(settings["manual_mark_as_read"]) # get_color() def test_get_color(self, m): - register_uris({'user': ['color']}, m) + register_uris({"user": ["color"]}, m) color = self.user.get_color("course_1") self.assertIsInstance(color, dict) - self.assertIn('hexcode', color) - self.assertEqual(color['hexcode'], "#abc123") + self.assertIn("hexcode", color) + self.assertEqual(color["hexcode"], "#abc123") # get_colors() def test_get_colors(self, m): - register_uris({'user': ['colors']}, m) + register_uris({"user": ["colors"]}, m) colors = self.user.get_colors() self.assertIsInstance(colors, dict) - self.assertIn('custom_colors', colors) - self.assertIsInstance(colors['custom_colors'], dict) + self.assertIn("custom_colors", colors) + self.assertIsInstance(colors["custom_colors"], dict) # update_color() def test_update_color(self, m): - register_uris({'user': ['color_update']}, m) + register_uris({"user": ["color_update"]}, m) new_hexcode = "#f00f00" color = self.user.update_color("course_1", new_hexcode) self.assertIsInstance(color, dict) - self.assertIn('hexcode', color) - self.assertEqual(color['hexcode'], new_hexcode) + self.assertIn("hexcode", color) + self.assertEqual(color["hexcode"], new_hexcode) def test_update_color_no_hashtag(self, m): - register_uris({'user': ['color_update']}, m) + register_uris({"user": ["color_update"]}, m) new_hexcode = "f00f00" color = self.user.update_color("course_1", new_hexcode) self.assertIsInstance(color, dict) - self.assertIn('hexcode', color) - self.assertEqual(color['hexcode'], "#" + new_hexcode) + self.assertIn("hexcode", color) + self.assertEqual(color["hexcode"], "#" + new_hexcode) # edit() def test_edit(self, m): - register_uris({'user': ['edit']}, m) + register_uris({"user": ["edit"]}, m) new_name = "New User Name" - self.user.edit(user={'name': new_name}) + self.user.edit(user={"name": new_name}) self.assertIsInstance(self.user, User) - self.assertTrue(hasattr(self.user, 'name')) + self.assertTrue(hasattr(self.user, "name")) self.assertEqual(self.user.name, new_name) # merge_into() def test_merge_into_id(self, m): - register_uris({'user': ['merge']}, m) + register_uris({"user": ["merge"]}, m) self.user.merge_into(2) self.assertIsInstance(self.user, User) - self.assertTrue(hasattr(self.user, 'name')) - self.assertEqual(self.user.name, 'John Smith') + self.assertTrue(hasattr(self.user, "name")) + self.assertEqual(self.user.name, "John Smith") def test_merge_into_user(self, m): - register_uris({'user': ['get_by_id_2', 'merge']}, m) + register_uris({"user": ["get_by_id_2", "merge"]}, m) other_user = self.canvas.get_user(2) self.user.merge_into(other_user) self.assertIsInstance(self.user, User) - self.assertTrue(hasattr(self.user, 'name')) - self.assertEqual(self.user.name, 'John Smith') + self.assertTrue(hasattr(self.user, "name")) + self.assertEqual(self.user.name, "John Smith") # get_avatars() def test_get_avatars(self, m): - register_uris({'user': ['avatars', 'avatars_p2']}, m) + register_uris({"user": ["avatars", "avatars_p2"]}, m) avatars = self.user.get_avatars() avatar_list = [avatar for avatar in avatars] @@ -173,8 +173,8 @@ def test_get_avatars(self, m): def test_user_get_assignments(self, m): register_uris( { - 'course': ['get_by_id'], - 'user': ['get_user_assignments', 'get_user_assignments2'], + "course": ["get_by_id"], + "user": ["get_user_assignments", "get_user_assignments2"], }, m, ) @@ -192,7 +192,7 @@ def test_user_get_assignments(self, m): # get_enrollments() def test_get_enrollments(self, m): - register_uris({'user': ['list_enrollments', 'list_enrollments_2']}, m) + register_uris({"user": ["list_enrollments", "list_enrollments_2"]}, m) enrollments = self.user.get_enrollments() enrollment_list = [enrollment for enrollment in enrollments] @@ -202,23 +202,23 @@ def test_get_enrollments(self, m): # upload() def test_upload(self, m): - register_uris({'user': ['upload', 'upload_final']}, m) + register_uris({"user": ["upload", "upload_final"]}, m) - filename = 'testfile_user_{}'.format(uuid.uuid4().hex) + filename = "testfile_user_{}".format(uuid.uuid4().hex) try: - with open(filename, 'w+') as file: + with open(filename, "w+") as file: response = self.user.upload(file) self.assertTrue(response[0]) self.assertIsInstance(response[1], dict) - self.assertIn('url', response[1]) + self.assertIn("url", response[1]) finally: cleanup_file(filename) # list_calendar_events_for_user() def test_list_calendar_events_for_user(self, m): - register_uris({'user': ['list_calendar_events_for_user']}, m) + register_uris({"user": ["list_calendar_events_for_user"]}, m) with warnings.catch_warnings(record=True) as warning_list: cal_events = self.user.list_calendar_events_for_user() @@ -231,7 +231,7 @@ def test_list_calendar_events_for_user(self, m): # get_calendar_events_for_user() def test_get_calendar_events_for_user(self, m): - register_uris({'user': ['list_calendar_events_for_user']}, m) + register_uris({"user": ["list_calendar_events_for_user"]}, m) cal_events = self.user.get_calendar_events_for_user() cal_event_list = [cal_event for cal_event in cal_events] @@ -240,7 +240,7 @@ def test_get_calendar_events_for_user(self, m): # list_communication_channels() def test_list_communication_channels(self, m): - register_uris({'user': ['list_comm_channels', 'list_comm_channels2']}, m) + register_uris({"user": ["list_comm_channels", "list_comm_channels2"]}, m) with warnings.catch_warnings(record=True) as warning_list: comm_channels = self.user.list_communication_channels() @@ -253,7 +253,7 @@ def test_list_communication_channels(self, m): # get_communication_channels() def test_get_communication_channels(self, m): - register_uris({'user': ['list_comm_channels', 'list_comm_channels2']}, m) + register_uris({"user": ["list_comm_channels", "list_comm_channels2"]}, m) comm_channels = self.user.get_communication_channels() channel_list = [channel for channel in comm_channels] @@ -262,7 +262,7 @@ def test_get_communication_channels(self, m): # create_communication_channel() def test_create_communication_channels(self, m): - register_uris({'user': ['create_comm_channel']}, m) + register_uris({"user": ["create_comm_channel"]}, m) channel = {"type": "email", "address": "username@example.org"} new_channel = self.user.create_communication_channel( @@ -273,7 +273,7 @@ def test_create_communication_channels(self, m): # list_files() def test_list_files(self, m): - register_uris({'user': ['get_user_files', 'get_user_files2']}, m) + register_uris({"user": ["get_user_files", "get_user_files2"]}, m) with warnings.catch_warnings(record=True) as warning_list: files = self.user.list_files() @@ -286,7 +286,7 @@ def test_list_files(self, m): # get_files() def test_get_files(self, m): - register_uris({'user': ['get_user_files', 'get_user_files2']}, m) + register_uris({"user": ["get_user_files", "get_user_files2"]}, m) files = self.user.get_files() file_list = [file for file in files] @@ -295,21 +295,21 @@ def test_get_files(self, m): # get_file() def test_get_file(self, m): - register_uris({'user': ['get_file']}, m) + register_uris({"user": ["get_file"]}, m) file_by_id = self.user.get_file(1) self.assertIsInstance(file_by_id, File) - self.assertEqual(file_by_id.display_name, 'User_File.docx') + self.assertEqual(file_by_id.display_name, "User_File.docx") self.assertEqual(file_by_id.size, 1024) file_by_obj = self.user.get_file(file_by_id) self.assertIsInstance(file_by_obj, File) - self.assertEqual(file_by_obj.display_name, 'User_File.docx') + self.assertEqual(file_by_obj.display_name, "User_File.docx") self.assertEqual(file_by_obj.size, 1024) # get_folder() def test_get_folder(self, m): - register_uris({'user': ['get_folder']}, m) + register_uris({"user": ["get_folder"]}, m) folder_by_id = self.user.get_folder(1) self.assertEqual(folder_by_id.name, "Folder 1") @@ -321,7 +321,7 @@ def test_get_folder(self, m): # list_folders() def test_list_folders(self, m): - register_uris({'user': ['list_folders']}, m) + register_uris({"user": ["list_folders"]}, m) with warnings.catch_warnings(record=True) as warning_list: folders = self.user.list_folders() @@ -334,7 +334,7 @@ def test_list_folders(self, m): # get_folders() def test_get_folders(self, m): - register_uris({'user': ['list_folders']}, m) + register_uris({"user": ["list_folders"]}, m) folders = self.user.get_folders() folder_list = [folder for folder in folders] @@ -343,7 +343,7 @@ def test_get_folders(self, m): # create_folder() def test_create_folder(self, m): - register_uris({'user': ['create_folder']}, m) + register_uris({"user": ["create_folder"]}, m) name_str = "Test String" response = self.user.create_folder(name=name_str) @@ -351,7 +351,7 @@ def test_create_folder(self, m): # list_user_logins() def test_list_user_logins(self, m): - requires = {'user': ['list_user_logins', 'list_user_logins_2']} + requires = {"user": ["list_user_logins", "list_user_logins_2"]} register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: @@ -366,7 +366,7 @@ def test_list_user_logins(self, m): # get_user_logins() def test_get_user_logins(self, m): - requires = {'user': ['list_user_logins', 'list_user_logins_2']} + requires = {"user": ["list_user_logins", "list_user_logins_2"]} register_uris(requires, m) response = self.user.get_user_logins() @@ -377,7 +377,7 @@ def test_get_user_logins(self, m): # list_observees() def test_list_observees(self, m): - requires = {'user': ['list_observees', 'list_observees_2']} + requires = {"user": ["list_observees", "list_observees_2"]} register_uris(requires, m) with warnings.catch_warnings(record=True) as warning_list: @@ -392,7 +392,7 @@ def test_list_observees(self, m): # get_observees() def test_get_observees(self, m): - requires = {'user': ['list_observees', 'list_observees_2']} + requires = {"user": ["list_observees", "list_observees_2"]} register_uris(requires, m) response = self.user.get_observees() @@ -403,7 +403,7 @@ def test_get_observees(self, m): # add_observee_with_credentials() def test_add_observee_with_credentials(self, m): - register_uris({'user': ['add_observee_with_credentials']}, m) + register_uris({"user": ["add_observee_with_credentials"]}, m) response = self.user.add_observee_with_credentials() @@ -411,7 +411,7 @@ def test_add_observee_with_credentials(self, m): # show_observee() def test_show_observee(self, m): - register_uris({'user': ['show_observee']}, m) + register_uris({"user": ["show_observee"]}, m) response = self.user.show_observee(6) @@ -419,7 +419,7 @@ def test_show_observee(self, m): # add_observee() def test_add_observee(self, m): - register_uris({'user': ['add_observee']}, m) + register_uris({"user": ["add_observee"]}, m) response = self.user.add_observee(7) @@ -427,7 +427,7 @@ def test_add_observee(self, m): # remove_observee() def test_remove_observee(self, m): - register_uris({'user': ['remove_observee']}, m) + register_uris({"user": ["remove_observee"]}, m) response = self.user.remove_observee(8) @@ -435,42 +435,42 @@ def test_remove_observee(self, m): # create_content_migration def test_create_content_migration(self, m): - register_uris({'user': ['create_content_migration']}, m) + register_uris({"user": ["create_content_migration"]}, m) - content_migration = self.user.create_content_migration('dummy_importer') + content_migration = self.user.create_content_migration("dummy_importer") self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_migrator(self, m): register_uris( - {'user': ['create_content_migration', 'get_migration_systems_multiple']}, m + {"user": ["create_content_migration", "get_migration_systems_multiple"]}, m ) migrators = self.user.get_migration_systems() content_migration = self.user.create_content_migration(migrators[0]) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) def test_create_content_migration_bad_migration_type(self, m): - register_uris({'user': ['create_content_migration']}, m) + register_uris({"user": ["create_content_migration"]}, m) with self.assertRaises(TypeError): self.user.create_content_migration(1) # get_content_migration def test_get_content_migration(self, m): - register_uris({'user': ['get_content_migration_single']}, m) + register_uris({"user": ["get_content_migration_single"]}, m) content_migration = self.user.get_content_migration(1) self.assertIsInstance(content_migration, ContentMigration) - self.assertTrue(hasattr(content_migration, 'migration_type')) + self.assertTrue(hasattr(content_migration, "migration_type")) # get_content_migrations def test_get_content_migrations(self, m): - register_uris({'user': ['get_content_migration_multiple']}, m) + register_uris({"user": ["get_content_migration_multiple"]}, m) content_migrations = self.user.get_content_migrations() @@ -485,7 +485,7 @@ def test_get_content_migrations(self, m): # get_migration_systems def test_get_migration_systems(self, m): - register_uris({'user': ['get_migration_systems_multiple']}, m) + register_uris({"user": ["get_migration_systems_multiple"]}, m) migration_systems = self.user.get_migration_systems() @@ -502,7 +502,7 @@ def test_get_migration_systems(self, m): # get_content_exports() def test_list_content_exports(self, m): - register_uris({'user': ['multiple_content_exports']}, m) + register_uris({"user": ["multiple_content_exports"]}, m) content_exports = self.user.get_content_exports() content_export_list = [content_export for content_export in content_exports] @@ -514,21 +514,21 @@ def test_list_content_exports(self, m): # get_content_export() def test_show_content_export(self, m): - register_uris({'user': ['single_content_export']}, m) + register_uris({"user": ["single_content_export"]}, m) content_export = self.user.get_content_export(11) - self.assertTrue(hasattr(content_export, 'export_type')) + self.assertTrue(hasattr(content_export, "export_type")) self.assertIsInstance(content_export, ContentExport) # export_content() def test_export_content(self, m): - register_uris({'user': ['export_content']}, m) + register_uris({"user": ["export_content"]}, m) - content_export = self.user.export_content('d') + content_export = self.user.export_content("d") self.assertIsInstance(content_export, ContentExport) - self.assertTrue(hasattr(content_export, 'export_type')) + self.assertTrue(hasattr(content_export, "export_type")) @requests_mock.Mocker() @@ -539,10 +539,10 @@ def setUp(self): with requests_mock.Mocker() as m: register_uris( { - 'course': [ - 'get_by_id', - 'get_assignment_by_id', - 'list_gradeable_students', + "course": [ + "get_by_id", + "get_assignment_by_id", + "list_gradeable_students", ] }, m, diff --git a/tests/test_validate_docstrings.py b/tests/test_validate_docstrings.py index 77fb1818..1dcaaeb6 100644 --- a/tests/test_validate_docstrings.py +++ b/tests/test_validate_docstrings.py @@ -17,12 +17,12 @@ @requests_mock.Mocker() class TestValidateDocstrings(unittest.TestCase): def test_validate_method_verb_mismatch(self, m): - url = 'https://canvas.instructure.com/doc/api/files.html#method.files.destroy>' + url = "https://canvas.instructure.com/doc/api/files.html#method.files.destroy>" register_doc_uri(url, m) self.assertFalse(validate_method(ExampleMethods.verb_mismatch, True)) def test_validate_method_invalid_verb(self, m): - url = 'https://canvas.instructure.com/doc/api/files.html#method.files.destroy' + url = "https://canvas.instructure.com/doc/api/files.html#method.files.destroy" register_doc_uri(url, m) self.assertFalse(validate_method(ExampleMethods.invalid_verb, True)) @@ -30,61 +30,61 @@ def test_validate_method_no_api_call(self, m): self.assertTrue(validate_method(ExampleMethods.no_api_call, True)) def test_validate_method_good_docstring(self, m): - url = 'https://canvas.instructure.com/doc/api/files.html#method.files.destroy' + url = "https://canvas.instructure.com/doc/api/files.html#method.files.destroy" register_doc_uri(url, m) self.assertTrue(validate_method(ExampleMethods.good_docstring, True)) def test_validate_method_multiple_endpoints(self, m): - url = 'https://canvas.instructure.com/doc/api/files.html#method.folders.show' + url = "https://canvas.instructure.com/doc/api/files.html#method.folders.show" register_doc_uri(url, m) self.assertTrue(validate_method(ExampleMethods.multiple_endpoints, True)) def test_validate_method_multiline_URL(self, m): url = ( - 'https://canvas.instructure.com/doc/api/notification_preferences.html' - '#method.notification_preferences.index' + "https://canvas.instructure.com/doc/api/notification_preferences.html" + "#method.notification_preferences.index" ) register_doc_uri(url, m) self.assertTrue(validate_method(ExampleMethods.multiline_URL, True)) def test_validate_method_invalid_URL(self, m): - url = 'https://canvas.instructure.com/doc/api/404.html' + url = "https://canvas.instructure.com/doc/api/404.html" register_doc_uri(url, m, code=404) self.assertFalse(validate_method(ExampleMethods.invalid_URL, True)) def test_validate_method_missing_endpoint_URL(self, m): - url = 'https://canvas.instructure.com/doc/api/files.html' + url = "https://canvas.instructure.com/doc/api/files.html" register_doc_uri(url, m) self.assertFalse(validate_method(ExampleMethods.missing_endpoint_URL, True)) def test_validate_method_endpoint_URL_invalid(self, m): - url = 'https://canvas.instructure.com/doc/api/files.html#invalid' + url = "https://canvas.instructure.com/doc/api/files.html#invalid" register_doc_uri(url, m) self.assertFalse(validate_method(ExampleMethods.endpoint_invalid, True)) def test_validate_method_not_an_endpoint(self, m): url = ( - 'https://canvas.instructure.com/doc/api/notification_preferences.html' - '#NotificationPreference' + "https://canvas.instructure.com/doc/api/notification_preferences.html" + "#NotificationPreference" ) register_doc_uri(url, m) self.assertFalse(validate_method(ExampleMethods.not_an_endpoint, True)) def register_doc_uri(url, m, code=200): - url_groups = re.search(r'(.*\/)([^\/]*)\.html', url) + url_groups = re.search(r"(.*\/)([^\/]*)\.html", url) if not url_groups: return file_name = url_groups.group(2) with io.open( - 'tests/fixtures/{}.html'.format(file_name), 'r', encoding='utf-8' + "tests/fixtures/{}.html".format(file_name), "r", encoding="utf-8" ) as file: data = file.read() m.register_uri( - 'GET', - url_groups.group(1) + url_groups.group(2) + '.html', + "GET", + url_groups.group(1) + url_groups.group(2) + ".html", text=data, status_code=code, ) @@ -98,7 +98,7 @@ def verb_mismatch(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request('DELETE', 'files/{}'.format(self.id)) + response = self._requester.request("DELETE", "files/{}".format(self.id)) return ExampleMethods(self._requester, response.json()) def invalid_verb(self): @@ -110,7 +110,7 @@ def invalid_verb(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request('DELETE', 'files/{}'.format(self.id)) + response = self._requester.request("DELETE", "files/{}".format(self.id)) return ExampleMethods(self._requester, response.json()) def no_api_call(self): @@ -128,7 +128,7 @@ def good_docstring(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request('DELETE', 'files/{}'.format(self.id)) + response = self._requester.request("DELETE", "files/{}".format(self.id)) return ExampleMethods(self._requester, response.json()) def multiple_endpoints(self, folder): @@ -145,7 +145,7 @@ def multiple_endpoints(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) + response = self.__requester.request("GET", "folders/{}".format(folder_id)) return Folder(self.__requester, response.json()) def multiline_URL(self, **kwargs): @@ -160,14 +160,14 @@ def multiline_URL(self, **kwargs): :rtype: `list` """ response = self._requester.request( - 'GET', - 'users/{}/communication_channels/{}/notification_preferences'.format( + "GET", + "users/{}/communication_channels/{}/notification_preferences".format( self.user_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - return response.json()['notification_preferences'] + return response.json()["notification_preferences"] def non_api_call(self): """ @@ -190,7 +190,7 @@ def invalid_URL(self): :rtype: :class:`canvasapi.file.File` """ - response = self._requester.request('DELETE', 'files/{}'.format(self.id)) + response = self._requester.request("DELETE", "files/{}".format(self.id)) return ExampleMethods(self._requester, response.json()) def missing_endpoint_URL(self, folder): @@ -207,7 +207,7 @@ def missing_endpoint_URL(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) + response = self.__requester.request("GET", "folders/{}".format(folder_id)) return Folder(self.__requester, response.json()) def endpoint_invalid(self, folder): @@ -224,7 +224,7 @@ def endpoint_invalid(self, folder): """ folder_id = obj_or_id(folder, "folder", (Folder,)) - response = self.__requester.request('GET', 'folders/{}'.format(folder_id)) + response = self.__requester.request("GET", "folders/{}".format(folder_id)) return Folder(self.__requester, response.json()) def not_an_endpoint(self, **kwargs): @@ -239,11 +239,11 @@ def not_an_endpoint(self, **kwargs): :rtype: `list` """ response = self._requester.request( - 'GET', - 'users/{}/communication_channels/{}/notification_preferences'.format( + "GET", + "users/{}/communication_channels/{}/notification_preferences".format( self.user_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) - return response.json()['notification_preferences'] + return response.json()["notification_preferences"] diff --git a/tests/util.py b/tests/util.py index 864b6f7d..64d7cee3 100644 --- a/tests/util.py +++ b/tests/util.py @@ -19,39 +19,39 @@ def register_uris(requirements, requests_mocker): """ for fixture, objects in requirements.items(): try: - with open('tests/fixtures/{}.json'.format(fixture)) as file: + with open("tests/fixtures/{}.json".format(fixture)) as file: data = json.loads(file.read()) except IOError: - raise ValueError('Fixture {}.json contains invalid JSON.'.format(fixture)) + raise ValueError("Fixture {}.json contains invalid JSON.".format(fixture)) if not isinstance(objects, list): - raise TypeError('{} is not a list.'.format(objects)) + raise TypeError("{} is not a list.".format(objects)) for obj_name in objects: obj = data.get(obj_name) if obj is None: raise ValueError( - '{} does not exist in {}.json'.format(obj_name.__repr__(), fixture) + "{} does not exist in {}.json".format(obj_name.__repr__(), fixture) ) - method = requests_mock.ANY if obj['method'] == 'ANY' else obj['method'] - if obj['endpoint'] == 'ANY': + method = requests_mock.ANY if obj["method"] == "ANY" else obj["method"] + if obj["endpoint"] == "ANY": url = requests_mock.ANY else: url = ( get_institution_url(settings.BASE_URL) - + '/api/v1/' - + obj['endpoint'] + + "/api/v1/" + + obj["endpoint"] ) try: requests_mocker.register_uri( method, url, - json=obj.get('data'), - status_code=obj.get('status_code', 200), - headers=obj.get('headers', {}), + json=obj.get("data"), + status_code=obj.get("status_code", 200), + headers=obj.get("headers", {}), ) except Exception as e: print(e) From 22b9f917052c529756979c4e447327705245c0f7 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 9 Jul 2019 17:47:12 -0400 Subject: [PATCH 08/65] Add test for methods to be in alphabetic order. Alphabetize all methods in canvasapi module. --- .travis.yml | 1 + canvasapi/canvas.py | 1612 +++++++-------- canvasapi/canvas_object.py | 14 +- canvasapi/communication_channel.py | 196 +- canvasapi/course.py | 3032 ++++++++++++++-------------- canvasapi/current_user.py | 198 +- canvasapi/discussion_topic.py | 380 ++-- canvasapi/file.py | 18 +- canvasapi/folder.py | 172 +- canvasapi/grading_period.py | 36 +- canvasapi/group.py | 1304 ++++++------ canvasapi/page.py | 196 +- canvasapi/paginated_list.py | 46 +- canvasapi/quiz.py | 420 ++-- canvasapi/quiz_group.py | 84 +- canvasapi/requester.py | 158 +- canvasapi/section.py | 294 +-- canvasapi/submission.py | 52 +- canvasapi/upload.py | 32 +- canvasapi/user.py | 988 ++++----- scripts/alphabetic.py | 91 + scripts/run_black.sh | 2 +- scripts/run_tests.sh | 2 + 23 files changed, 4711 insertions(+), 4617 deletions(-) create mode 100644 scripts/alphabetic.py diff --git a/.travis.yml b/.travis.yml index f0df48a8..4d84edcd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,6 +21,7 @@ script: - flake8 canvasapi tests - mdl . .github - ./scripts/run_black.sh + - python scripts/alphabetic.py after_success: - coveralls notifications: diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py index e912ad80..37aeaca7 100644 --- a/canvasapi/canvas.py +++ b/canvasapi/canvas.py @@ -65,377 +65,193 @@ def __init__(self, base_url, access_token): self.__requester = Requester(base_url, access_token) - def create_account(self, **kwargs): - """ - Create a new root account. - - :calls: `POST /api/v1/accounts \ - `_ - - :rtype: :class:`canvasapi.account.Account` - """ - response = self.__requester.request( - "POST", "accounts", _kwargs=combine_kwargs(**kwargs) - ) - return Account(self.__requester, response.json()) - - def get_account(self, account, use_sis_id=False, **kwargs): - """ - Retrieve information on an individual account. - - :calls: `GET /api/v1/accounts/:id \ - `_ - - :param account: The object or ID of the account to retrieve. - :type account: int, str or :class:`canvasapi.account.Account` - :param use_sis_id: Whether or not account_id is an sis ID. - Defaults to `False`. - :type use_sis_id: bool - - :rtype: :class:`canvasapi.account.Account` - """ - if use_sis_id: - account_id = account - uri_str = "accounts/sis_account_id:{}" - else: - account_id = obj_or_id(account, "account", (Account,)) - uri_str = "accounts/{}" - - response = self.__requester.request( - "GET", uri_str.format(account_id), _kwargs=combine_kwargs(**kwargs) - ) - return Account(self.__requester, response.json()) - - def get_accounts(self, **kwargs): - """ - List accounts that the current user can view or manage. - - Typically, students and teachers will get an empty list in - response. Only account admins can view the accounts that they - are in. - - :calls: `GET /api/v1/accounts \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.Account` - """ - return PaginatedList( - Account, - self.__requester, - "GET", - "accounts", - _kwargs=combine_kwargs(**kwargs), - ) - - def get_course_accounts(self): - """ - List accounts that the current user can view through their - admin course enrollments (Teacher, TA or designer enrollments). - - Only returns `id`, `name`, `workflow_state`, `root_account_id` - and `parent_account_id`. - - :calls: `GET /api/v1/course_accounts \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.account.Account` - """ - return PaginatedList(Account, self.__requester, "GET", "course_accounts") - - def get_course(self, course, use_sis_id=False, **kwargs): + def clear_course_nicknames(self): """ - Retrieve a course by its ID. + Remove all stored course nicknames. - :calls: `GET /api/v1/courses/:id \ - `_ + :calls: `DELETE /api/v1/users/self/course_nicknames \ + `_ - :param course: The object or ID of the course to retrieve. - :type course: int, str or :class:`canvasapi.course.Course` - :param use_sis_id: Whether or not course_id is an sis ID. - Defaults to `False`. - :type use_sis_id: bool + :returns: True if the nicknames were cleared, False otherwise. - :rtype: :class:`canvasapi.course.Course` + :rtype: bool """ - if use_sis_id: - course_id = course - uri_str = "courses/sis_course_id:{}" - else: - course_id = obj_or_id(course, "course", (Course,)) - uri_str = "courses/{}" - response = self.__requester.request( - "GET", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) - ) - return Course(self.__requester, response.json()) + response = self.__requester.request("DELETE", "users/self/course_nicknames") + return response.json().get("message") == "OK" - def get_user(self, user, id_type=None): + def conversations_batch_update(self, conversation_ids, event): """ - Retrieve a user by their ID. `id_type` denotes which endpoint to try as there are - several different IDs that can pull the same user record from Canvas. - - Refer to API documentation's - `User `_ - example to see the ID types a user can be retrieved with. - :calls: `GET /api/v1/users/:id \ - `_ - - :param user: The user's object or ID. - :type user: :class:`canvasapi.user.User` or int - :param id_type: The ID type. - :type id_type: str + :calls: `PUT /api/v1/conversations \ + `_ - :rtype: :class:`canvasapi.user.User` + :param conversation_ids: List of conversations to update. Limited to 500 conversations. + :type conversation_ids: `list` of `str` + :param event: The action to take on each conversation. + :type event: `str` + :rtype: :class:`canvasapi.progress.Progress` """ - if id_type: - uri = "users/{}:{}".format(id_type, user) - elif user == "self": - uri = "users/self" - else: - user_id = obj_or_id(user, "user", (User,)) - uri = "users/{}".format(user_id) - - response = self.__requester.request("GET", uri) - return User(self.__requester, response.json()) - - def get_current_user(self): - return CurrentUser(self.__requester) - def get_courses(self, **kwargs): - """ - Return a list of active courses for the current user. + from canvasapi.progress import Progress - :calls: `GET /api/v1/courses \ - `_ + ALLOWED_EVENTS = [ + "mark_as_read", + "mark_as_unread", + "star", + "unstar", + "archive", + "destroy", + ] - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` - """ - return PaginatedList( - Course, self.__requester, "GET", "courses", _kwargs=combine_kwargs(**kwargs) - ) + try: + if event not in ALLOWED_EVENTS: + raise ValueError( + "{} is not a valid action. Please use one of the following: {}".format( + event, ",".join(ALLOWED_EVENTS) + ) + ) - def get_activity_stream_summary(self): - """ - Return a summary of the current user's global activity stream. + if len(conversation_ids) > 500: + raise ValueError( + "You have requested {} updates, which exceeds the limit of 500".format( + len(conversation_ids) + ) + ) - :calls: `GET /api/v1/users/self/activity_stream/summary \ - `_ + response = self.__requester.request( + "PUT", + "conversations", + event=event, + **{"conversation_ids[]": conversation_ids} + ) + return_progress = Progress(self.__requester, response.json()) + return return_progress - :rtype: dict - """ - response = self.__requester.request("GET", "users/self/activity_stream/summary") - return response.json() + except ValueError as e: + return e - def get_todo_items(self): + def conversations_get_running_batches(self): """ - Return the current user's list of todo items, as seen on the user dashboard. - - :calls: `GET /api/v1/users/self/todo \ - `_ + Returns any currently running conversation batches for the current user. + Conversation batches are created when a bulk private message is sent + asynchronously. - :rtype: dict - """ - response = self.__requester.request("GET", "users/self/todo") - return response.json() + :calls: `GET /api/v1/conversations/batches \ + `_ - def get_upcoming_events(self): + :returns: dict with list of batch objects - not currently a Class + :rtype: `dict` """ - Return the current user's upcoming events, i.e. the same things shown - in the dashboard 'Coming Up' sidebar. - :calls: `GET /api/v1/users/self/upcoming_events \ - `_ + response = self.__requester.request("GET", "conversations/batches") - :rtype: dict - """ - response = self.__requester.request("GET", "users/self/upcoming_events") return response.json() - def get_course_nicknames(self): - """ - Return all course nicknames set by the current account. - - :calls: `GET /api/v1/users/self/course_nicknames \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.CourseNickname` - """ - from canvasapi.course import CourseNickname - - return PaginatedList( - CourseNickname, self.__requester, "GET", "users/self/course_nicknames" - ) - - def get_course_nickname(self, course): - """ - Return the nickname for the given course. - - :calls: `GET /api/v1/users/self/course_nicknames/:course_id \ - `_ - - :param course: The object or ID of the course. - :type course: :class:`canvasapi.course.Course` or int - - :rtype: :class:`canvasapi.course.CourseNickname` - """ - from canvasapi.course import CourseNickname - - course_id = obj_or_id(course, "course", (Course,)) - - response = self.__requester.request( - "GET", "users/self/course_nicknames/{}".format(course_id) - ) - return CourseNickname(self.__requester, response.json()) - - def get_section(self, section, use_sis_id=False, **kwargs): - """ - Get details about a specific section. - - :calls: `GET /api/v1/sections/:id \ - `_ - - :param section: The object or ID of the section to get. - :type section: :class:`canvasapi.section.Section` or int - :param use_sis_id: Whether or not section_id is an sis ID. - Defaults to `False`. - :type use_sis_id: bool - - :rtype: :class:`canvasapi.section.Section` - """ - if use_sis_id: - section_id = section - uri_str = "sections/sis_section_id:{}" - else: - section_id = obj_or_id(section, "section", (Section,)) - uri_str = "sections/{}" - - response = self.__requester.request( - "GET", uri_str.format(section_id), _kwargs=combine_kwargs(**kwargs) - ) - return Section(self.__requester, response.json()) - - def set_course_nickname(self, course, nickname): - """ - Set a nickname for the given course. This will replace the - course's name in the output of subsequent API calls, as - well as in selected places in the Canvas web user interface. - - :calls: `PUT /api/v1/users/self/course_nicknames/:course_id \ - `_ - - :param course: The ID of the course. - :type course: :class:`canvasapi.course.Course` or int - :param nickname: The nickname for the course. - :type nickname: str - - :rtype: :class:`canvasapi.course.CourseNickname` - """ - from canvasapi.course import CourseNickname - - course_id = obj_or_id(course, "course", (Course,)) - - response = self.__requester.request( - "PUT", "users/self/course_nicknames/{}".format(course_id), nickname=nickname - ) - return CourseNickname(self.__requester, response.json()) - - def clear_course_nicknames(self): + def conversations_mark_all_as_read(self): """ - Remove all stored course nicknames. - - :calls: `DELETE /api/v1/users/self/course_nicknames \ - `_ + Mark all conversations as read. - :returns: True if the nicknames were cleared, False otherwise. + :calls: `POST /api/v1/conversations/mark_all_as_read \ + `_ - :rtype: bool + :rtype: `bool` """ + response = self.__requester.request("POST", "conversations/mark_all_as_read") + return response.json() == {} - response = self.__requester.request("DELETE", "users/self/course_nicknames") - return response.json().get("message") == "OK" - - def search_accounts(self, **kwargs): - """ - Return a list of up to 5 matching account domains. Partial matches on - name and domain are supported. + def conversations_unread_count(self): + """ + Get the number of unread conversations for the current user - :calls: `GET /api/v1/accounts/search \ - `_ + :calls: `GET /api/v1/conversations/unread_count \ + `_ - :rtype: dict + :returns: simple object with unread_count, example: {'unread_count': '7'} + :rtype: `dict` """ - response = self.__requester.request( - "GET", "accounts/search", _kwargs=combine_kwargs(**kwargs) - ) + response = self.__requester.request("GET", "conversations/unread_count") + return response.json() - def create_group(self, **kwargs): + def create_account(self, **kwargs): """ - Create a group + Create a new root account. - :calls: `POST /api/v1/groups/ \ - `_ + :calls: `POST /api/v1/accounts \ + `_ - :rtype: :class:`canvasapi.group.Group` + :rtype: :class:`canvasapi.account.Account` """ response = self.__requester.request( - "POST", "groups", _kwargs=combine_kwargs(**kwargs) + "POST", "accounts", _kwargs=combine_kwargs(**kwargs) ) - return Group(self.__requester, response.json()) + return Account(self.__requester, response.json()) - def get_group(self, group, use_sis_id=False, **kwargs): + def create_appointment_group(self, appointment_group, **kwargs): """ - Return the data for a single group. If the caller does not - have permission to view the group a 401 will be returned. + Create a new Appointment Group. - :calls: `GET /api/v1/groups/:group_id \ - `_ + :calls: `POST /api/v1/appointment_groups \ + `_ - :param group: The object or ID of the group to get. - :type group: :class:`canvasapi.group.Group` or int + :param appointment_group: The attributes of the appointment group. + :type appointment_group: `dict` + :param title: The title of the appointment group. + :type title: `str` + :rtype: :class:`canvasapi.appointment_group.AppointmentGroup` + """ + from canvasapi.appointment_group import AppointmentGroup - :param use_sis_id: Whether or not group_id is an sis ID. - Defaults to `False`. - :type use_sis_id: bool + if ( + isinstance(appointment_group, dict) + and "context_codes" in appointment_group + and "title" in appointment_group + ): + kwargs["appointment_group"] = appointment_group - :rtype: :class:`canvasapi.group.Group` - """ + elif ( + isinstance(appointment_group, dict) + and "context_codes" not in appointment_group + ): + raise RequiredFieldMissing( + "Dictionary with key 'context_codes' is missing." + ) - if use_sis_id: - group_id = group - uri_str = "groups/sis_group_id:{}" - else: - group_id = obj_or_id(group, "group", (Group,)) - uri_str = "groups/{}" + elif isinstance(appointment_group, dict) and "title" not in appointment_group: + raise RequiredFieldMissing("Dictionary with key 'title' is missing.") response = self.__requester.request( - "GET", uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) + "POST", "appointment_groups", _kwargs=combine_kwargs(**kwargs) ) - return Group(self.__requester, response.json()) - def get_group_category(self, category): - """ - Get a single group category. + return AppointmentGroup(self.__requester, response.json()) - :calls: `GET /api/v1/group_categories/:group_category_id \ - `_ + def create_calendar_event(self, calendar_event, **kwargs): + """ + Create a new Calendar Event. - :param category: The object or ID of the category. - :type category: :class:`canvasapi.group.GroupCategory` or int + :calls: `POST /api/v1/calendar_events \ + `_ - :rtype: :class:`canvasapi.group.GroupCategory` + :param calendar_event: The attributes of the calendar event. + :type calendar_event: `dict` + :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ - category_id = obj_or_id(category, "category", (GroupCategory,)) + from canvasapi.calendar_event import CalendarEvent + + if isinstance(calendar_event, dict) and "context_code" in calendar_event: + kwargs["calendar_event"] = calendar_event + else: + raise RequiredFieldMissing( + "Dictionary with key 'context_codes' is required." + ) response = self.__requester.request( - "GET", "group_categories/{}".format(category_id) + "POST", "calendar_events", _kwargs=combine_kwargs(**kwargs) ) - return GroupCategory(self.__requester, response.json()) + + return CalendarEvent(self.__requester, response.json()) def create_conversation(self, recipients, body, **kwargs): """ @@ -463,247 +279,231 @@ def create_conversation(self, recipients, body, **kwargs): ) return [Conversation(self.__requester, convo) for convo in response.json()] - def get_conversation(self, conversation, **kwargs): + def create_group(self, **kwargs): """ - Return single Conversation - - :calls: `GET /api/v1/conversations/:id \ - `_ + Create a group - :param conversation: The object or ID of the conversation. - :type conversation: :class:`canvasapi.conversation.Conversation` or int + :calls: `POST /api/v1/groups/ \ + `_ - :rtype: :class:`canvasapi.conversation.Conversation` + :rtype: :class:`canvasapi.group.Group` """ - from canvasapi.conversation import Conversation - - conversation_id = obj_or_id(conversation, "conversation", (Conversation,)) - response = self.__requester.request( - "GET", - "conversations/{}".format(conversation_id), - _kwargs=combine_kwargs(**kwargs), + "POST", "groups", _kwargs=combine_kwargs(**kwargs) ) - return Conversation(self.__requester, response.json()) + return Group(self.__requester, response.json()) - def get_conversations(self, **kwargs): + def create_planner_note(self, **kwargs): """ - Return list of conversations for the current user, most resent ones first. + Create a planner note for the current user - :calls: `GET /api/v1/conversations \ - `_ + :calls: `POST /api/v1/planner_notes \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of \ - :class:`canvasapi.conversation.Conversation` + :rtype: :class:`canvasapi.planner.PlannerNote` """ - from canvasapi.conversation import Conversation + from canvasapi.planner import PlannerNote - return PaginatedList( - Conversation, - self.__requester, - "GET", - "conversations", - _kwargs=combine_kwargs(**kwargs), + response = self.__requester.request( + "POST", "planner_notes", _kwargs=combine_kwargs(**kwargs) ) + return PlannerNote(self.__requester, response.json()) - def conversations_mark_all_as_read(self): - """ - Mark all conversations as read. - - :calls: `POST /api/v1/conversations/mark_all_as_read \ - `_ - - :rtype: `bool` - """ - response = self.__requester.request("POST", "conversations/mark_all_as_read") - return response.json() == {} - - def conversations_unread_count(self): - """ - Get the number of unread conversations for the current user - - :calls: `GET /api/v1/conversations/unread_count \ - `_ - - :returns: simple object with unread_count, example: {'unread_count': '7'} - :rtype: `dict` + def create_planner_override(self, plannable_type, plannable_id, **kwargs): """ - response = self.__requester.request("GET", "conversations/unread_count") + Create a planner override for the current user - return response.json() + :calls: `POST /api/v1/planner/overrides \ + `_ - def conversations_get_running_batches(self): - """ - Returns any currently running conversation batches for the current user. - Conversation batches are created when a bulk private message is sent - asynchronously. + :param plannable_type: Type of the item that you are overriding in the planner + :type plannable_type: str - :calls: `GET /api/v1/conversations/batches \ - `_ + :param plannable_id: ID of the item that you are overriding in the planner + :type plannable_id: int or :class:`canvasapi.planner.PlannerOverride` - :returns: dict with list of batch objects - not currently a Class - :rtype: `dict` + :rtype: :class:`canvasapi.planner.PlannerOverride` """ + from canvasapi.planner import PlannerOverride + from six import text_type, integer_types - response = self.__requester.request("GET", "conversations/batches") + if isinstance(plannable_type, text_type): + kwargs["plannable_type"] = plannable_type + else: + raise RequiredFieldMissing("plannable_type is required as a str.") + if isinstance(plannable_id, integer_types): + kwargs["plannable_id"] = plannable_id + else: + raise RequiredFieldMissing("plannable_id is required as an int.") - return response.json() + response = self.__requester.request( + "POST", "planner/overrides", _kwargs=combine_kwargs(**kwargs) + ) + return PlannerOverride(self.__requester, response.json()) - def conversations_batch_update(self, conversation_ids, event): + def create_poll(self, poll, **kwargs): """ + Create a new poll for the current user. - :calls: `PUT /api/v1/conversations \ - `_ + :calls: `POST /api/v1/polls \ + `_ - :param conversation_ids: List of conversations to update. Limited to 500 conversations. - :type conversation_ids: `list` of `str` - :param event: The action to take on each conversation. - :type event: `str` - :rtype: :class:`canvasapi.progress.Progress` + :param poll: List of polls to create. `'question'` key is required. + :type poll: list of dict + :rtype: :class:`canvasapi.poll.Poll` """ + from canvasapi.poll import Poll - from canvasapi.progress import Progress - - ALLOWED_EVENTS = [ - "mark_as_read", - "mark_as_unread", - "star", - "unstar", - "archive", - "destroy", - ] - - try: - if event not in ALLOWED_EVENTS: - raise ValueError( - "{} is not a valid action. Please use one of the following: {}".format( - event, ",".join(ALLOWED_EVENTS) - ) - ) - - if len(conversation_ids) > 500: - raise ValueError( - "You have requested {} updates, which exceeds the limit of 500".format( - len(conversation_ids) - ) - ) - - response = self.__requester.request( - "PUT", - "conversations", - event=event, - **{"conversation_ids[]": conversation_ids} + if ( + isinstance(poll, list) + and isinstance(poll[0], dict) + and "question" in poll[0] + ): + kwargs["poll"] = poll + else: + raise RequiredFieldMissing( + "Dictionary with key 'question' and is required." ) - return_progress = Progress(self.__requester, response.json()) - return return_progress - except ValueError as e: - return e + response = self.__requester.request( + "POST", "polls", _kwargs=combine_kwargs(**kwargs) + ) + return Poll(self.__requester, response.json()["polls"][0]) - def create_calendar_event(self, calendar_event, **kwargs): + def get_account(self, account, use_sis_id=False, **kwargs): """ - Create a new Calendar Event. + Retrieve information on an individual account. - :calls: `POST /api/v1/calendar_events \ - `_ + :calls: `GET /api/v1/accounts/:id \ + `_ - :param calendar_event: The attributes of the calendar event. - :type calendar_event: `dict` - :rtype: :class:`canvasapi.calendar_event.CalendarEvent` - """ - from canvasapi.calendar_event import CalendarEvent + :param account: The object or ID of the account to retrieve. + :type account: int, str or :class:`canvasapi.account.Account` + :param use_sis_id: Whether or not account_id is an sis ID. + Defaults to `False`. + :type use_sis_id: bool - if isinstance(calendar_event, dict) and "context_code" in calendar_event: - kwargs["calendar_event"] = calendar_event + :rtype: :class:`canvasapi.account.Account` + """ + if use_sis_id: + account_id = account + uri_str = "accounts/sis_account_id:{}" else: - raise RequiredFieldMissing( - "Dictionary with key 'context_codes' is required." - ) + account_id = obj_or_id(account, "account", (Account,)) + uri_str = "accounts/{}" response = self.__requester.request( - "POST", "calendar_events", _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(account_id), _kwargs=combine_kwargs(**kwargs) ) + return Account(self.__requester, response.json()) - return CalendarEvent(self.__requester, response.json()) - - def list_calendar_events(self, **kwargs): + def get_accounts(self, **kwargs): """ - List calendar events. + List accounts that the current user can view or manage. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.canvas.Canvas.get_calendar_events` instead. + Typically, students and teachers will get an empty list in + response. Only account admins can view the accounts that they + are in. - :calls: `GET /api/v1/calendar_events \ - `_ + :calls: `GET /api/v1/accounts \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.calendar_event.CalendarEvent` + :class:`canvasapi.account.Account` """ - warnings.warn( - "`list_calendar_events` is being deprecated and will be removed " - "in a future version. Use `get_calendar_events` instead", - DeprecationWarning, + return PaginatedList( + Account, + self.__requester, + "GET", + "accounts", + _kwargs=combine_kwargs(**kwargs), ) - return self.get_calendar_events(**kwargs) + def get_activity_stream_summary(self): + """ + Return a summary of the current user's global activity stream. - def get_calendar_events(self, **kwargs): + :calls: `GET /api/v1/users/self/activity_stream/summary \ + `_ + + :rtype: dict """ - List calendar events. + response = self.__requester.request("GET", "users/self/activity_stream/summary") + return response.json() - :calls: `GET /api/v1/calendar_events \ - `_ + def get_announcements(self, **kwargs): + """ + List announcements. + + :calls: `GET /api/v1/announcements \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.calendar_event.CalendarEvent` + :class:`canvasapi.discussion_topic.DiscussionTopic` """ - from canvasapi.calendar_event import CalendarEvent + from canvasapi.discussion_topic import DiscussionTopic return PaginatedList( - CalendarEvent, + DiscussionTopic, self.__requester, "GET", - "calendar_events", + "announcements", _kwargs=combine_kwargs(**kwargs), ) - def get_calendar_event(self, calendar_event): + def get_appointment_group(self, appointment_group): """ - Return single Calendar Event by id + Return single Appointment Group by id - :calls: `GET /api/v1/calendar_events/:id \ - `_ + :calls: `GET /api/v1/appointment_groups/:id \ + `_ - :param calendar_event: The object or ID of the calendar event. - :type calendar_event: :class:`canvasapi.calendar_event.CalendarEvent` or int + :param appointment_group: The ID of the appointment group. + :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int - :rtype: :class:`canvasapi.calendar_event.CalendarEvent` + :rtype: :class:`canvasapi.appointment_group.AppointmentGroup` """ - from canvasapi.calendar_event import CalendarEvent + from canvasapi.appointment_group import AppointmentGroup - calendar_event_id = obj_or_id( - calendar_event, "calendar_event", (CalendarEvent,) + appointment_group_id = obj_or_id( + appointment_group, "appointment_group", (AppointmentGroup,) ) response = self.__requester.request( - "GET", "calendar_events/{}".format(calendar_event_id) + "GET", "appointment_groups/{}".format(appointment_group_id) ) - return CalendarEvent(self.__requester, response.json()) + return AppointmentGroup(self.__requester, response.json()) - def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs): + def get_appointment_groups(self, **kwargs): + """ + List appointment groups. + + :calls: `GET /api/v1/appointment_groups \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.appointment_group.AppointmentGroup` + """ + from canvasapi.appointment_group import AppointmentGroup + + return PaginatedList( + AppointmentGroup, + self.__requester, + "GET", + "appointment_groups", + _kwargs=combine_kwargs(**kwargs), + ) + + def get_calendar_event(self, calendar_event): """ Return single Calendar Event by id - :calls: `POST /api/v1/calendar_events/:id/reservations \ - `_ + :calls: `GET /api/v1/calendar_events/:id \ + `_ :param calendar_event: The object or ID of the calendar event. :type calendar_event: :class:`canvasapi.calendar_event.CalendarEvent` or int - :param participant_id: The ID of the participant, if given. - :type participant_id: str - :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ from canvasapi.calendar_event import CalendarEvent @@ -712,222 +512,189 @@ def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs): calendar_event, "calendar_event", (CalendarEvent,) ) - if participant_id: - uri = "calendar_events/{}/reservations/{}".format( - calendar_event_id, participant_id - ) - else: - uri = "calendar_events/{}/reservations".format(calendar_event_id) - response = self.__requester.request( - "POST", uri, _kwargs=combine_kwargs(**kwargs) + "GET", "calendar_events/{}".format(calendar_event_id) ) return CalendarEvent(self.__requester, response.json()) - def list_appointment_groups(self, **kwargs): - """ - List appointment groups. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.canvas.Canvas.get_appointment_groups` instead. - - :calls: `GET /api/v1/appointment_groups \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.appointment_group.AppointmentGroup` - """ - warnings.warn( - "`list_appointment_groups` is being deprecated and will be removed" - " in a future version. Use `get_appointment_groups` instead.", - DeprecationWarning, - ) - - return self.get_appointment_groups(**kwargs) - - def get_appointment_groups(self, **kwargs): + def get_calendar_events(self, **kwargs): """ - List appointment groups. + List calendar events. - :calls: `GET /api/v1/appointment_groups \ - `_ + :calls: `GET /api/v1/calendar_events \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.appointment_group.AppointmentGroup` + :class:`canvasapi.calendar_event.CalendarEvent` """ - from canvasapi.appointment_group import AppointmentGroup + from canvasapi.calendar_event import CalendarEvent return PaginatedList( - AppointmentGroup, + CalendarEvent, self.__requester, "GET", - "appointment_groups", + "calendar_events", _kwargs=combine_kwargs(**kwargs), ) - def get_appointment_group(self, appointment_group): + def get_conversation(self, conversation, **kwargs): """ - Return single Appointment Group by id + Return single Conversation - :calls: `GET /api/v1/appointment_groups/:id \ - `_ + :calls: `GET /api/v1/conversations/:id \ + `_ - :param appointment_group: The ID of the appointment group. - :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + :param conversation: The object or ID of the conversation. + :type conversation: :class:`canvasapi.conversation.Conversation` or int - :rtype: :class:`canvasapi.appointment_group.AppointmentGroup` + :rtype: :class:`canvasapi.conversation.Conversation` """ - from canvasapi.appointment_group import AppointmentGroup + from canvasapi.conversation import Conversation - appointment_group_id = obj_or_id( - appointment_group, "appointment_group", (AppointmentGroup,) - ) + conversation_id = obj_or_id(conversation, "conversation", (Conversation,)) response = self.__requester.request( - "GET", "appointment_groups/{}".format(appointment_group_id) + "GET", + "conversations/{}".format(conversation_id), + _kwargs=combine_kwargs(**kwargs), ) - return AppointmentGroup(self.__requester, response.json()) + return Conversation(self.__requester, response.json()) - def create_appointment_group(self, appointment_group, **kwargs): + def get_conversations(self, **kwargs): """ - Create a new Appointment Group. + Return list of conversations for the current user, most resent ones first. - :calls: `POST /api/v1/appointment_groups \ - `_ + :calls: `GET /api/v1/conversations \ + `_ - :param appointment_group: The attributes of the appointment group. - :type appointment_group: `dict` - :param title: The title of the appointment group. - :type title: `str` - :rtype: :class:`canvasapi.appointment_group.AppointmentGroup` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of \ + :class:`canvasapi.conversation.Conversation` + """ + from canvasapi.conversation import Conversation + + return PaginatedList( + Conversation, + self.__requester, + "GET", + "conversations", + _kwargs=combine_kwargs(**kwargs), + ) + + def get_course(self, course, use_sis_id=False, **kwargs): """ - from canvasapi.appointment_group import AppointmentGroup + Retrieve a course by its ID. - if ( - isinstance(appointment_group, dict) - and "context_codes" in appointment_group - and "title" in appointment_group - ): - kwargs["appointment_group"] = appointment_group + :calls: `GET /api/v1/courses/:id \ + `_ - elif ( - isinstance(appointment_group, dict) - and "context_codes" not in appointment_group - ): - raise RequiredFieldMissing( - "Dictionary with key 'context_codes' is missing." - ) + :param course: The object or ID of the course to retrieve. + :type course: int, str or :class:`canvasapi.course.Course` + :param use_sis_id: Whether or not course_id is an sis ID. + Defaults to `False`. + :type use_sis_id: bool - elif isinstance(appointment_group, dict) and "title" not in appointment_group: - raise RequiredFieldMissing("Dictionary with key 'title' is missing.") + :rtype: :class:`canvasapi.course.Course` + """ + if use_sis_id: + course_id = course + uri_str = "courses/sis_course_id:{}" + else: + course_id = obj_or_id(course, "course", (Course,)) + uri_str = "courses/{}" response = self.__requester.request( - "POST", "appointment_groups", _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) ) + return Course(self.__requester, response.json()) - return AppointmentGroup(self.__requester, response.json()) - - def list_user_participants(self, appointment_group, **kwargs): + def get_course_accounts(self): """ - List user participants in this appointment group. + List accounts that the current user can view through their + admin course enrollments (Teacher, TA or designer enrollments). - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi. canvas.Canvas.get_user_participants` instead. + Only returns `id`, `name`, `workflow_state`, `root_account_id` + and `parent_account_id`. - :calls: `GET /api/v1/appointment_groups/:id/users \ - `_ + :calls: `GET /api/v1/course_accounts \ + `_ - :param appointment_group: The object or ID of the appointment group. - :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.account.Account` + """ + return PaginatedList(Account, self.__requester, "GET", "course_accounts") - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` + def get_course_nickname(self, course): """ - warnings.warn( - "`list_user_participants` is being deprecated and will be removed in a future version." - " Use `get_user_participants` instead", - DeprecationWarning, - ) + Return the nickname for the given course. - return self.get_user_participants(appointment_group, **kwargs) + :calls: `GET /api/v1/users/self/course_nicknames/:course_id \ + `_ - def get_user_participants(self, appointment_group, **kwargs): + :param course: The object or ID of the course. + :type course: :class:`canvasapi.course.Course` or int + + :rtype: :class:`canvasapi.course.CourseNickname` """ - List user participants in this appointment group. + from canvasapi.course import CourseNickname - :calls: `GET /api/v1/appointment_groups/:id/users \ - `_ + course_id = obj_or_id(course, "course", (Course,)) - :param appointment_group: The object or ID of the appointment group. - :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + response = self.__requester.request( + "GET", "users/self/course_nicknames/{}".format(course_id) + ) + return CourseNickname(self.__requester, response.json()) - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` + def get_course_nicknames(self): """ - from canvasapi.appointment_group import AppointmentGroup - from canvasapi.user import User + Return all course nicknames set by the current account. - appointment_group_id = obj_or_id( - appointment_group, "appointment_group", (AppointmentGroup,) - ) + :calls: `GET /api/v1/users/self/course_nicknames \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.CourseNickname` + """ + from canvasapi.course import CourseNickname return PaginatedList( - User, - self.__requester, - "GET", - "appointment_groups/{}/users".format(appointment_group_id), - _kwargs=combine_kwargs(**kwargs), + CourseNickname, self.__requester, "GET", "users/self/course_nicknames" ) - def list_group_participants(self, appointment_group, **kwargs): + def get_courses(self, **kwargs): """ - List student group participants in this appointment group. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi. canvas.Canvas.get_group_participants` instead. - - :calls: `GET /api/v1/appointment_groups/:id/groups \ - `_ + Return a list of active courses for the current user. - :param appointment_group: The object or ID of the appointment group. - :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + :calls: `GET /api/v1/courses \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.Course` """ - warnings.warn( - "`list_group_participants` is being deprecated and will be removed " - "in a future version. Use `get_group_participants` instead", - DeprecationWarning, + return PaginatedList( + Course, self.__requester, "GET", "courses", _kwargs=combine_kwargs(**kwargs) ) - return self.get_group_participants(appointment_group, **kwargs) + def get_current_user(self): + return CurrentUser(self.__requester) - def get_group_participants(self, appointment_group, **kwargs): + def get_epub_exports(self, **kwargs): """ - List student group participants in this appointment group. - - :calls: `GET /api/v1/appointment_groups/:id/groups \ - `_ + Return a list of epub exports for the associated course. - :param appointment_group: The object or ID of the appointment group. - :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + :calls: `GET /api/v1/epub_exports\ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course_epub_export.CourseEpubExport` """ - from canvasapi.appointment_group import AppointmentGroup - from canvasapi.group import Group - - appointment_group_id = obj_or_id( - appointment_group, "appointment_group", (AppointmentGroup,) - ) return PaginatedList( - Group, + CourseEpubExport, self.__requester, "GET", - "appointment_groups/{}/groups".format(appointment_group_id), - _kwargs=combine_kwargs(**kwargs), + "epub_exports", + _root="courses", + kwargs=combine_kwargs(**kwargs), ) def get_file(self, file, **kwargs): @@ -966,39 +733,81 @@ def get_folder(self, folder): response = self.__requester.request("GET", "folders/{}".format(folder_id)) return Folder(self.__requester, response.json()) - def search_recipients(self, **kwargs): + def get_group(self, group, use_sis_id=False, **kwargs): """ - Find valid recipients (users, courses and groups) that the current user - can send messages to. - Returns a list of mixed data types. + Return the data for a single group. If the caller does not + have permission to view the group a 401 will be returned. - :calls: `GET /api/v1/search/recipients \ - `_ + :calls: `GET /api/v1/groups/:group_id \ + `_ - :rtype: `list` + :param group: The object or ID of the group to get. + :type group: :class:`canvasapi.group.Group` or int + + :param use_sis_id: Whether or not group_id is an sis ID. + Defaults to `False`. + :type use_sis_id: bool + + :rtype: :class:`canvasapi.group.Group` """ - if "search" not in kwargs: - kwargs["search"] = " " + + if use_sis_id: + group_id = group + uri_str = "groups/sis_group_id:{}" + else: + group_id = obj_or_id(group, "group", (Group,)) + uri_str = "groups/{}" response = self.__requester.request( - "GET", "search/recipients", _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) ) - return response.json() + return Group(self.__requester, response.json()) - def search_all_courses(self, **kwargs): + def get_group_category(self, category): """ - List all the courses visible in the public index. - Returns a list of dicts, each containing a single course. + Get a single group category. - :calls: `GET /api/v1/search/all_courses \ - `_ + :calls: `GET /api/v1/group_categories/:group_category_id \ + `_ - :rtype: `list` + :param category: The object or ID of the category. + :type category: :class:`canvasapi.group.GroupCategory` or int + + :rtype: :class:`canvasapi.group.GroupCategory` """ + category_id = obj_or_id(category, "category", (GroupCategory,)) + response = self.__requester.request( - "GET", "search/all_courses", _kwargs=combine_kwargs(**kwargs) + "GET", "group_categories/{}".format(category_id) + ) + return GroupCategory(self.__requester, response.json()) + + def get_group_participants(self, appointment_group, **kwargs): + """ + List student group participants in this appointment group. + + :calls: `GET /api/v1/appointment_groups/:id/groups \ + `_ + + :param appointment_group: The object or ID of the appointment group. + :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + """ + from canvasapi.appointment_group import AppointmentGroup + from canvasapi.group import Group + + appointment_group_id = obj_or_id( + appointment_group, "appointment_group", (AppointmentGroup,) + ) + + return PaginatedList( + Group, + self.__requester, + "GET", + "appointment_groups/{}/groups".format(appointment_group_id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() def get_outcome(self, outcome): """ @@ -1019,21 +828,6 @@ def get_outcome(self, outcome): response = self.__requester.request("GET", "outcomes/{}".format(outcome_id)) return Outcome(self.__requester, response.json()) - def get_root_outcome_group(self): - """ - Redirect to root outcome group for context - - :calls: `GET /api/v1/global/root_outcome_group \ - `_ - - :returns: The OutcomeGroup of the context. - :rtype: :class:`canvasapi.outcome.OutcomeGroup` - """ - from canvasapi.outcome import OutcomeGroup - - response = self.__requester.request("GET", "global/root_outcome_group") - return OutcomeGroup(self.__requester, response.json()) - def get_outcome_group(self, group): """ Returns the details of the Outcome Group with the given id. @@ -1057,66 +851,105 @@ def get_outcome_group(self, group): return OutcomeGroup(self.__requester, response.json()) - def get_progress(self, progress, **kwargs): + def get_planner_note(self, planner_note, **kwargs): """ - Get a specific progress. + Retrieve a planner note for the current user - :calls: `GET /api/v1/progress/:id - `_ + :calls: `GET /api/v1/planner_notes/:id \ + `_ - :param progress: The object or ID of the progress to retrieve. - :type progress: int, str or :class:`canvasapi.progress.Progress` + :param planner_note: The ID of the planner note to retrieve. + :type planner_note: int or :class:`canvasapi.planner.PlannerNote` - :rtype: :class:`canvasapi.progress.Progress` + :rtype: :class:`canvasapi.planner.PlannerNote` """ + from canvasapi.planner import PlannerNote - from canvasapi.progress import Progress - - progress_id = obj_or_id(progress, "progress", (Progress,)) + if isinstance(planner_note, int) or isinstance(planner_note, PlannerNote): + planner_note_id = obj_or_id(planner_note, "planner_note", (PlannerNote,)) + else: + raise RequiredFieldMissing( + "planner_note is required as an object or as an int." + ) response = self.__requester.request( - "GET", "progress/{}".format(progress_id), _kwargs=combine_kwargs(**kwargs) + "GET", + "planner_notes/{}".format(planner_note_id), + _kwargs=combine_kwargs(**kwargs), ) - return Progress(self.__requester, response.json()) - def get_announcements(self, **kwargs): + return PlannerNote(self.__requester, response.json()) + + def get_planner_notes(self, **kwargs): """ - List announcements. + Retrieve the paginated list of planner notes - :calls: `GET /api/v1/announcements \ - `_ + :calls: `GET /api/v1/planner_notes \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.discussion_topic.DiscussionTopic` + :class:`canvasapi.planner.PlannerNote` """ - from canvasapi.discussion_topic import DiscussionTopic + from canvasapi.planner import PlannerNote return PaginatedList( - DiscussionTopic, + PlannerNote, self.__requester, "GET", - "announcements", + "planner_notes", _kwargs=combine_kwargs(**kwargs), ) - def get_polls(self, **kwargs): + def get_planner_override(self, planner_override, **kwargs): """ - Returns a paginated list of polls for the current user + Retrieve a planner override for the current user - :calls: `GET /api/1/polls \ - `_ + :calls: `GET /api/v1/planner/overrides/:id \ + `_ + + :param planner_override: The override or the ID of the planner override to retrieve. + :type planner_override: int or :class:`canvasapi.planner.PlannerOverride` + + :rtype: :class:`canvasapi.planner.PlannerOverride` + """ + from canvasapi.planner import PlannerOverride + + if isinstance(planner_override, int) or isinstance( + planner_override, PlannerOverride + ): + planner_override_id = obj_or_id( + planner_override, "planner_override", (PlannerOverride,) + ) + else: + raise RequiredFieldMissing( + "planner_override is required as an object or as an int." + ) + + response = self.__requester.request( + "GET", + "planner/overrides/{}".format(planner_override_id), + _kwargs=combine_kwargs(**kwargs), + ) + + return PlannerOverride(self.__requester, response.json()) + + def get_planner_overrides(self, **kwargs): + """ + Retrieve a planner override for the current user + + :calls: `GET /api/v1/planner/overrides \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.poll.Poll` + :class:`canvasapi.planner.PlannerOverride` """ - from canvasapi.poll import Poll + from canvasapi.planner import PlannerOverride return PaginatedList( - Poll, + PlannerOverride, self.__requester, "GET", - "polls", - _root="polls", + "planner/overrides", _kwargs=combine_kwargs(**kwargs), ) @@ -1140,201 +973,368 @@ def get_poll(self, poll, **kwargs): ) return Poll(self.__requester, response.json()["polls"][0]) - def create_poll(self, poll, **kwargs): + def get_polls(self, **kwargs): """ - Create a new poll for the current user. + Returns a paginated list of polls for the current user - :calls: `POST /api/v1/polls \ - `_ + :calls: `GET /api/1/polls \ + `_ - :param poll: List of polls to create. `'question'` key is required. - :type poll: list of dict - :rtype: :class:`canvasapi.poll.Poll` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.poll.Poll` """ from canvasapi.poll import Poll - if ( - isinstance(poll, list) - and isinstance(poll[0], dict) - and "question" in poll[0] - ): - kwargs["poll"] = poll + return PaginatedList( + Poll, + self.__requester, + "GET", + "polls", + _root="polls", + _kwargs=combine_kwargs(**kwargs), + ) + + def get_progress(self, progress, **kwargs): + """ + Get a specific progress. + + :calls: `GET /api/v1/progress/:id + `_ + + :param progress: The object or ID of the progress to retrieve. + :type progress: int, str or :class:`canvasapi.progress.Progress` + + :rtype: :class:`canvasapi.progress.Progress` + """ + + from canvasapi.progress import Progress + + progress_id = obj_or_id(progress, "progress", (Progress,)) + + response = self.__requester.request( + "GET", "progress/{}".format(progress_id), _kwargs=combine_kwargs(**kwargs) + ) + return Progress(self.__requester, response.json()) + + def get_root_outcome_group(self): + """ + Redirect to root outcome group for context + + :calls: `GET /api/v1/global/root_outcome_group \ + `_ + + :returns: The OutcomeGroup of the context. + :rtype: :class:`canvasapi.outcome.OutcomeGroup` + """ + from canvasapi.outcome import OutcomeGroup + + response = self.__requester.request("GET", "global/root_outcome_group") + return OutcomeGroup(self.__requester, response.json()) + + def get_section(self, section, use_sis_id=False, **kwargs): + """ + Get details about a specific section. + + :calls: `GET /api/v1/sections/:id \ + `_ + + :param section: The object or ID of the section to get. + :type section: :class:`canvasapi.section.Section` or int + :param use_sis_id: Whether or not section_id is an sis ID. + Defaults to `False`. + :type use_sis_id: bool + + :rtype: :class:`canvasapi.section.Section` + """ + if use_sis_id: + section_id = section + uri_str = "sections/sis_section_id:{}" else: - raise RequiredFieldMissing( - "Dictionary with key 'question' and is required." - ) + section_id = obj_or_id(section, "section", (Section,)) + uri_str = "sections/{}" response = self.__requester.request( - "POST", "polls", _kwargs=combine_kwargs(**kwargs) + "GET", uri_str.format(section_id), _kwargs=combine_kwargs(**kwargs) ) - return Poll(self.__requester, response.json()["polls"][0]) + return Section(self.__requester, response.json()) - def get_planner_notes(self, **kwargs): + def get_todo_items(self): """ - Retrieve the paginated list of planner notes + Return the current user's list of todo items, as seen on the user dashboard. - :calls: `GET /api/v1/planner_notes \ - `_ + :calls: `GET /api/v1/users/self/todo \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.planner.PlannerNote` + :rtype: dict + """ + response = self.__requester.request("GET", "users/self/todo") + return response.json() + + def get_upcoming_events(self): + """ + Return the current user's upcoming events, i.e. the same things shown + in the dashboard 'Coming Up' sidebar. + + :calls: `GET /api/v1/users/self/upcoming_events \ + `_ + + :rtype: dict + """ + response = self.__requester.request("GET", "users/self/upcoming_events") + return response.json() + + def get_user(self, user, id_type=None): + """ + Retrieve a user by their ID. `id_type` denotes which endpoint to try as there are + several different IDs that can pull the same user record from Canvas. + + Refer to API documentation's + `User `_ + example to see the ID types a user can be retrieved with. + + :calls: `GET /api/v1/users/:id \ + `_ + + :param user: The user's object or ID. + :type user: :class:`canvasapi.user.User` or int + :param id_type: The ID type. + :type id_type: str + + :rtype: :class:`canvasapi.user.User` + """ + if id_type: + uri = "users/{}:{}".format(id_type, user) + elif user == "self": + uri = "users/self" + else: + user_id = obj_or_id(user, "user", (User,)) + uri = "users/{}".format(user_id) + + response = self.__requester.request("GET", uri) + return User(self.__requester, response.json()) + + def get_user_participants(self, appointment_group, **kwargs): + """ + List user participants in this appointment group. + + :calls: `GET /api/v1/appointment_groups/:id/users \ + `_ + + :param appointment_group: The object or ID of the appointment group. + :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` """ - from canvasapi.planner import PlannerNote + from canvasapi.appointment_group import AppointmentGroup + from canvasapi.user import User + + appointment_group_id = obj_or_id( + appointment_group, "appointment_group", (AppointmentGroup,) + ) return PaginatedList( - PlannerNote, + User, self.__requester, "GET", - "planner_notes", + "appointment_groups/{}/users".format(appointment_group_id), _kwargs=combine_kwargs(**kwargs), ) - def get_planner_note(self, planner_note, **kwargs): + def list_appointment_groups(self, **kwargs): """ - Retrieve a planner note for the current user + List appointment groups. - :calls: `GET /api/v1/planner_notes/:id \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.canvas.Canvas.get_appointment_groups` instead. - :param planner_note: The ID of the planner note to retrieve. - :type planner_note: int or :class:`canvasapi.planner.PlannerNote` + :calls: `GET /api/v1/appointment_groups \ + `_ - :rtype: :class:`canvasapi.planner.PlannerNote` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.appointment_group.AppointmentGroup` """ - from canvasapi.planner import PlannerNote + warnings.warn( + "`list_appointment_groups` is being deprecated and will be removed" + " in a future version. Use `get_appointment_groups` instead.", + DeprecationWarning, + ) - if isinstance(planner_note, int) or isinstance(planner_note, PlannerNote): - planner_note_id = obj_or_id(planner_note, "planner_note", (PlannerNote,)) - else: - raise RequiredFieldMissing( - "planner_note is required as an object or as an int." - ) + return self.get_appointment_groups(**kwargs) - response = self.__requester.request( - "GET", - "planner_notes/{}".format(planner_note_id), - _kwargs=combine_kwargs(**kwargs), - ) + def list_calendar_events(self, **kwargs): + """ + List calendar events. - return PlannerNote(self.__requester, response.json()) + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.canvas.Canvas.get_calendar_events` instead. - def create_planner_note(self, **kwargs): + :calls: `GET /api/v1/calendar_events \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.calendar_event.CalendarEvent` """ - Create a planner note for the current user + warnings.warn( + "`list_calendar_events` is being deprecated and will be removed " + "in a future version. Use `get_calendar_events` instead", + DeprecationWarning, + ) - :calls: `POST /api/v1/planner_notes \ - `_ + return self.get_calendar_events(**kwargs) - :rtype: :class:`canvasapi.planner.PlannerNote` + def list_group_participants(self, appointment_group, **kwargs): """ - from canvasapi.planner import PlannerNote + List student group participants in this appointment group. - response = self.__requester.request( - "POST", "planner_notes", _kwargs=combine_kwargs(**kwargs) - ) - return PlannerNote(self.__requester, response.json()) + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi. canvas.Canvas.get_group_participants` instead. - def get_planner_overrides(self, **kwargs): + :calls: `GET /api/v1/appointment_groups/:id/groups \ + `_ + + :param appointment_group: The object or ID of the appointment group. + :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` """ - Retrieve a planner override for the current user + warnings.warn( + "`list_group_participants` is being deprecated and will be removed " + "in a future version. Use `get_group_participants` instead", + DeprecationWarning, + ) - :calls: `GET /api/v1/planner/overrides \ - `_ + return self.get_group_participants(appointment_group, **kwargs) - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.planner.PlannerOverride` + def list_user_participants(self, appointment_group, **kwargs): """ - from canvasapi.planner import PlannerOverride + List user participants in this appointment group. - return PaginatedList( - PlannerOverride, - self.__requester, - "GET", - "planner/overrides", - _kwargs=combine_kwargs(**kwargs), + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi. canvas.Canvas.get_user_participants` instead. + + :calls: `GET /api/v1/appointment_groups/:id/users \ + `_ + + :param appointment_group: The object or ID of the appointment group. + :type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` + """ + warnings.warn( + "`list_user_participants` is being deprecated and will be removed in a future version." + " Use `get_user_participants` instead", + DeprecationWarning, ) - def get_planner_override(self, planner_override, **kwargs): + return self.get_user_participants(appointment_group, **kwargs) + + def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs): """ - Retrieve a planner override for the current user + Return single Calendar Event by id - :calls: `GET /api/v1/planner/overrides/:id \ - `_ + :calls: `POST /api/v1/calendar_events/:id/reservations \ + `_ - :param planner_override: The override or the ID of the planner override to retrieve. - :type planner_override: int or :class:`canvasapi.planner.PlannerOverride` + :param calendar_event: The object or ID of the calendar event. + :type calendar_event: :class:`canvasapi.calendar_event.CalendarEvent` or int - :rtype: :class:`canvasapi.planner.PlannerOverride` + :param participant_id: The ID of the participant, if given. + :type participant_id: str + + :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ - from canvasapi.planner import PlannerOverride + from canvasapi.calendar_event import CalendarEvent - if isinstance(planner_override, int) or isinstance( - planner_override, PlannerOverride - ): - planner_override_id = obj_or_id( - planner_override, "planner_override", (PlannerOverride,) + calendar_event_id = obj_or_id( + calendar_event, "calendar_event", (CalendarEvent,) + ) + + if participant_id: + uri = "calendar_events/{}/reservations/{}".format( + calendar_event_id, participant_id ) else: - raise RequiredFieldMissing( - "planner_override is required as an object or as an int." - ) + uri = "calendar_events/{}/reservations".format(calendar_event_id) response = self.__requester.request( - "GET", - "planner/overrides/{}".format(planner_override_id), - _kwargs=combine_kwargs(**kwargs), + "POST", uri, _kwargs=combine_kwargs(**kwargs) ) + return CalendarEvent(self.__requester, response.json()) - return PlannerOverride(self.__requester, response.json()) + def search_accounts(self, **kwargs): + """ + Return a list of up to 5 matching account domains. Partial matches on + name and domain are supported. - def create_planner_override(self, plannable_type, plannable_id, **kwargs): + :calls: `GET /api/v1/accounts/search \ + `_ + + :rtype: dict """ - Create a planner override for the current user + response = self.__requester.request( + "GET", "accounts/search", _kwargs=combine_kwargs(**kwargs) + ) + return response.json() - :calls: `POST /api/v1/planner/overrides \ - `_ + def search_all_courses(self, **kwargs): + """ + List all the courses visible in the public index. + Returns a list of dicts, each containing a single course. - :param plannable_type: Type of the item that you are overriding in the planner - :type plannable_type: str + :calls: `GET /api/v1/search/all_courses \ + `_ - :param plannable_id: ID of the item that you are overriding in the planner - :type plannable_id: int or :class:`canvasapi.planner.PlannerOverride` + :rtype: `list` + """ + response = self.__requester.request( + "GET", "search/all_courses", _kwargs=combine_kwargs(**kwargs) + ) + return response.json() - :rtype: :class:`canvasapi.planner.PlannerOverride` + def search_recipients(self, **kwargs): """ - from canvasapi.planner import PlannerOverride - from six import text_type, integer_types + Find valid recipients (users, courses and groups) that the current user + can send messages to. + Returns a list of mixed data types. - if isinstance(plannable_type, text_type): - kwargs["plannable_type"] = plannable_type - else: - raise RequiredFieldMissing("plannable_type is required as a str.") - if isinstance(plannable_id, integer_types): - kwargs["plannable_id"] = plannable_id - else: - raise RequiredFieldMissing("plannable_id is required as an int.") + :calls: `GET /api/v1/search/recipients \ + `_ + + :rtype: `list` + """ + if "search" not in kwargs: + kwargs["search"] = " " response = self.__requester.request( - "POST", "planner/overrides", _kwargs=combine_kwargs(**kwargs) + "GET", "search/recipients", _kwargs=combine_kwargs(**kwargs) ) - return PlannerOverride(self.__requester, response.json()) + return response.json() - def get_epub_exports(self, **kwargs): + def set_course_nickname(self, course, nickname): """ - Return a list of epub exports for the associated course. + Set a nickname for the given course. This will replace the + course's name in the output of subsequent API calls, as + well as in selected places in the Canvas web user interface. - :calls: `GET /api/v1/epub_exports\ - `_ + :calls: `PUT /api/v1/users/self/course_nicknames/:course_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course_epub_export.CourseEpubExport` + :param course: The ID of the course. + :type course: :class:`canvasapi.course.Course` or int + :param nickname: The nickname for the course. + :type nickname: str + + :rtype: :class:`canvasapi.course.CourseNickname` """ + from canvasapi.course import CourseNickname - return PaginatedList( - CourseEpubExport, - self.__requester, - "GET", - "epub_exports", - _root="courses", - kwargs=combine_kwargs(**kwargs), + course_id = obj_or_id(course, "course", (Course,)) + + response = self.__requester.request( + "PUT", "users/self/course_nicknames/{}".format(course_id), nickname=nickname ) + return CourseNickname(self.__requester, response.json()) diff --git a/canvasapi/canvas_object.py b/canvasapi/canvas_object.py index f146ade5..184c26ff 100644 --- a/canvasapi/canvas_object.py +++ b/canvasapi/canvas_object.py @@ -38,13 +38,6 @@ def __repr__(self): # pragma: no cover ) # noqa return "{}({})".format(classname, attrs) - def to_json(self): - """ - Return the original JSON response from the API that was used to - construct the object. - """ - return json.dumps(self.attributes) - def set_attributes(self, attributes): """ Load this object with attributes. @@ -79,3 +72,10 @@ def set_attributes(self, attributes): naive = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") aware = naive.replace(tzinfo=pytz.utc) self.__setattr__(attribute + "_date", aware) + + def to_json(self): + """ + Return the original JSON response from the API that was used to + construct the object. + """ + return json.dumps(self.attributes) diff --git a/canvasapi/communication_channel.py b/canvasapi/communication_channel.py index 76c29f1b..240d58ef 100644 --- a/canvasapi/communication_channel.py +++ b/canvasapi/communication_channel.py @@ -14,29 +14,66 @@ class CommunicationChannel(CanvasObject): def __str__(self): return "{} ({})".format(self.address, self.id) - def list_preferences(self, **kwargs): + def delete(self): """ - Fetch all preferences for the given communication channel. + Delete the current communication_channel - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.communication_channel.CommunicationChannel.get_preferences` - instead. + :calls: `DELETE /api/v1/users/:user_id/communication_channels/:id \ + `_ + + :returns: True if successfully deleted; False otherwise. + :rtype: bool + """ + + response = self._requester.request( + "DELETE", "users/{}/communication_channels/{}".format(self.user_id, self.id) + ) + + return response.json().get("workflow_state") == "deleted" + + def get_preference(self, notification): + """ + Fetch the preference for the given notification for the given + communication channel. :calls: `GET - /api/v1/users/:user_id/communication_channels/:communication_channel_id/ \ - notification_preferences \ - `_ + /api/v1/users/:user_id/communication_channels/ \ + :communication_channel_id/notification_preferences/:notification \ + `_ - :rtype: `list` + :param notification: The name of the notification. + :type notification: str + :rtype: :class:`canvasapi.notification_preference.NotificationPreference` """ - warnings.warn( - "`list_preferences` is being deprecated and will be removed in a future version." - " Use `get_preferences` instead", - DeprecationWarning, + response = self._requester.request( + "GET", + "users/{}/communication_channels/{}/notification_preferences/{}".format( + self.user_id, self.id, notification + ), ) + data = response.json()["notification_preferences"][0] + return NotificationPreference(self._requester, data) - return self.get_preferences(**kwargs) + def get_preference_categories(self, **kwargs): + """ + Fetch all notification preference categories for the given communication + channel. + + :calls: `GET + /api/v1/users/:user_id/communication_channels/ \ + :communication_channel_id/notification_preference_categories \ + `_ + + :rtype: `list` + """ + response = self._requester.request( + "GET", + "users/{}/communication_channels/{}/notification_preference_categories".format( + self.user_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + return response.json()["categories"] def get_preferences(self, **kwargs): """ @@ -86,49 +123,65 @@ def list_preference_categories(self, **kwargs): return self.get_preference_categories(**kwargs) - def get_preference_categories(self, **kwargs): + def list_preferences(self, **kwargs): """ - Fetch all notification preference categories for the given communication - channel. + Fetch all preferences for the given communication channel. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.communication_channel.CommunicationChannel.get_preferences` + instead. :calls: `GET - /api/v1/users/:user_id/communication_channels/ \ - :communication_channel_id/notification_preference_categories \ - `_ + /api/v1/users/:user_id/communication_channels/:communication_channel_id/ \ + notification_preferences \ + `_ :rtype: `list` """ - response = self._requester.request( - "GET", - "users/{}/communication_channels/{}/notification_preference_categories".format( - self.user_id, self.id - ), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_preferences` is being deprecated and will be removed in a future version." + " Use `get_preferences` instead", + DeprecationWarning, ) - return response.json()["categories"] - def get_preference(self, notification): + return self.get_preferences(**kwargs) + + def update_multiple_preferences(self, notification_preferences, **kwargs): """ - Fetch the preference for the given notification for the given - communication channel. + Change preferences for multiple notifications based on the category + for a single communication channel. - :calls: `GET - /api/v1/users/:user_id/communication_channels/ \ - :communication_channel_id/notification_preferences/:notification \ - `_ + :calls: `PUT + /api/v1/users/self/communication_channels/:communication_channel_id/ \ + notification_preferences \ + `_ + + :param notification_preferences: Dict that indicates the frequency for \ + different notification types. + :type notification: dict - :param notification: The name of the notification. - :type notification: str :rtype: :class:`canvasapi.notification_preference.NotificationPreference` """ - response = self._requester.request( - "GET", - "users/{}/communication_channels/{}/notification_preferences/{}".format( - self.user_id, self.id, notification - ), - ) - data = response.json()["notification_preferences"][0] - return NotificationPreference(self._requester, data) + if isinstance(notification_preferences, dict) and notification_preferences: + + for key, value in notification_preferences.items(): + try: + if not value["frequency"]: + return False + except KeyError: + return False + + kwargs["notification_preferences"] = notification_preferences + response = self._requester.request( + "PUT", + "users/self/communication_channels/{}/notification_preferences".format( + self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + return response.json()["notification_preferences"] + return False def update_preference(self, notification, frequency, **kwargs): """ @@ -186,56 +239,3 @@ def update_preferences_by_catagory(self, category, frequency, **kwargs): _kwargs=combine_kwargs(**kwargs), ) return response.json()["notification_preferences"] - - def update_multiple_preferences(self, notification_preferences, **kwargs): - """ - Change preferences for multiple notifications based on the category - for a single communication channel. - - :calls: `PUT - /api/v1/users/self/communication_channels/:communication_channel_id/ \ - notification_preferences \ - `_ - - :param notification_preferences: Dict that indicates the frequency for \ - different notification types. - :type notification: dict - - :rtype: :class:`canvasapi.notification_preference.NotificationPreference` - """ - if isinstance(notification_preferences, dict) and notification_preferences: - - for key, value in notification_preferences.items(): - try: - if not value["frequency"]: - return False - except KeyError: - return False - - kwargs["notification_preferences"] = notification_preferences - response = self._requester.request( - "PUT", - "users/self/communication_channels/{}/notification_preferences".format( - self.id - ), - _kwargs=combine_kwargs(**kwargs), - ) - return response.json()["notification_preferences"] - return False - - def delete(self): - """ - Delete the current communication_channel - - :calls: `DELETE /api/v1/users/:user_id/communication_channels/:id \ - `_ - - :returns: True if successfully deleted; False otherwise. - :rtype: bool - """ - - response = self._requester.request( - "DELETE", "users/{}/communication_channels/{}".format(self.user_id, self.id) - ) - - return response.json().get("workflow_state") == "deleted" diff --git a/canvasapi/course.py b/canvasapi/course.py index 509001d3..9e4d6873 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -38,6 +38,39 @@ class Course(CanvasObject): def __str__(self): return "{} {} ({})".format(self.course_code, self.name, self.id) + def add_grading_standards(self, title, grading_scheme_entry, **kwargs): + """ + Create a new grading standard for the course. + + :calls: `POST /api/v1/courses/:course_id/grading_standards \ + `_ + + :param title: The title for the Grading Standard + :type title: str + :param grading_scheme: A list of dictionaries containing keys for "name" and "value" + :type grading_scheme: list[dict] + :rtype: :class:`canvasapi.grading_standards.GradingStandard` + """ + if not isinstance(grading_scheme_entry, list) or len(grading_scheme_entry) <= 0: + raise ValueError("Param `grading_scheme_entry` must be a non-empty list.") + + for entry in grading_scheme_entry: + if not isinstance(entry, dict): + raise ValueError("grading_scheme_entry must consist of dictionaries.") + if "name" not in entry or "value" not in entry: + raise ValueError( + "Dictionaries with keys 'name' and 'value' are required." + ) + kwargs["grading_scheme_entry"] = grading_scheme_entry + + response = self._requester.request( + "POST", + "courses/%s/grading_standards" % (self.id), + title=title, + _kwargs=combine_kwargs(**kwargs), + ) + return GradingStandard(self._requester, response.json()) + def conclude(self): """ Mark this course as concluded. @@ -54,76 +87,63 @@ def conclude(self): return response.json().get("conclude") - def create_assignment_overrides(self, assignment_overrides, **kwargs): + def create_assignment(self, assignment, **kwargs): """ - Create the specified overrides for each assignment. + Create a new assignment for this course. - :calls: `POST /api/v1/courses/:course_id/assignments/overrides \ - `_ + Note: The assignment is created in the active state. - :param assignment_overrides: Attributes for the new assignment overrides. - :type assignment_overrides: list + :calls: `POST /api/v1/courses/:course_id/assignments \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.assignment.AssignmentOverride` + :param assignment: The attributes of the assignment + :type assignment: dict + :rtype: :class:`canvasapi.assignment.Assignment` """ - from canvasapi.assignment import AssignmentOverride + from canvasapi.assignment import Assignment - kwargs["assignment_overrides"] = assignment_overrides + if isinstance(assignment, dict) and "name" in assignment: + kwargs["assignment"] = assignment + else: + raise RequiredFieldMissing("Dictionary with key 'name' is required.") - return PaginatedList( - AssignmentOverride, - self._requester, + response = self._requester.request( "POST", - "courses/{}/assignments/overrides".format(self.id), - {"course_id": self.id}, + "courses/{}/assignments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def delete(self): - """ - Permanently delete this course. - - :calls: `DELETE /api/v1/courses/:id \ - `_ - - :returns: True if the course was deleted, False otherwise. - :rtype: bool - """ - response = self._requester.request( - "DELETE", "courses/{}".format(self.id), event="delete" - ) - return response.json().get("delete") + return Assignment(self._requester, response.json()) - def update(self, **kwargs): + def create_assignment_group(self, **kwargs): """ - Update this course. + Create a new assignment group for this course. - :calls: `PUT /api/v1/courses/:id \ - `_ + :calls: `POST /api/v1/courses/:course_id/assignment_groups \ + `_ - :returns: True if the course was updated, False otherwise. - :rtype: bool + :rtype: :class:`canvasapi.assignment.AssignmentGroup` """ + from canvasapi.assignment import AssignmentGroup + response = self._requester.request( - "PUT", "courses/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) + "POST", + "courses/{}/assignment_groups".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) + response_json = response.json() + response_json.update({"course_id": self.id}) - if response.json().get("name"): - super(Course, self).set_attributes(response.json()) - - return response.json().get("name") + return AssignmentGroup(self._requester, response_json) - def update_assignment_overrides(self, assignment_overrides, **kwargs): + def create_assignment_overrides(self, assignment_overrides, **kwargs): """ - Update a list of specified overrides for each assignment. - - Note: All current overridden values must be supplied if they are to be retained. + Create the specified overrides for each assignment. - :calls: `PUT /api/v1/courses/:course_id/assignments/overrides \ - `_ + :calls: `POST /api/v1/courses/:course_id/assignments/overrides \ + `_ - :param assignment_overrides: Attributes for the updated assignment overrides. + :param assignment_overrides: Attributes for the new assignment overrides. :type assignment_overrides: list :rtype: :class:`canvasapi.paginated_list.PaginatedList` of @@ -136,335 +156,254 @@ def update_assignment_overrides(self, assignment_overrides, **kwargs): return PaginatedList( AssignmentOverride, self._requester, - "PUT", + "POST", "courses/{}/assignments/overrides".format(self.id), {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) - def get_user(self, user, user_id_type=None): + def create_content_migration(self, migration_type, **kwargs): """ - Retrieve a user by their ID. `user_id_type` denotes which endpoint to try as there are - several different ids that can pull the same user record from Canvas. + Create a content migration. - :calls: `GET /api/v1/courses/:course_id/users/:id \ - `_ + :calls: `POST /api/v1/courses/:course_id/content_migrations \ + `_ - :param user: The object or ID of the user to retrieve. - :type user: :class:`canvasapi.user.User` or int - :param user_id_type: The type of the ID to search for. - :type user_id_type: str + :param migration_type: The migrator type to use in this migration + :type migration_type: str or :class:`canvasapi.content_migration.Migrator` - :rtype: :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.content_migration.ContentMigration` """ - from canvasapi.user import User + from canvasapi.content_migration import ContentMigration, Migrator - if user_id_type: - uri = "courses/{}/users/{}:{}".format(self.id, user_id_type, user) + if isinstance(migration_type, Migrator): + kwargs["migration_type"] = migration_type.type + elif isinstance(migration_type, string_types): + kwargs["migration_type"] = migration_type else: - user_id = obj_or_id(user, "user", (User,)) - uri = "courses/{}/users/{}".format(self.id, user_id) + raise TypeError("Parameter migration_type must be of type Migrator or str") - response = self._requester.request("GET", uri) - return User(self._requester, response.json()) + response = self._requester.request( + "POST", + "courses/{}/content_migrations".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) - def get_users(self, **kwargs): + response_json = response.json() + response_json.update({"course_id": self.id}) + + return ContentMigration(self._requester, response_json) + + def create_course_section(self, **kwargs): """ - List all users in a course. + Create a new section for this course. - :calls: `GET /api/v1/courses/:course_id/search_users \ - `_ + :calls: `POST /api/v1/courses/:course_id/sections \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.course.Section` """ - from canvasapi.user import User - return PaginatedList( - User, - self._requester, - "GET", - "courses/{}/search_users".format(self.id), + from canvasapi.section import Section + + response = self._requester.request( + "POST", + "courses/{}/sections".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def enroll_user(self, user, enrollment_type, **kwargs): - """ - Create a new user enrollment for a course or a section. - - :calls: `POST /api/v1/courses/:course_id/enrollments \ - `_ + return Section(self._requester, response.json()) - :param user: The object or ID of the user to enroll in this course. - :type user: :class:`canvasapi.user.User` or int - :param enrollment_type: The type of enrollment. - :type enrollment_type: str - :rtype: :class:`canvasapi.enrollment.Enrollment` + def create_discussion_topic(self, **kwargs): """ - from canvasapi.enrollment import Enrollment - from canvasapi.user import User + Creates a new discussion topic for the course or group. - kwargs["enrollment[user_id]"] = obj_or_id(user, "user", (User,)) - kwargs["enrollment[type]"] = enrollment_type + :calls: `POST /api/v1/courses/:course_id/discussion_topics \ + `_ + :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` + """ response = self._requester.request( "POST", - "courses/{}/enrollments".format(self.id), + "courses/{}/discussion_topics".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return Enrollment(self._requester, response.json()) + response_json = response.json() + response_json.update({"course_id": self.id}) - def get_recent_students(self): + return DiscussionTopic(self._requester, response_json) + + def create_epub_export(self, **kwargs): """ - Return a list of students in the course ordered by how recently they - have logged in. + Create an ePub export for a course. - :calls: `GET /api/v1/courses/:course_id/recent_students \ - `_ + :calls: `POST /api/v1/courses/:course_id/epub_exports/:id\ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.course_epub_export.CourseEpubExport` """ - from canvasapi.user import User - return PaginatedList( - User, self._requester, "GET", "courses/{}/recent_students".format(self.id) + response = self._requester.request( + "POST", + "courses/{}/epub_exports/".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - def preview_html(self, html): + return CourseEpubExport(self._requester, response.json()) + + def create_external_feed(self, url, **kwargs): """ - Preview HTML content processed for this course. + Create a new external feed for the course. - :calls: `POST /api/v1/courses/:course_id/preview_html \ - `_ + :calls: `POST /api/v1/courses/:course_id/external_feeds \ + `_ - :param html: The HTML code to preview. - :type html: str - :rtype: str + :param url: The url of the external rss or atom feed + :type url: str + :rtype: :class:`canvasapi.external_feed.ExternalFeed` """ + from canvasapi.external_feed import ExternalFeed + response = self._requester.request( - "POST", "courses/{}/preview_html".format(self.id), html=html + "POST", + "courses/{}/external_feeds".format(self.id), + url=url, + _kwargs=combine_kwargs(**kwargs), ) - return response.json().get("html", "") + return ExternalFeed(self._requester, response.json()) - def get_settings(self): + def create_external_tool( + self, name, privacy_level, consumer_key, shared_secret, **kwargs + ): """ - Returns this course's settings. - - :calls: `GET /api/v1/courses/:course_id/settings \ - `_ + Create an external tool in the current course. - :rtype: dict - """ - response = self._requester.request("GET", "courses/{}/settings".format(self.id)) - return response.json() + :calls: `POST /api/v1/courses/:course_id/external_tools \ + `_ - def update_settings(self, **kwargs): + :param name: The name of the tool + :type name: str + :param privacy_level: What information to send to the external + tool. Options are "anonymous", "name_only", "public" + :type privacy_level: str + :param consumer_key: The consumer key for the external tool + :type consumer_key: str + :param shared_secret: The shared secret with the external tool + :type shared_secret: str + :rtype: :class:`canvasapi.external_tool.ExternalTool` """ - Update a course's settings. - - :calls: `PUT /api/v1/courses/:course_id/settings \ - `_ + from canvasapi.external_tool import ExternalTool - :rtype: dict - """ response = self._requester.request( - "PUT", "courses/{}/settings".format(self.id), **kwargs + "POST", + "courses/{}/external_tools".format(self.id), + name=name, + privacy_level=privacy_level, + consumer_key=consumer_key, + shared_secret=shared_secret, + _kwargs=combine_kwargs(**kwargs), ) - return response.json() - - def upload(self, file, **kwargs): - """ - Upload a file to this course. - - :calls: `POST /api/v1/courses/:course_id/files \ - `_ + response_json = response.json() + response_json.update({"course_id": self.id}) - :param file: The file or path of the file to upload. - :type file: file or str - :returns: True if the file uploaded successfully, False otherwise, \ - and the JSON response from the API. - :rtype: tuple - """ - return Uploader( - self._requester, "courses/{}/files".format(self.id), file, **kwargs - ).start() + return ExternalTool(self._requester, response_json) - def reset(self): + def create_folder(self, name, **kwargs): """ - Delete the current course and create a new equivalent course - with no content, but all sections and users moved over. + Creates a folder in this course. - :calls: `POST /api/v1/courses/:course_id/reset_content \ - `_ + :calls: `POST /api/v1/courses/:course_id/folders \ + `_ - :rtype: :class:`canvasapi.course.Course` + :param name: The name of the folder. + :type name: str + :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - "POST", "courses/{}/reset_content".format(self.id) - ) - return Course(self._requester, response.json()) - - def get_enrollments(self, **kwargs): - """ - List all of the enrollments in this course. - - :calls: `GET /api/v1/courses/:course_id/enrollments \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.enrollment.Enrollment` - """ - from canvasapi.enrollment import Enrollment - - return PaginatedList( - Enrollment, - self._requester, - "GET", - "courses/{}/enrollments".format(self.id), + "POST", + "courses/{}/folders".format(self.id), + name=name, _kwargs=combine_kwargs(**kwargs), ) + return Folder(self._requester, response.json()) - def get_assignment(self, assignment, **kwargs): + def create_group_category(self, name, **kwargs): """ - Return the assignment with the given ID. - - :calls: `GET /api/v1/courses/:course_id/assignments/:id \ - `_ + Create a group category. - :param assignment: The object or ID of the assignment to retrieve. - :type assignment: :class:`canvasapi.assignment.Assignment` or int + :calls: `POST /api/v1/courses/:course_id/group_categories \ + `_ - :rtype: :class:`canvasapi.assignment.Assignment` + :param name: Name of the category. + :type name: str + :rtype: :class:`canvasapi.group.GroupCategory` """ - from canvasapi.assignment import Assignment - - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + from canvasapi.group import GroupCategory response = self._requester.request( - "GET", - "courses/{}/assignments/{}".format(self.id, assignment_id), - _kwargs=combine_kwargs(**kwargs), - ) - return Assignment(self._requester, response.json()) - - def get_assignment_overrides(self, assignment_overrides, **kwargs): - """ - List the specified overrides in this course, providing they target - sections/groups/students visible to the current user. - - :calls: `GET /api/v1/courses/:course_id/assignments/overrides \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.assignment.AssignmentOverride` - """ - from canvasapi.assignment import AssignmentOverride - - kwargs["assignment_overrides"] = assignment_overrides - - return PaginatedList( - AssignmentOverride, - self._requester, - "GET", - "courses/{}/assignments/overrides".format(self.id), - {"course_id": self.id}, - _kwargs=combine_kwargs(**kwargs), - ) - - def get_assignments(self, **kwargs): - """ - List all of the assignments in this course. - - :calls: `GET /api/v1/courses/:course_id/assignments \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.assignment.Assignment` - """ - from canvasapi.assignment import Assignment - - return PaginatedList( - Assignment, - self._requester, - "GET", - "courses/{}/assignments".format(self.id), + "POST", + "courses/{}/group_categories".format(self.id), + name=name, _kwargs=combine_kwargs(**kwargs), ) + return GroupCategory(self._requester, response.json()) - def create_assignment(self, assignment, **kwargs): + def create_module(self, module, **kwargs): """ - Create a new assignment for this course. - - Note: The assignment is created in the active state. + Create a new module. - :calls: `POST /api/v1/courses/:course_id/assignments \ - `_ + :calls: `POST /api/v1/courses/:course_id/modules \ + `_ - :param assignment: The attributes of the assignment - :type assignment: dict - :rtype: :class:`canvasapi.assignment.Assignment` + :param module: The attributes for the module. + :type module: dict + :returns: The created module. + :rtype: :class:`canvasapi.module.Module` """ - from canvasapi.assignment import Assignment + from canvasapi.module import Module - if isinstance(assignment, dict) and "name" in assignment: - kwargs["assignment"] = assignment + if isinstance(module, dict) and "name" in module: + kwargs["module"] = module else: raise RequiredFieldMissing("Dictionary with key 'name' is required.") response = self._requester.request( "POST", - "courses/{}/assignments".format(self.id), + "courses/{}/modules".format(self.id), _kwargs=combine_kwargs(**kwargs), ) + module_json = response.json() + module_json.update({"course_id": self.id}) - return Assignment(self._requester, response.json()) - - def get_quizzes(self, **kwargs): - """ - Return a list of quizzes belonging to this course. - - :calls: `GET /api/v1/courses/:course_id/quizzes \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.quiz.Quiz` - """ - from canvasapi.quiz import Quiz - - return PaginatedList( - Quiz, - self._requester, - "GET", - "courses/{}/quizzes".format(self.id), - {"course_id": self.id}, - _kwargs=combine_kwargs(**kwargs), - ) + return Module(self._requester, module_json) - def get_quiz(self, quiz): + def create_page(self, wiki_page, **kwargs): """ - Return the quiz with the given id. - - :calls: `GET /api/v1/courses/:course_id/quizzes/:id \ - `_ + Create a new wiki page. - :param quiz: The object or ID of the quiz to retrieve. - :type quiz: :class:`canvasapi.quiz.Quiz` or int + :calls: `POST /api/v1/courses/:course_id/pages \ + `_ - :rtype: :class:`canvasapi.quiz.Quiz` + :param title: The title for the page. + :type title: dict + :returns: The created page. + :rtype: :class:`canvasapi.course.Course` """ - from canvasapi.quiz import Quiz - quiz_id = obj_or_id(quiz, "quiz", (Quiz,)) + if isinstance(wiki_page, dict) and "title" in wiki_page: + kwargs["wiki_page"] = wiki_page + else: + raise RequiredFieldMissing("Dictionary with key 'title' is required.") response = self._requester.request( - "GET", "courses/{}/quizzes/{}".format(self.id, quiz_id) + "POST", "courses/{}/pages".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - quiz_json = response.json() - quiz_json.update({"course_id": self.id}) - return Quiz(self._requester, quiz_json) + page_json = response.json() + page_json.update({"course_id": self.id}) + + return Page(self._requester, page_json) def create_quiz(self, quiz, **kwargs): """ @@ -494,435 +433,418 @@ def create_quiz(self, quiz, **kwargs): return Quiz(self._requester, quiz_json) - def get_modules(self, **kwargs): + def delete(self): """ - Return a list of modules in this course. + Permanently delete this course. - :calls: `GET /api/v1/courses/:course_id/modules \ - `_ + :calls: `DELETE /api/v1/courses/:id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.module.Module` - """ - from canvasapi.module import Module - - return PaginatedList( - Module, - self._requester, - "GET", - "courses/{}/modules".format(self.id), - {"course_id": self.id}, - _kwargs=combine_kwargs(**kwargs), + :returns: True if the course was deleted, False otherwise. + :rtype: bool + """ + response = self._requester.request( + "DELETE", "courses/{}".format(self.id), event="delete" ) + return response.json().get("delete") - def get_module(self, module, **kwargs): + def delete_external_feed(self, feed): """ - Retrieve a single module by ID. + Deletes the external feed. - :calls: `GET /api/v1/courses/:course_id/modules/:id \ - `_ + :calls: `DELETE /api/v1/courses/:course_id/external_feeds/:external_feed_id \ + `_ - :param module: The object or ID of the module to retrieve. - :type module: :class:`canvasapi.module.Module` or int + :param feed: The object or ID of the feed to be deleted. + :type feed: :class:`canvasapi.external_feed.ExternalFeed` or int - :rtype: :class:`canvasapi.module.Module` + :rtype: :class:`canvasapi.external_feed.ExternalFeed` """ - from canvasapi.module import Module + from canvasapi.external_feed import ExternalFeed - module_id = obj_or_id(module, "module", (Module,)) + feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) response = self._requester.request( - "GET", "courses/{}/modules/{}".format(self.id, module_id) + "DELETE", "courses/{}/external_feeds/{}".format(self.id, feed_id) ) - module_json = response.json() - module_json.update({"course_id": self.id}) - - return Module(self._requester, module_json) + return ExternalFeed(self._requester, response.json()) - def create_module(self, module, **kwargs): + def edit_front_page(self, **kwargs): """ - Create a new module. + Update the title or contents of the front page. - :calls: `POST /api/v1/courses/:course_id/modules \ - `_ + :calls: `PUT /api/v1/courses/:course_id/front_page \ + `_ - :param module: The attributes for the module. - :type module: dict - :returns: The created module. - :rtype: :class:`canvasapi.module.Module` + :rtype: :class:`canvasapi.course.Course` """ - from canvasapi.module import Module - - if isinstance(module, dict) and "name" in module: - kwargs["module"] = module - else: - raise RequiredFieldMissing("Dictionary with key 'name' is required.") - response = self._requester.request( - "POST", - "courses/{}/modules".format(self.id), + "PUT", + "courses/{}/front_page".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - module_json = response.json() - module_json.update({"course_id": self.id}) + page_json = response.json() + page_json.update({"course_id": self.id}) - return Module(self._requester, module_json) + return Page(self._requester, page_json) - def get_external_tool(self, tool): + def enroll_user(self, user, enrollment_type, **kwargs): """ - :calls: `GET /api/v1/courses/:course_id/external_tools/:external_tool_id \ - `_ + Create a new user enrollment for a course or a section. - :param tool: The object or ID of the tool to retrieve. - :type tool: :class:`canvasapi.external_tool.ExternalTool` or int + :calls: `POST /api/v1/courses/:course_id/enrollments \ + `_ - :rtype: :class:`canvasapi.external_tool.ExternalTool` + :param user: The object or ID of the user to enroll in this course. + :type user: :class:`canvasapi.user.User` or int + :param enrollment_type: The type of enrollment. + :type enrollment_type: str + :rtype: :class:`canvasapi.enrollment.Enrollment` """ - from canvasapi.external_tool import ExternalTool + from canvasapi.enrollment import Enrollment + from canvasapi.user import User - tool_id = obj_or_id(tool, "tool", (ExternalTool,)) + kwargs["enrollment[user_id]"] = obj_or_id(user, "user", (User,)) + kwargs["enrollment[type]"] = enrollment_type response = self._requester.request( - "GET", "courses/{}/external_tools/{}".format(self.id, tool_id) + "POST", + "courses/{}/enrollments".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - tool_json = response.json() - tool_json.update({"course_id": self.id}) - return ExternalTool(self._requester, tool_json) + return Enrollment(self._requester, response.json()) - def get_external_tools(self, **kwargs): + def export_content(self, export_type, **kwargs): """ - :calls: `GET /api/v1/courses/:course_id/external_tools \ - `_ + Begin a content export job for a course. - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.external_tool.ExternalTool` + :calls: `POST /api/v1/courses/:course_id/content_exports\ + `_ + + :param export_type: The type of content to export. + :type export_type: str + + :rtype: :class:`canvasapi.content_export.ContentExport` """ - from canvasapi.external_tool import ExternalTool + from canvasapi.content_export import ContentExport - return PaginatedList( - ExternalTool, - self._requester, - "GET", - "courses/{}/external_tools".format(self.id), - {"course_id": self.id}, + kwargs["export_type"] = export_type + + response = self._requester.request( + "POST", + "courses/{}/content_exports".format(self.id), _kwargs=combine_kwargs(**kwargs), ) + return ContentExport(self._requester, response.json()) - def get_sections(self, **kwargs): + def get_all_outcome_links_in_context(self): """ - List all sections in a course. + Get all outcome links for context - BETA - :calls: `GET /api/v1/courses/:course_id/sections \ - `_ + :calls: `GET /api/v1/courses/:course_id/outcome_group_links \ + `_ + :returns: Paginated List of OutcomesLinks in the context. :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.section.Section` + :class:`canvasapi.outcome.OutcomeLink` """ - from canvasapi.section import Section + from canvasapi.outcome import OutcomeLink return PaginatedList( - Section, + OutcomeLink, self._requester, "GET", - "courses/{}/sections".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "courses/{}/outcome_group_links".format(self.id), ) - def get_section(self, section, **kwargs): + def get_assignment(self, assignment, **kwargs): """ - Retrieve a section. + Return the assignment with the given ID. - :calls: `GET /api/v1/courses/:course_id/sections/:id \ - `_ + :calls: `GET /api/v1/courses/:course_id/assignments/:id \ + `_ - :param section: The object or ID of the section to retrieve. - :type section: :class:`canvasapi.section.Section` or int + :param assignment: The object or ID of the assignment to retrieve. + :type assignment: :class:`canvasapi.assignment.Assignment` or int - :rtype: :class:`canvasapi.section.Section` + :rtype: :class:`canvasapi.assignment.Assignment` """ - from canvasapi.section import Section + from canvasapi.assignment import Assignment - section_id = obj_or_id(section, "section", (Section,)) + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) response = self._requester.request( "GET", - "courses/{}/sections/{}".format(self.id, section_id), + "courses/{}/assignments/{}".format(self.id, assignment_id), _kwargs=combine_kwargs(**kwargs), ) - return Section(self._requester, response.json()) + return Assignment(self._requester, response.json()) - def show_front_page(self): + def get_assignment_group(self, assignment_group, **kwargs): """ - Retrieve the content of the front page. - - :calls: `GET /api/v1/courses/:course_id/front_page \ - `_ + Retrieve specified assignment group for the specified course. - :rtype: :class:`canvasapi.course.Course` - """ - response = self._requester.request( - "GET", "courses/{}/front_page".format(self.id) - ) - page_json = response.json() - page_json.update({"course_id": self.id}) + :calls: `GET /api/v1/courses/:course_id/assignment_groups/:assignment_group_id \ + `_ - return Page(self._requester, page_json) + :param assignment_group: object or ID of assignment group. + :type assignment_group: :class:`canvasapi.assignment.AssignmentGroup` or int - def edit_front_page(self, **kwargs): + :rtype: :class:`canvasapi.assignment.AssignmentGroup` """ - Update the title or contents of the front page. + from canvasapi.assignment import AssignmentGroup - :calls: `PUT /api/v1/courses/:course_id/front_page \ - `_ + assignment_group_id = obj_or_id( + assignment_group, "assignment_group", (AssignmentGroup,) + ) - :rtype: :class:`canvasapi.course.Course` - """ response = self._requester.request( - "PUT", - "courses/{}/front_page".format(self.id), + "GET", + "courses/{}/assignment_groups/{}".format(self.id, assignment_group_id), _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"course_id": self.id}) + response_json = response.json() + response_json.update({"course_id": self.id}) - return Page(self._requester, page_json) + return AssignmentGroup(self._requester, response_json) - def get_pages(self, **kwargs): + def get_assignment_groups(self, **kwargs): """ - List the wiki pages associated with a course. + List assignment groups for the specified course. - :calls: `GET /api/v1/courses/:course_id/pages \ - `_ + :calls: `GET /api/v1/courses/:course_id/assignment_groups \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` + :class:`canvasapi.assignment.AssignmentGroup` """ + from canvasapi.assignment import AssignmentGroup + return PaginatedList( - Page, + AssignmentGroup, self._requester, "GET", - "courses/{}/pages".format(self.id), + "courses/{}/assignment_groups".format(self.id), {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) - def create_page(self, wiki_page, **kwargs): + def get_assignment_overrides(self, assignment_overrides, **kwargs): """ - Create a new wiki page. + List the specified overrides in this course, providing they target + sections/groups/students visible to the current user. - :calls: `POST /api/v1/courses/:course_id/pages \ - `_ + :calls: `GET /api/v1/courses/:course_id/assignments/overrides \ + `_ - :param title: The title for the page. - :type title: dict - :returns: The created page. - :rtype: :class:`canvasapi.course.Course` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.assignment.AssignmentOverride` """ + from canvasapi.assignment import AssignmentOverride - if isinstance(wiki_page, dict) and "title" in wiki_page: - kwargs["wiki_page"] = wiki_page - else: - raise RequiredFieldMissing("Dictionary with key 'title' is required.") + kwargs["assignment_overrides"] = assignment_overrides - response = self._requester.request( - "POST", "courses/{}/pages".format(self.id), _kwargs=combine_kwargs(**kwargs) + return PaginatedList( + AssignmentOverride, + self._requester, + "GET", + "courses/{}/assignments/overrides".format(self.id), + {"course_id": self.id}, + _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"course_id": self.id}) - - return Page(self._requester, page_json) - - def get_page(self, url): + def get_assignments(self, **kwargs): """ - Retrieve the contents of a wiki page. + List all of the assignments in this course. - :calls: `GET /api/v1/courses/:course_id/pages/:url \ - `_ + :calls: `GET /api/v1/courses/:course_id/assignments \ + `_ - :param url: The url for the page. - :type url: str - :returns: The specified page. - :rtype: :class:`canvasapi.course.Course` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.assignment.Assignment` """ + from canvasapi.assignment import Assignment - response = self._requester.request( - "GET", "courses/{}/pages/{}".format(self.id, url) + return PaginatedList( + Assignment, + self._requester, + "GET", + "courses/{}/assignments".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"course_id": self.id}) - - return Page(self._requester, page_json) - - def list_sections(self, **kwargs): - """ - Returns the list of sections for this course. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.course.Course.get_sections` instead. - - :calls: `GET /api/v1/courses/:course_id/sections \ - `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.section.Section` + def get_blueprint(self, template="default", **kwargs): """ - warnings.warn( - "`list_sections` is being deprecated and will be removed in a future version." - " Use `get_sections` instead", - DeprecationWarning, - ) - return self.get_sections(**kwargs) + Return the blueprint of a given ID. - def create_course_section(self, **kwargs): - """ - Create a new section for this course. + :calls: `GET /api/v1/courses/:course_id/blueprint_templates/:template_id \ + `_ - :calls: `POST /api/v1/courses/:course_id/sections \ - `_ + :param template: The object or ID of the blueprint template to get. + :type template: int or :class:`canvasapi.blueprint.BlueprintTemplate` - :rtype: :class:`canvasapi.course.Section` + :rtype: :class:`canvasapi.blueprint.BlueprintTemplate` """ + from canvasapi.blueprint import BlueprintTemplate - from canvasapi.section import Section + if template == "default": + template_id = template + else: + template_id = obj_or_id(template, "template", (BlueprintTemplate,)) response = self._requester.request( - "POST", - "courses/{}/sections".format(self.id), + "GET", + "courses/{}/blueprint_templates/{}".format(self.id, template_id), _kwargs=combine_kwargs(**kwargs), ) + return BlueprintTemplate(self._requester, response.json()) - return Section(self._requester, response.json()) - - def list_groups(self, **kwargs): + def get_content_export(self, content_export, **kwargs): """ - Return list of active groups for the specified course. + Return information about a single content export. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_groups` instead. + :calls: `GET /api/v1/courses/:course_id/content_exports/:id\ + `_ - :calls: `GET /api/v1/courses/:course_id/groups \ - `_ + :param content_export: The object or ID of the content export to show. + :type content_export: int or :class:`canvasapi.content_export.ContentExport` - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` + :rtype: :class:`canvasapi.content_export.ContentExport` """ - warnings.warn( - "`list_groups` is being deprecated and will be removed in a future version." - " Use `get_groups` instead", - DeprecationWarning, + from canvasapi.content_export import ContentExport + + export_id = obj_or_id(content_export, "content_export", (ContentExport,)) + + response = self._requester.request( + "GET", + "courses/{}/content_exports/{}".format(self.id, export_id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_groups(**kwargs) + return ContentExport(self._requester, response.json()) - def get_groups(self, **kwargs): + def get_content_exports(self, **kwargs): """ - Return list of active groups for the specified course. + Return a paginated list of the past and pending content export jobs for a course. - :calls: `GET /api/v1/courses/:course_id/groups \ - `_ + :calls: `GET /api/v1/courses/:course_id/content_exports\ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` + :class:`canvasapi.content_export.ContentExport` """ - from canvasapi.group import Group + from canvasapi.content_export import ContentExport return PaginatedList( - Group, + ContentExport, self._requester, "GET", - "courses/{}/groups".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "courses/{}/content_exports".format(self.id), + kwargs=combine_kwargs(**kwargs), ) - def create_group_category(self, name, **kwargs): + def get_content_migration(self, content_migration, **kwargs): """ - Create a group category. + Retrive a content migration by its ID - :calls: `POST /api/v1/courses/:course_id/group_categories \ - `_ + :calls: `GET /api/v1/courses/:course_id/content_migrations/:id \ + `_ - :param name: Name of the category. - :type name: str - :rtype: :class:`canvasapi.group.GroupCategory` + :param content_migration: The object or ID of the content migration to retrieve. + :type content_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + + :rtype: :class:`canvasapi.content_migration.ContentMigration` """ - from canvasapi.group import GroupCategory + from canvasapi.content_migration import ContentMigration + + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) + ) response = self._requester.request( - "POST", - "courses/{}/group_categories".format(self.id), - name=name, + "GET", + "courses/{}/content_migrations/{}".format(self.id, migration_id), _kwargs=combine_kwargs(**kwargs), ) - return GroupCategory(self._requester, response.json()) - def list_group_categories(self, **kwargs): - """ - List group categories for a context. + response_json = response.json() + response_json.update({"course_id": self.id}) - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_group_categories` instead. + return ContentMigration(self._requester, response_json) - :calls: `GET /api/v1/courses/:course_id/group_categories \ - `_ + def get_content_migrations(self, **kwargs): + """ + List content migrations that the current account can view or manage. + + :calls: `GET /api/v1/courses/:course_id/content_migrations/ \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupCategory` + :class:`canvasapi.content_migration.ContentMigration` """ - warnings.warn( - "`list_group_categories` is being deprecated and will be removed in a future version." - " Use `get_group_categories` instead", - DeprecationWarning, - ) + from canvasapi.content_migration import ContentMigration - return self.get_group_categories(**kwargs) + return PaginatedList( + ContentMigration, + self._requester, + "GET", + "courses/{}/content_migrations".format(self.id), + {"course_id": self.id}, + _kwargs=combine_kwargs(**kwargs), + ) - def get_group_categories(self, **kwargs): + def get_course_level_assignment_data(self, **kwargs): """ - List group categories for a context. + Return a list of assignments for the course sorted by due date - :calls: `GET /api/v1/courses/:course_id/group_categories \ - `_ + :calls: `GET /api/v1/courses/:course_id/analytics/assignments \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupCategory` + :rtype: dict """ - from canvasapi.group import GroupCategory - return PaginatedList( - GroupCategory, - self._requester, + response = self._requester.request( "GET", - "courses/{}/group_categories".format(self.id), + "courses/{}/analytics/assignments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def get_file(self, file, **kwargs): + return response.json() + + def get_course_level_participation_data(self): """ - Return the standard attachment json object for a file. + Return page view hits and participation numbers grouped by day through the course's history - :calls: `GET /api/v1/courses/:course_id/files/:id \ - `_ + :calls: `GET /api/v1/courses/:course_id/analytics/activity \ + `_ - :param file: The object or ID of the file to retrieve. - :type file: :class:`canvasapi.file.File` or int + :rtype: dict + """ - :rtype: :class:`canvasapi.file.File` + response = self._requester.request( + "GET", "courses/{}/analytics/activity".format(self.id) + ) + + return response.json() + + def get_course_level_student_summary_data(self, **kwargs): """ - from canvasapi.file import File + Return a summary of per-user access information for all students in a course - file_id = obj_or_id(file, "file", (File,)) + :calls: `GET /api/v1/courses/:course_id/analytics/student_summaries \ + `_ + + :rtype: dict + """ response = self._requester.request( "GET", - "courses/{}/files/{}".format(self.id, file_id), + "courses/{}/analytics/student_summaries".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return File(self._requester, response.json()) + + return response.json() def get_discussion_topic(self, topic): """ @@ -947,25 +869,6 @@ def get_discussion_topic(self, topic): return DiscussionTopic(self._requester, response_json) - def get_full_discussion_topic(self, topic): - """ - Return a cached structure of the discussion topic. - - :calls: `GET /api/v1/courses/:course_id/discussion_topics/:topic_id/view \ - `_ - - :param topic: The object or ID of the discussion topic. - :type topic: :class:`canvasapi.discussion_topic.DiscussionTopic` or int - - :rtype: dict - """ - topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) - - response = self._requester.request( - "GET", "courses/{}/discussion_topics/{}/view".format(self.id, topic_id) - ) - return response.json() - def get_discussion_topics(self, **kwargs): """ Returns the paginated list of discussion topics for this course or group. @@ -985,393 +888,376 @@ def get_discussion_topics(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def get_assignment_group(self, assignment_group, **kwargs): + def get_enrollments(self, **kwargs): """ - Retrieve specified assignment group for the specified course. - - :calls: `GET /api/v1/courses/:course_id/assignment_groups/:assignment_group_id \ - `_ + List all of the enrollments in this course. - :param assignment_group: object or ID of assignment group. - :type assignment_group: :class:`canvasapi.assignment.AssignmentGroup` or int + :calls: `GET /api/v1/courses/:course_id/enrollments \ + `_ - :rtype: :class:`canvasapi.assignment.AssignmentGroup` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.enrollment.Enrollment` """ - from canvasapi.assignment import AssignmentGroup - - assignment_group_id = obj_or_id( - assignment_group, "assignment_group", (AssignmentGroup,) - ) + from canvasapi.enrollment import Enrollment - response = self._requester.request( + return PaginatedList( + Enrollment, + self._requester, "GET", - "courses/{}/assignment_groups/{}".format(self.id, assignment_group_id), + "courses/{}/enrollments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({"course_id": self.id}) - - return AssignmentGroup(self._requester, response_json) - def list_assignment_groups(self, **kwargs): + def get_epub_export(self, epub, **kwargs): """ - List assignment groups for the specified course. + Get information about a single epub export. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_assignment_groups` instead. + :calls: `GET /api/v1/courses/:course_id/epub_exports/:id\ + `_ - :calls: `GET /api/v1/courses/:course_id/assignment_groups \ - `_ + :param epub: Object or ID of ePub Export + :type epub: int or :class:`canvasapi.course_epub_export.CourseEpubExport` - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.assignment.AssignmentGroup` + :rtype: :class:`canvasapi.course_epub_export.CourseEpubExport` """ - warnings.warn( - "`list_assignment_groups` is being deprecated and will be removed " - "in a future version. Use `get_assignment_groups` instead", - DeprecationWarning, + + epub_id = obj_or_id(epub, "epub", (CourseEpubExport,)) + + response = self._requester.request( + "GET", + "courses/{}/epub_exports/{}".format(self.id, epub_id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_assignment_groups(**kwargs) + return CourseEpubExport(self._requester, response.json()) - def get_assignment_groups(self, **kwargs): + def get_external_feeds(self, **kwargs): """ - List assignment groups for the specified course. + Returns the list of External Feeds this course. - :calls: `GET /api/v1/courses/:course_id/assignment_groups \ - `_ + :calls: `GET /api/v1/courses/:course_id/external_feeds \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.assignment.AssignmentGroup` + :class:`canvasapi.external_feed.ExternalFeed` """ - from canvasapi.assignment import AssignmentGroup + from canvasapi.external_feed import ExternalFeed return PaginatedList( - AssignmentGroup, + ExternalFeed, self._requester, "GET", - "courses/{}/assignment_groups".format(self.id), - {"course_id": self.id}, + "courses/{}/external_feeds".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def create_discussion_topic(self, **kwargs): + def get_external_tool(self, tool): """ - Creates a new discussion topic for the course or group. + :calls: `GET /api/v1/courses/:course_id/external_tools/:external_tool_id \ + `_ - :calls: `POST /api/v1/courses/:course_id/discussion_topics \ - `_ + :param tool: The object or ID of the tool to retrieve. + :type tool: :class:`canvasapi.external_tool.ExternalTool` or int - :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` + :rtype: :class:`canvasapi.external_tool.ExternalTool` """ + from canvasapi.external_tool import ExternalTool + + tool_id = obj_or_id(tool, "tool", (ExternalTool,)) + response = self._requester.request( - "POST", - "courses/{}/discussion_topics".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "GET", "courses/{}/external_tools/{}".format(self.id, tool_id) ) + tool_json = response.json() + tool_json.update({"course_id": self.id}) - response_json = response.json() - response_json.update({"course_id": self.id}) - - return DiscussionTopic(self._requester, response_json) + return ExternalTool(self._requester, tool_json) - def reorder_pinned_topics(self, order): + def get_external_tools(self, **kwargs): """ - Puts the pinned discussion topics in the specified order. - All pinned topics should be included. - - :calls: `POST /api/v1/courses/:course_id/discussion_topics/reorder \ - `_ - - :param order: The ids of the pinned discussion topics in the desired order. - e.g. [104, 102, 103], (104, 102, 103), or "104,102,103" - :type order: string or iterable sequence of values + :calls: `GET /api/v1/courses/:course_id/external_tools \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.discussion_topic.DiscussionTopic` + :class:`canvasapi.external_tool.ExternalTool` """ - # Convert iterable sequence to comma-separated string - if is_multivalued(order): - order = ",".join([text_type(topic_id) for topic_id in order]) - - # Check if is a string with commas - if not isinstance(order, text_type) or "," not in order: - raise ValueError("Param `order` must be a list, tuple, or string.") + from canvasapi.external_tool import ExternalTool - response = self._requester.request( - "POST", "courses/{}/discussion_topics/reorder".format(self.id), order=order + return PaginatedList( + ExternalTool, + self._requester, + "GET", + "courses/{}/external_tools".format(self.id), + {"course_id": self.id}, + _kwargs=combine_kwargs(**kwargs), ) - return response.json().get("reorder") - - def create_assignment_group(self, **kwargs): + def get_file(self, file, **kwargs): """ - Create a new assignment group for this course. + Return the standard attachment json object for a file. - :calls: `POST /api/v1/courses/:course_id/assignment_groups \ - `_ + :calls: `GET /api/v1/courses/:course_id/files/:id \ + `_ - :rtype: :class:`canvasapi.assignment.AssignmentGroup` + :param file: The object or ID of the file to retrieve. + :type file: :class:`canvasapi.file.File` or int + + :rtype: :class:`canvasapi.file.File` """ - from canvasapi.assignment import AssignmentGroup + from canvasapi.file import File + + file_id = obj_or_id(file, "file", (File,)) response = self._requester.request( - "POST", - "courses/{}/assignment_groups".format(self.id), + "GET", + "courses/{}/files/{}".format(self.id, file_id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({"course_id": self.id}) - - return AssignmentGroup(self._requester, response_json) + return File(self._requester, response.json()) - def create_external_tool( - self, name, privacy_level, consumer_key, shared_secret, **kwargs - ): + def get_files(self, **kwargs): """ - Create an external tool in the current course. + Returns the paginated list of files for the course. - :calls: `POST /api/v1/courses/:course_id/external_tools \ - `_ + :calls: `GET /api/v1/courses/:course_id/files \ + `_ - :param name: The name of the tool - :type name: str - :param privacy_level: What information to send to the external - tool. Options are "anonymous", "name_only", "public" - :type privacy_level: str - :param consumer_key: The consumer key for the external tool - :type consumer_key: str - :param shared_secret: The shared secret with the external tool - :type shared_secret: str - :rtype: :class:`canvasapi.external_tool.ExternalTool` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.file.File` """ - from canvasapi.external_tool import ExternalTool + from canvasapi.file import File - response = self._requester.request( - "POST", - "courses/{}/external_tools".format(self.id), - name=name, - privacy_level=privacy_level, - consumer_key=consumer_key, - shared_secret=shared_secret, + return PaginatedList( + File, + self._requester, + "GET", + "courses/{}/files".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({"course_id": self.id}) - - return ExternalTool(self._requester, response_json) - def get_course_level_participation_data(self): + def get_folder(self, folder): """ - Return page view hits and participation numbers grouped by day through the course's history + Returns the details for a course folder - :calls: `GET /api/v1/courses/:course_id/analytics/activity \ - `_ + :calls: `GET /api/v1/courses/:course_id/folders/:id \ + `_ - :rtype: dict + :param folder: The object or ID of the folder to retrieve. + :type folder: :class:`canvasapi.folder.Folder` or int + + :rtype: :class:`canvasapi.folder.Folder` """ + folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - "GET", "courses/{}/analytics/activity".format(self.id) + "GET", "courses/{}/folders/{}".format(self.id, folder_id) ) + return Folder(self._requester, response.json()) - return response.json() - - def get_course_level_assignment_data(self, **kwargs): + def get_folders(self, **kwargs): """ - Return a list of assignments for the course sorted by due date + Returns the paginated list of all folders for the given course. This will be returned as a + flat list containing all subfolders as well. - :calls: `GET /api/v1/courses/:course_id/analytics/assignments \ - `_ + :calls: `GET /api/v1/courses/:course_id/folders \ + `_ - :rtype: dict + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.folder.Folder` """ - - response = self._requester.request( + return PaginatedList( + Folder, + self._requester, "GET", - "courses/{}/analytics/assignments".format(self.id), + "courses/{}/folders".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return response.json() - - def get_course_level_student_summary_data(self, **kwargs): + def get_full_discussion_topic(self, topic): """ - Return a summary of per-user access information for all students in a course + Return a cached structure of the discussion topic. - :calls: `GET /api/v1/courses/:course_id/analytics/student_summaries \ - `_ + :calls: `GET /api/v1/courses/:course_id/discussion_topics/:topic_id/view \ + `_ + + :param topic: The object or ID of the discussion topic. + :type topic: :class:`canvasapi.discussion_topic.DiscussionTopic` or int :rtype: dict """ + topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - "GET", - "courses/{}/analytics/student_summaries".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "GET", "courses/{}/discussion_topics/{}/view".format(self.id, topic_id) ) - return response.json() - def get_user_in_a_course_level_participation_data(self, user): + def get_grading_period(self, grading_period, **kwargs): """ - Return page view hits grouped by hour and participation details through course's history - - :calls: `GET /api/v1/courses/:course_id/analytics/users/:student_id/activity \ - `_ + Return a single grading period for the associated course and id. - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :calls: `GET /api/v1/courses/:course_id/grading_periods/:id\ + `_ + :param grading_period_id: The ID of the rubric. + :type grading_period_id: int - :rtype: dict + :rtype: :class:`canvasapi.grading_period.GradingPeriod` """ - from canvasapi.user import User - - user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - "GET", "courses/{}/analytics/users/{}/activity".format(self.id, user_id) + "GET", + "courses/{}/grading_periods/{}".format(self.id, grading_period), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() + response_grading_period = response.json()["grading_periods"][0] + response_grading_period.update({"course_id": self.id}) - def get_user_in_a_course_level_assignment_data(self, user): - """ - Return a list of assignments for the course sorted by due date + return GradingPeriod(self._requester, response_grading_period) - :calls: `GET /api/v1/courses/:course_id/analytics/users/:student_id/assignments \ - `_ + def get_grading_periods(self, **kwargs): + """ + Return a list of grading periods for the associated course. - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :calls: `GET /api/v1/courses/:course_id/grading_periods\ + `_ - :rtype: dict + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.grading_period.GradingPeriod` """ - from canvasapi.user import User - user_id = obj_or_id(user, "user", (User,)) - - response = self._requester.request( - "GET", "courses/{}/analytics/users/{}/assignments".format(self.id, user_id) + return PaginatedList( + GradingPeriod, + self._requester, + "GET", + "courses/{}/grading_periods".format(self.id), + {"course_id": self.id}, + _root="grading_periods", + kwargs=combine_kwargs(**kwargs), ) - return response.json() - - def get_user_in_a_course_level_messaging_data(self, user): + def get_grading_standards(self, **kwargs): """ - Return messaging hits grouped by day through the entire history of the course + Get a PaginatedList of the grading standards available for the course - :calls: `GET /api/v1/courses/:course_id/analytics/users/:student_id/communication \ - `_ + :calls: `GET /api/v1/courses/:course_id/grading_standards \ + `_ - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.grading_standards.GradingStandard` + """ + return PaginatedList( + GradingStandard, + self._requester, + "GET", + "courses/%s/grading_standards" % (self.id), + _kwargs=combine_kwargs(**kwargs), + ) - :rtype: dict + def get_group_categories(self, **kwargs): """ - from canvasapi.user import User + List group categories for a context. - user_id = obj_or_id(user, "user", (User,)) + :calls: `GET /api/v1/courses/:course_id/group_categories \ + `_ - response = self._requester.request( + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.group.GroupCategory` + """ + from canvasapi.group import GroupCategory + + return PaginatedList( + GroupCategory, + self._requester, "GET", - "courses/{}/analytics/users/{}/communication".format(self.id, user_id), + "courses/{}/group_categories".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() - - def submit_assignment(self, assignment, submission, **kwargs): + def get_groups(self, **kwargs): """ - Makes a submission for an assignment. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.assignment.Assignment.submit` instead. + Return list of active groups for the specified course. - :calls: `POST /api/v1/courses/:course_id/assignments/:assignment_id/submissions \ - `_ + :calls: `GET /api/v1/courses/:course_id/groups \ + `_ - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.Course` + """ + from canvasapi.group import Group - :param submission: The attributes of the submission. - :type submission: dict + return PaginatedList( + Group, + self._requester, + "GET", + "courses/{}/groups".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) - :rtype: :class:`canvasapi.submission.Submission` + def get_migration_systems(self, **kwargs): """ - from canvasapi.assignment import Assignment + Return a list of migration systems. - warnings.warn( - "Course.submit_assignment() is deprecated and will be removed in " - "the future. Use Assignment.submit() instead.", - DeprecationWarning, - ) + :calls: `GET /api/v1/courses/:course_id/content_migrations/migrators \ + `_ - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.content_migration.Migrator` + """ + from canvasapi.content_migration import Migrator - assignment = Assignment( - self._requester, {"course_id": self.id, "id": assignment_id} + return PaginatedList( + Migrator, + self._requester, + "GET", + "courses/{}/content_migrations/migrators".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return assignment.submit(submission, **kwargs) - - def list_submissions(self, assignment, **kwargs): + def get_module(self, module, **kwargs): """ - Get all existing submissions for an assignment. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.assignment.Assignment.get_submissions` instead. + Retrieve a single module by ID. - :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/submissions \ - `_ + :calls: `GET /api/v1/courses/:course_id/modules/:id \ + `_ - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param module: The object or ID of the module to retrieve. + :type module: :class:`canvasapi.module.Module` or int - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.submission.Submission` + :rtype: :class:`canvasapi.module.Module` """ - from canvasapi.assignment import Assignment - - warnings.warn( - "Course.list_submissions() is deprecated and will be removed in " - "the future. Use Assignment.get_submissions() instead.", - DeprecationWarning, - ) + from canvasapi.module import Module - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + module_id = obj_or_id(module, "module", (Module,)) - assignment = Assignment( - self._requester, {"course_id": self.id, "id": assignment_id} + response = self._requester.request( + "GET", "courses/{}/modules/{}".format(self.id, module_id) ) + module_json = response.json() + module_json.update({"course_id": self.id}) - return assignment.get_submissions(**kwargs) + return Module(self._requester, module_json) - def list_multiple_submissions(self, **kwargs): + def get_modules(self, **kwargs): """ - List submissions for multiple assignments. - Get all existing submissions for a given set of students and assignments. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_multiple_submissions` instead. + Return a list of modules in this course. - :calls: `GET /api/v1/courses/:course_id/students/submissions \ - `_ + :calls: `GET /api/v1/courses/:course_id/modules \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.submission.Submission` + :class:`canvasapi.module.Module` """ - warnings.warn( - "`list_multiple_submissions`" - " is being deprecated and will be removed in a future version." - " Use `get_multiple_submissions` instead", - DeprecationWarning, - ) + from canvasapi.module import Module - return self.get_multiple_submissions(**kwargs) + return PaginatedList( + Module, + self._requester, + "GET", + "courses/{}/modules".format(self.id), + {"course_id": self.id}, + _kwargs=combine_kwargs(**kwargs), + ) def get_multiple_submissions(self, **kwargs): """ @@ -1401,412 +1287,380 @@ def get_multiple_submissions(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def get_submission(self, assignment, user, **kwargs): + def get_outcome_group(self, group): """ - Get a single submission, based on user id. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.assignment.Assignment.get_submission` instead. + Returns the details of the Outcome Group with the given id. - :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id \ - `_ + :calls: `GET /api/v1/courses/:course_id/outcome_groups/:id \ + `_ - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :param group: The outcome group object or ID to return. + :type group: :class:`canvasapi.outcome.OutcomeGroup` or int - :rtype: :class:`canvasapi.submission.Submission` + :returns: An outcome group object. + :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ - from canvasapi.assignment import Assignment - - warnings.warn( - "`Course.get_submission()` is deprecated and will be removed in a " - "future version. Use `Assignment.get_submission()` instead", - DeprecationWarning, - ) + from canvasapi.outcome import OutcomeGroup - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,)) - assignment = Assignment( - self._requester, {"course_id": self.id, "id": assignment_id} + response = self._requester.request( + "GET", "courses/{}/outcome_groups/{}".format(self.id, outcome_group_id) ) - return assignment.get_submission(user, **kwargs) + return OutcomeGroup(self._requester, response.json()) - def update_submission(self, assignment, user, **kwargs): + def get_outcome_groups_in_context(self): """ - Comment on and/or update the grading for a student's assignment submission. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.submission.Submission.edit` instead. - - :calls: `PUT /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id \ - `_ + Get all outcome groups for context - BETA - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :calls: `GET /api/v1/courses/:course_id/outcome_groups \ + `_ - :rtype: :class:`canvasapi.submission.Submission` + :returns: Paginated List of OutcomesGroups in the context. + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.outcome.OutcomeGroups` """ - from canvasapi.assignment import Assignment - from canvasapi.user import User - - warnings.warn( - "`Course.update_submission()` is deprecated and will be removed in a " - "future version. Use `Submission.edit()` instead", - DeprecationWarning, - ) - - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - user_id = obj_or_id(user, "user", (User,)) + from canvasapi.outcome import OutcomeGroup - submission = Submission( + return PaginatedList( + OutcomeGroup, self._requester, - {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, + "GET", + "courses/{}/outcome_groups".format(self.id), ) - return submission.edit(**kwargs) - - def list_gradeable_students(self, assignment, **kwargs): + def get_outcome_import_status(self, outcome_import, **kwargs): """ - List students eligible to submit the assignment. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.assignment.Assignment.get_gradeable_students` instead. + Get the status of an already created Outcome import. + Pass 'latest' for the outcome import id for the latest import. - :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/gradeable_students \ - `_ + :calls: `GET /api/v1/courses/:course_id/outcome_imports/:id \ + `_ - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param outcome_import: The outcome import object or ID to get the status of. + :type outcome_import: :class:`canvasapi.outcome_import.OutcomeImport`, + int, or string: "latest" - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.UserDisplay` + :rtype: :class:`canvasapi.outcome_import.OutcomeImport` """ - from canvasapi.assignment import Assignment + if outcome_import == "latest": + outcome_import_id = "latest" + else: + outcome_import_id = obj_or_id( + outcome_import, "outcome_import", (OutcomeImport,) + ) - warnings.warn( - "`Course.list_gradeable_students()` is deprecated and will be " - "removed in a future version. Use " - "`Assignment.get_gradeable_students()` instead.", - DeprecationWarning, + response = self._requester.request( + "GET", + "courses/{}/outcome_imports/{}".format(self.id, outcome_import_id), + _kwargs=combine_kwargs(**kwargs), ) - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - assignment = Assignment( - self._requester, {"id": assignment_id, "course_id": self.id} - ) + response_json = response.json() + response_json.update({"course_id": self.id}) - return assignment.get_gradeable_students(**kwargs) + return OutcomeImport(self._requester, response_json) - def mark_submission_as_read(self, assignment, user, **kwargs): + def get_outcome_result_rollups(self, **kwargs): """ - Mark submission as read. No request fields are necessary. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.submission.Submission.mark_read` instead. - - :calls: `PUT - /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id/read \ - `_ + Get all outcome result rollups for context - BETA - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :calls: `GET /api/v1/courses/:course_id/outcome_rollups \ + `_ - :rtype: `bool` + :returns: List of outcome result rollups in the context. + :rtype: dict """ - from canvasapi.assignment import Assignment - from canvasapi.user import User - - warnings.warn( - "`Course.mark_submission_as_read()` is deprecated and will be " - "removed in a future version. Use `Submission.mark_read()` instead.", - DeprecationWarning, + response = self._requester.request( + "GET", + "courses/{}/outcome_rollups".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - user_id = obj_or_id(user, "user", (User,)) + return response.json() - submission = Submission( - self._requester, - {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, - ) - return submission.mark_read(**kwargs) + def get_outcome_results(self, **kwargs): + """ + Get all outcome results for context - BETA - def mark_submission_as_unread(self, assignment, user, **kwargs): + :calls: `GET /api/v1/courses/:course_id/outcome_results \ + `_ + + :returns: List of potential related outcome result dicts. + :rtype: dict """ - Mark submission as unread. No request fields are necessary. + response = self._requester.request( + "GET", + "courses/{}/outcome_results".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.submission.Submission.mark_unread` instead. + return response.json() - :calls: `DELETE - /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id/read \ - `_ + def get_page(self, url): + """ + Retrieve the contents of a wiki page. - :param assignment: The object or ID of the related assignment - :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param user: The object or ID of the related user - :type user: :class:`canvasapi.user.User` or int + :calls: `GET /api/v1/courses/:course_id/pages/:url \ + `_ - :rtype: `bool` + :param url: The url for the page. + :type url: str + :returns: The specified page. + :rtype: :class:`canvasapi.course.Course` """ - from canvasapi.assignment import Assignment - from canvasapi.user import User - warnings.warn( - "`Course.mark_submission_as_unread()` is deprecated and will be " - "removed in a future version. Use `Submission.mark_unread()` instead.", - DeprecationWarning, + response = self._requester.request( + "GET", "courses/{}/pages/{}".format(self.id, url) ) + page_json = response.json() + page_json.update({"course_id": self.id}) - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - user_id = obj_or_id(user, "user", (User,)) + return Page(self._requester, page_json) - submission = Submission( + def get_pages(self, **kwargs): + """ + List the wiki pages associated with a course. + + :calls: `GET /api/v1/courses/:course_id/pages \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.Course` + """ + return PaginatedList( + Page, self._requester, - {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, + "GET", + "courses/{}/pages".format(self.id), + {"course_id": self.id}, + _kwargs=combine_kwargs(**kwargs), ) - return submission.mark_unread(**kwargs) - def list_external_feeds(self, **kwargs): + def get_quiz(self, quiz): """ - Returns the list of External Feeds this course. + Return the quiz with the given id. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_external_feeds` instead. + :calls: `GET /api/v1/courses/:course_id/quizzes/:id \ + `_ - :calls: `GET /api/v1/courses/:course_id/external_feeds \ - `_ + :param quiz: The object or ID of the quiz to retrieve. + :type quiz: :class:`canvasapi.quiz.Quiz` or int - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.external_feed.ExternalFeed` + :rtype: :class:`canvasapi.quiz.Quiz` """ - warnings.warn( - "`list_external_feeds` is being deprecated and will be removed in " - "a future version. Use `get_external_feeds` instead", - DeprecationWarning, + from canvasapi.quiz import Quiz + + quiz_id = obj_or_id(quiz, "quiz", (Quiz,)) + + response = self._requester.request( + "GET", "courses/{}/quizzes/{}".format(self.id, quiz_id) ) + quiz_json = response.json() + quiz_json.update({"course_id": self.id}) - return self.get_external_feeds(**kwargs) + return Quiz(self._requester, quiz_json) - def get_external_feeds(self, **kwargs): + def get_quizzes(self, **kwargs): """ - Returns the list of External Feeds this course. + Return a list of quizzes belonging to this course. - :calls: `GET /api/v1/courses/:course_id/external_feeds \ - `_ + :calls: `GET /api/v1/courses/:course_id/quizzes \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.external_feed.ExternalFeed` + :class:`canvasapi.quiz.Quiz` """ - from canvasapi.external_feed import ExternalFeed + from canvasapi.quiz import Quiz return PaginatedList( - ExternalFeed, + Quiz, self._requester, "GET", - "courses/{}/external_feeds".format(self.id), + "courses/{}/quizzes".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) - def create_external_feed(self, url, **kwargs): + def get_recent_students(self): """ - Create a new external feed for the course. + Return a list of students in the course ordered by how recently they + have logged in. - :calls: `POST /api/v1/courses/:course_id/external_feeds \ - `_ + :calls: `GET /api/v1/courses/:course_id/recent_students \ + `_ - :param url: The url of the external rss or atom feed - :type url: str - :rtype: :class:`canvasapi.external_feed.ExternalFeed` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.user.User` """ - from canvasapi.external_feed import ExternalFeed + from canvasapi.user import User - response = self._requester.request( - "POST", - "courses/{}/external_feeds".format(self.id), - url=url, - _kwargs=combine_kwargs(**kwargs), + return PaginatedList( + User, self._requester, "GET", "courses/{}/recent_students".format(self.id) ) - return ExternalFeed(self._requester, response.json()) - def delete_external_feed(self, feed): + def get_root_outcome_group(self): """ - Deletes the external feed. - - :calls: `DELETE /api/v1/courses/:course_id/external_feeds/:external_feed_id \ - `_ + Redirect to root outcome group for context - :param feed: The object or ID of the feed to be deleted. - :type feed: :class:`canvasapi.external_feed.ExternalFeed` or int + :calls: `GET /api/v1/courses/:course_id/root_outcome_group \ + `_ - :rtype: :class:`canvasapi.external_feed.ExternalFeed` + :returns: The OutcomeGroup of the context. + :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ - from canvasapi.external_feed import ExternalFeed - - feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) + from canvasapi.outcome import OutcomeGroup response = self._requester.request( - "DELETE", "courses/{}/external_feeds/{}".format(self.id, feed_id) + "GET", "courses/{}/root_outcome_group".format(self.id) ) - return ExternalFeed(self._requester, response.json()) + return OutcomeGroup(self._requester, response.json()) - def list_files(self, **kwargs): + def get_rubric(self, rubric_id, **kwargs): """ - Returns the paginated list of files for the course. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_files` instead. + Get a single rubric, based on rubric id. - :calls: `GET /api/v1/courses/:course_id/files \ - `_ + :calls: `GET /api/v1/courses/:course_id/rubrics/:id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` + :param rubric_id: The ID of the rubric. + :type rubric_id: int + :rtype: :class:`canvasapi.rubric.Rubric` """ - warnings.warn( - "`list_files` is being deprecated and will be removed in a future " - "version. Use `get_files` instead", - DeprecationWarning, + response = self._requester.request( + "GET", + "courses/%s/rubrics/%s" % (self.id, rubric_id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_files(**kwargs) + return Rubric(self._requester, response.json()) - def get_files(self, **kwargs): + def get_rubrics(self, **kwargs): """ - Returns the paginated list of files for the course. + Get the paginated list of active rubrics for the current course. - :calls: `GET /api/v1/courses/:course_id/files \ - `_ + :calls: `GET /api/v1/courses/:course_id/rubrics \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` + :class:`canvasapi.rubric.Rubric` """ - from canvasapi.file import File - return PaginatedList( - File, + Rubric, self._requester, "GET", - "courses/{}/files".format(self.id), + "courses/%s/rubrics" % (self.id), _kwargs=combine_kwargs(**kwargs), ) - def get_folder(self, folder): + def get_section(self, section, **kwargs): """ - Returns the details for a course folder + Retrieve a section. - :calls: `GET /api/v1/courses/:course_id/folders/:id \ - `_ + :calls: `GET /api/v1/courses/:course_id/sections/:id \ + `_ - :param folder: The object or ID of the folder to retrieve. - :type folder: :class:`canvasapi.folder.Folder` or int + :param section: The object or ID of the section to retrieve. + :type section: :class:`canvasapi.section.Section` or int - :rtype: :class:`canvasapi.folder.Folder` + :rtype: :class:`canvasapi.section.Section` """ - folder_id = obj_or_id(folder, "folder", (Folder,)) + from canvasapi.section import Section + + section_id = obj_or_id(section, "section", (Section,)) response = self._requester.request( - "GET", "courses/{}/folders/{}".format(self.id, folder_id) + "GET", + "courses/{}/sections/{}".format(self.id, section_id), + _kwargs=combine_kwargs(**kwargs), ) - return Folder(self._requester, response.json()) + return Section(self._requester, response.json()) - def list_folders(self, **kwargs): + def get_sections(self, **kwargs): """ - Returns the paginated list of all folders for the given course. This will be returned as a - flat list containing all subfolders as well. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_folders` instead. + List all sections in a course. - :calls: `GET /api/v1/courses/:course_id/folders \ - `_ + :calls: `GET /api/v1/courses/:course_id/sections \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.folder.Folder` - """ - warnings.warn( - "`list_folders` is being deprecated and will be removed in a " - "future version. Use `get_folders` instead", - DeprecationWarning, - ) - - return self.get_folders(**kwargs) - - def get_folders(self, **kwargs): + :class:`canvasapi.section.Section` """ - Returns the paginated list of all folders for the given course. This will be returned as a - flat list containing all subfolders as well. - - :calls: `GET /api/v1/courses/:course_id/folders \ - `_ + from canvasapi.section import Section - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.folder.Folder` - """ return PaginatedList( - Folder, + Section, self._requester, "GET", - "courses/{}/folders".format(self.id), + "courses/{}/sections".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def create_folder(self, name, **kwargs): + def get_settings(self): """ - Creates a folder in this course. + Returns this course's settings. - :calls: `POST /api/v1/courses/:course_id/folders \ - `_ + :calls: `GET /api/v1/courses/:course_id/settings \ + `_ - :param name: The name of the folder. - :type name: str - :rtype: :class:`canvasapi.folder.Folder` + :rtype: dict + """ + response = self._requester.request("GET", "courses/{}/settings".format(self.id)) + return response.json() + + def get_single_grading_standard(self, grading_standard_id, **kwargs): + """ + Get a single grading standard from the course. + + :calls: `GET /api/v1/courses/:course_id/grading_standards/:grading_standard_id \ + `_ + + :param grading_standard_id: The grading standard id + :type grading_standard_id: int + :rtype: :class:`canvasapi.grading_standards.GradingStandard` """ + response = self._requester.request( - "POST", - "courses/{}/folders".format(self.id), - name=name, + "GET", + "courses/%s/grading_standards/%d" % (self.id, grading_standard_id), _kwargs=combine_kwargs(**kwargs), ) - return Folder(self._requester, response.json()) + return GradingStandard(self._requester, response.json()) - def list_tabs(self, **kwargs): + def get_submission(self, assignment, user, **kwargs): """ - List available tabs for a course. - Returns a list of navigation tabs available in the current context. + Get a single submission, based on user id. .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_tabs` instead. + .. deprecated:: 0.9.0 + Use :func:`canvasapi.assignment.Assignment.get_submission` instead. - :calls: `GET /api/v1/courses/:course_id/tabs \ - `_ + :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.tab.Tab` + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int + + :rtype: :class:`canvasapi.submission.Submission` """ + from canvasapi.assignment import Assignment + warnings.warn( - "`list_tabs` is being deprecated and will be removed in a future " - "version. Use `get_tabs` instead", + "`Course.get_submission()` is deprecated and will be removed in a " + "future version. Use `Assignment.get_submission()` instead", DeprecationWarning, ) - return self.get_tabs(**kwargs) + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + + assignment = Assignment( + self._requester, {"course_id": self.id, "id": assignment_id} + ) + + return assignment.get_submission(user, **kwargs) def get_tabs(self, **kwargs): """ @@ -1828,377 +1682,593 @@ def get_tabs(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def update_tab(self, tab_id, **kwargs): + def get_user(self, user, user_id_type=None): """ - Update a tab for a course. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.tab.Tab.update` instead. + Retrieve a user by their ID. `user_id_type` denotes which endpoint to try as there are + several different ids that can pull the same user record from Canvas. - :calls: `PUT /api/v1/courses/:course_id/tabs/:tab_id \ - `_ + :calls: `GET /api/v1/courses/:course_id/users/:id \ + `_ - :param tab_id: The ID of the tab - :type tab_id: str + :param user: The object or ID of the user to retrieve. + :type user: :class:`canvasapi.user.User` or int + :param user_id_type: The type of the ID to search for. + :type user_id_type: str - :rtype: :class:`canvasapi.tab.Tab` + :rtype: :class:`canvasapi.user.User` """ - warnings.warn( - "`Course.update_tab()` is being deprecated and will be removed in " - "a future version. Use `Tab.update()` instead", - DeprecationWarning, - ) + from canvasapi.user import User - tab = Tab(self._requester, {"course_id": self.id, "id": tab_id}) - return tab.update(**kwargs) + if user_id_type: + uri = "courses/{}/users/{}:{}".format(self.id, user_id_type, user) + else: + user_id = obj_or_id(user, "user", (User,)) + uri = "courses/{}/users/{}".format(self.id, user_id) - def get_rubric(self, rubric_id, **kwargs): + response = self._requester.request("GET", uri) + return User(self._requester, response.json()) + + def get_user_in_a_course_level_assignment_data(self, user): """ - Get a single rubric, based on rubric id. + Return a list of assignments for the course sorted by due date - :calls: `GET /api/v1/courses/:course_id/rubrics/:id \ - `_ + :calls: `GET /api/v1/courses/:course_id/analytics/users/:student_id/assignments \ + `_ - :param rubric_id: The ID of the rubric. - :type rubric_id: int - :rtype: :class:`canvasapi.rubric.Rubric` - """ - response = self._requester.request( + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int + + :rtype: dict + """ + from canvasapi.user import User + + user_id = obj_or_id(user, "user", (User,)) + + response = self._requester.request( + "GET", "courses/{}/analytics/users/{}/assignments".format(self.id, user_id) + ) + + return response.json() + + def get_user_in_a_course_level_messaging_data(self, user): + """ + Return messaging hits grouped by day through the entire history of the course + + :calls: `GET /api/v1/courses/:course_id/analytics/users/:student_id/communication \ + `_ + + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int + + :rtype: dict + """ + from canvasapi.user import User + + user_id = obj_or_id(user, "user", (User,)) + + response = self._requester.request( "GET", - "courses/%s/rubrics/%s" % (self.id, rubric_id), + "courses/{}/analytics/users/{}/communication".format(self.id, user_id), + ) + + return response.json() + + def get_user_in_a_course_level_participation_data(self, user): + """ + Return page view hits grouped by hour and participation details through course's history + + :calls: `GET /api/v1/courses/:course_id/analytics/users/:student_id/activity \ + `_ + + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int + + :rtype: dict + """ + from canvasapi.user import User + + user_id = obj_or_id(user, "user", (User,)) + + response = self._requester.request( + "GET", "courses/{}/analytics/users/{}/activity".format(self.id, user_id) + ) + + return response.json() + + def get_users(self, **kwargs): + """ + List all users in a course. + + :calls: `GET /api/v1/courses/:course_id/search_users \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.user.User` + """ + from canvasapi.user import User + + return PaginatedList( + User, + self._requester, + "GET", + "courses/{}/search_users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return Rubric(self._requester, response.json()) + def import_outcome(self, attachment, **kwargs): + """ + Import outcome into canvas. - def list_rubrics(self, **kwargs): + :calls: `POST /api/v1/courses/:course_id/outcome_imports \ + `_ + + :param attachment: A file handler or path of the file to import. + :type attachment: file or str + + :rtype: :class:`canvasapi.outcome_import.OutcomeImport` """ - Get the paginated list of active rubrics for the current course. + + attachment, is_path = file_or_path(attachment) + + try: + response = self._requester.request( + "POST", + "courses/{}/outcome_imports".format(self.id), + file={"attachment": attachment}, + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({"course_id": self.id}) + + return OutcomeImport(self._requester, response_json) + finally: + if is_path: + attachment.close() + + def list_assignment_groups(self, **kwargs): + """ + List assignment groups for the specified course. .. warning:: .. deprecated:: 0.10.0 - Use :func:`canvasapi.course.Course.get_rubrics` instead. + Use :func:`canvasapi.course.Course.get_assignment_groups` instead. - :calls: `GET /api/v1/courses/:course_id/rubrics \ - `_ + :calls: `GET /api/v1/courses/:course_id/assignment_groups \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.rubric.Rubric` + :class:`canvasapi.assignment.AssignmentGroup` """ warnings.warn( - "`list_rubrics` is being deprecated and will be removed in a " - "future version. Use `get_rubrics` instead", + "`list_assignment_groups` is being deprecated and will be removed " + "in a future version. Use `get_assignment_groups` instead", DeprecationWarning, ) - return self.get_rubrics(**kwargs) + return self.get_assignment_groups(**kwargs) - def get_rubrics(self, **kwargs): + def list_blueprint_subscriptions(self, **kwargs): """ - Get the paginated list of active rubrics for the current course. + Return a list of blueprint subscriptions for the given course. - :calls: `GET /api/v1/courses/:course_id/rubrics \ - `_ + :calls: `GET /api/v1/courses/:course_id/blueprint_subscriptions\ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.rubric.Rubric` + :class:`canvasapi.blueprint.BlueprintSubscription` """ + return PaginatedList( - Rubric, + BlueprintSubscription, self._requester, "GET", - "courses/%s/rubrics" % (self.id), - _kwargs=combine_kwargs(**kwargs), + "courses/{}/blueprint_subscriptions".format(self.id), + {"course_id": self.id}, + kwargs=combine_kwargs(**kwargs), ) - def get_root_outcome_group(self): + def list_external_feeds(self, **kwargs): """ - Redirect to root outcome group for context + Returns the list of External Feeds this course. - :calls: `GET /api/v1/courses/:course_id/root_outcome_group \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_external_feeds` instead. - :returns: The OutcomeGroup of the context. - :rtype: :class:`canvasapi.outcome.OutcomeGroup` - """ - from canvasapi.outcome import OutcomeGroup + :calls: `GET /api/v1/courses/:course_id/external_feeds \ + `_ - response = self._requester.request( - "GET", "courses/{}/root_outcome_group".format(self.id) + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.external_feed.ExternalFeed` + """ + warnings.warn( + "`list_external_feeds` is being deprecated and will be removed in " + "a future version. Use `get_external_feeds` instead", + DeprecationWarning, ) - return OutcomeGroup(self._requester, response.json()) - def get_outcome_group(self, group): + return self.get_external_feeds(**kwargs) + + def list_files(self, **kwargs): """ - Returns the details of the Outcome Group with the given id. + Returns the paginated list of files for the course. - :calls: `GET /api/v1/courses/:course_id/outcome_groups/:id \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_files` instead. - :param group: The outcome group object or ID to return. - :type group: :class:`canvasapi.outcome.OutcomeGroup` or int + :calls: `GET /api/v1/courses/:course_id/files \ + `_ - :returns: An outcome group object. - :rtype: :class:`canvasapi.outcome.OutcomeGroup` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.file.File` """ - from canvasapi.outcome import OutcomeGroup + warnings.warn( + "`list_files` is being deprecated and will be removed in a future " + "version. Use `get_files` instead", + DeprecationWarning, + ) - outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,)) + return self.get_files(**kwargs) - response = self._requester.request( - "GET", "courses/{}/outcome_groups/{}".format(self.id, outcome_group_id) + def list_folders(self, **kwargs): + """ + Returns the paginated list of all folders for the given course. This will be returned as a + flat list containing all subfolders as well. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_folders` instead. + + :calls: `GET /api/v1/courses/:course_id/folders \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.folder.Folder` + """ + warnings.warn( + "`list_folders` is being deprecated and will be removed in a " + "future version. Use `get_folders` instead", + DeprecationWarning, ) - return OutcomeGroup(self._requester, response.json()) + return self.get_folders(**kwargs) - def get_outcome_groups_in_context(self): + def list_gradeable_students(self, assignment, **kwargs): """ - Get all outcome groups for context - BETA + List students eligible to submit the assignment. - :calls: `GET /api/v1/courses/:course_id/outcome_groups \ - `_ + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.assignment.Assignment.get_gradeable_students` instead. + + :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/gradeable_students \ + `_ + + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int - :returns: Paginated List of OutcomesGroups in the context. :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.outcome.OutcomeGroups` + :class:`canvasapi.user.UserDisplay` """ - from canvasapi.outcome import OutcomeGroup + from canvasapi.assignment import Assignment - return PaginatedList( - OutcomeGroup, - self._requester, - "GET", - "courses/{}/outcome_groups".format(self.id), + warnings.warn( + "`Course.list_gradeable_students()` is deprecated and will be " + "removed in a future version. Use " + "`Assignment.get_gradeable_students()` instead.", + DeprecationWarning, ) - def get_all_outcome_links_in_context(self): + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + assignment = Assignment( + self._requester, {"id": assignment_id, "course_id": self.id} + ) + + return assignment.get_gradeable_students(**kwargs) + + def list_group_categories(self, **kwargs): """ - Get all outcome links for context - BETA + List group categories for a context. - :calls: `GET /api/v1/courses/:course_id/outcome_group_links \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_group_categories` instead. + + :calls: `GET /api/v1/courses/:course_id/group_categories \ + `_ - :returns: Paginated List of OutcomesLinks in the context. :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.outcome.OutcomeLink` + :class:`canvasapi.group.GroupCategory` """ - from canvasapi.outcome import OutcomeLink - - return PaginatedList( - OutcomeLink, - self._requester, - "GET", - "courses/{}/outcome_group_links".format(self.id), + warnings.warn( + "`list_group_categories` is being deprecated and will be removed in a future version." + " Use `get_group_categories` instead", + DeprecationWarning, ) - def get_outcome_results(self, **kwargs): + return self.get_group_categories(**kwargs) + + def list_groups(self, **kwargs): """ - Get all outcome results for context - BETA + Return list of active groups for the specified course. - :calls: `GET /api/v1/courses/:course_id/outcome_results \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_groups` instead. - :returns: List of potential related outcome result dicts. - :rtype: dict + :calls: `GET /api/v1/courses/:course_id/groups \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.Course` """ - response = self._requester.request( - "GET", - "courses/{}/outcome_results".format(self.id), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_groups` is being deprecated and will be removed in a future version." + " Use `get_groups` instead", + DeprecationWarning, ) - return response.json() + return self.get_groups(**kwargs) - def get_outcome_result_rollups(self, **kwargs): + def list_multiple_submissions(self, **kwargs): """ - Get all outcome result rollups for context - BETA + List submissions for multiple assignments. + Get all existing submissions for a given set of students and assignments. - :calls: `GET /api/v1/courses/:course_id/outcome_rollups \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_multiple_submissions` instead. - :returns: List of outcome result rollups in the context. - :rtype: dict + :calls: `GET /api/v1/courses/:course_id/students/submissions \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.submission.Submission` """ - response = self._requester.request( - "GET", - "courses/{}/outcome_rollups".format(self.id), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_multiple_submissions`" + " is being deprecated and will be removed in a future version." + " Use `get_multiple_submissions` instead", + DeprecationWarning, ) - return response.json() + return self.get_multiple_submissions(**kwargs) - def add_grading_standards(self, title, grading_scheme_entry, **kwargs): + def list_rubrics(self, **kwargs): """ - Create a new grading standard for the course. + Get the paginated list of active rubrics for the current course. - :calls: `POST /api/v1/courses/:course_id/grading_standards \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_rubrics` instead. - :param title: The title for the Grading Standard - :type title: str - :param grading_scheme: A list of dictionaries containing keys for "name" and "value" - :type grading_scheme: list[dict] - :rtype: :class:`canvasapi.grading_standards.GradingStandard` + :calls: `GET /api/v1/courses/:course_id/rubrics \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.rubric.Rubric` """ - if not isinstance(grading_scheme_entry, list) or len(grading_scheme_entry) <= 0: - raise ValueError("Param `grading_scheme_entry` must be a non-empty list.") + warnings.warn( + "`list_rubrics` is being deprecated and will be removed in a " + "future version. Use `get_rubrics` instead", + DeprecationWarning, + ) - for entry in grading_scheme_entry: - if not isinstance(entry, dict): - raise ValueError("grading_scheme_entry must consist of dictionaries.") - if "name" not in entry or "value" not in entry: - raise ValueError( - "Dictionaries with keys 'name' and 'value' are required." - ) - kwargs["grading_scheme_entry"] = grading_scheme_entry + return self.get_rubrics(**kwargs) - response = self._requester.request( - "POST", - "courses/%s/grading_standards" % (self.id), - title=title, - _kwargs=combine_kwargs(**kwargs), + def list_sections(self, **kwargs): + """ + Returns the list of sections for this course. + + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.course.Course.get_sections` instead. + + :calls: `GET /api/v1/courses/:course_id/sections \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.section.Section` + """ + warnings.warn( + "`list_sections` is being deprecated and will be removed in a future version." + " Use `get_sections` instead", + DeprecationWarning, ) - return GradingStandard(self._requester, response.json()) + return self.get_sections(**kwargs) - def get_grading_standards(self, **kwargs): + def list_submissions(self, assignment, **kwargs): """ - Get a PaginatedList of the grading standards available for the course + Get all existing submissions for an assignment. - :calls: `GET /api/v1/courses/:course_id/grading_standards \ - `_ + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.assignment.Assignment.get_submissions` instead. + + :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/submissions \ + `_ + + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.grading_standards.GradingStandard` + :class:`canvasapi.submission.Submission` """ - return PaginatedList( - GradingStandard, - self._requester, - "GET", - "courses/%s/grading_standards" % (self.id), - _kwargs=combine_kwargs(**kwargs), + from canvasapi.assignment import Assignment + + warnings.warn( + "Course.list_submissions() is deprecated and will be removed in " + "the future. Use Assignment.get_submissions() instead.", + DeprecationWarning, ) - def get_single_grading_standard(self, grading_standard_id, **kwargs): - """ - Get a single grading standard from the course. + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - :calls: `GET /api/v1/courses/:course_id/grading_standards/:grading_standard_id \ - `_ + assignment = Assignment( + self._requester, {"course_id": self.id, "id": assignment_id} + ) - :param grading_standard_id: The grading standard id - :type grading_standard_id: int - :rtype: :class:`canvasapi.grading_standards.GradingStandard` + return assignment.get_submissions(**kwargs) + + def list_tabs(self, **kwargs): """ + List available tabs for a course. + Returns a list of navigation tabs available in the current context. - response = self._requester.request( - "GET", - "courses/%s/grading_standards/%d" % (self.id, grading_standard_id), - _kwargs=combine_kwargs(**kwargs), + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.course.Course.get_tabs` instead. + + :calls: `GET /api/v1/courses/:course_id/tabs \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.tab.Tab` + """ + warnings.warn( + "`list_tabs` is being deprecated and will be removed in a future " + "version. Use `get_tabs` instead", + DeprecationWarning, ) - return GradingStandard(self._requester, response.json()) - def create_content_migration(self, migration_type, **kwargs): + return self.get_tabs(**kwargs) + + def mark_submission_as_read(self, assignment, user, **kwargs): """ - Create a content migration. + Mark submission as read. No request fields are necessary. + + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.submission.Submission.mark_read` instead. - :calls: `POST /api/v1/courses/:course_id/content_migrations \ - `_ + :calls: `PUT + /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id/read \ + `_ - :param migration_type: The migrator type to use in this migration - :type migration_type: str or :class:`canvasapi.content_migration.Migrator` + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :rtype: `bool` """ - from canvasapi.content_migration import ContentMigration, Migrator - - if isinstance(migration_type, Migrator): - kwargs["migration_type"] = migration_type.type - elif isinstance(migration_type, string_types): - kwargs["migration_type"] = migration_type - else: - raise TypeError("Parameter migration_type must be of type Migrator or str") + from canvasapi.assignment import Assignment + from canvasapi.user import User - response = self._requester.request( - "POST", - "courses/{}/content_migrations".format(self.id), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`Course.mark_submission_as_read()` is deprecated and will be " + "removed in a future version. Use `Submission.mark_read()` instead.", + DeprecationWarning, ) - response_json = response.json() - response_json.update({"course_id": self.id}) + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + user_id = obj_or_id(user, "user", (User,)) - return ContentMigration(self._requester, response_json) + submission = Submission( + self._requester, + {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, + ) + return submission.mark_read(**kwargs) - def get_content_migration(self, content_migration, **kwargs): + def mark_submission_as_unread(self, assignment, user, **kwargs): """ - Retrive a content migration by its ID + Mark submission as unread. No request fields are necessary. - :calls: `GET /api/v1/courses/:course_id/content_migrations/:id \ - `_ + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.submission.Submission.mark_unread` instead. - :param content_migration: The object or ID of the content migration to retrieve. - :type content_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + :calls: `DELETE + /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id/read \ + `_ - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int + + :rtype: `bool` """ - from canvasapi.content_migration import ContentMigration + from canvasapi.assignment import Assignment + from canvasapi.user import User - migration_id = obj_or_id( - content_migration, "content_migration", (ContentMigration,) + warnings.warn( + "`Course.mark_submission_as_unread()` is deprecated and will be " + "removed in a future version. Use `Submission.mark_unread()` instead.", + DeprecationWarning, ) - response = self._requester.request( - "GET", - "courses/{}/content_migrations/{}".format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs), + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + user_id = obj_or_id(user, "user", (User,)) + + submission = Submission( + self._requester, + {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, ) + return submission.mark_unread(**kwargs) - response_json = response.json() - response_json.update({"course_id": self.id}) + def preview_html(self, html): + """ + Preview HTML content processed for this course. - return ContentMigration(self._requester, response_json) + :calls: `POST /api/v1/courses/:course_id/preview_html \ + `_ - def get_content_migrations(self, **kwargs): + :param html: The HTML code to preview. + :type html: str + :rtype: str """ - List content migrations that the current account can view or manage. + response = self._requester.request( + "POST", "courses/{}/preview_html".format(self.id), html=html + ) + return response.json().get("html", "") - :calls: `GET /api/v1/courses/:course_id/content_migrations/ \ - `_ + def reorder_pinned_topics(self, order): + """ + Puts the pinned discussion topics in the specified order. + All pinned topics should be included. + + :calls: `POST /api/v1/courses/:course_id/discussion_topics/reorder \ + `_ + + :param order: The ids of the pinned discussion topics in the desired order. + e.g. [104, 102, 103], (104, 102, 103), or "104,102,103" + :type order: string or iterable sequence of values :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.ContentMigration` + :class:`canvasapi.discussion_topic.DiscussionTopic` """ - from canvasapi.content_migration import ContentMigration + # Convert iterable sequence to comma-separated string + if is_multivalued(order): + order = ",".join([text_type(topic_id) for topic_id in order]) - return PaginatedList( - ContentMigration, - self._requester, - "GET", - "courses/{}/content_migrations".format(self.id), - {"course_id": self.id}, - _kwargs=combine_kwargs(**kwargs), + # Check if is a string with commas + if not isinstance(order, text_type) or "," not in order: + raise ValueError("Param `order` must be a list, tuple, or string.") + + response = self._requester.request( + "POST", "courses/{}/discussion_topics/reorder".format(self.id), order=order ) - def get_migration_systems(self, **kwargs): + return response.json().get("reorder") + + def reset(self): """ - Return a list of migration systems. + Delete the current course and create a new equivalent course + with no content, but all sections and users moved over. - :calls: `GET /api/v1/courses/:course_id/content_migrations/migrators \ - `_ + :calls: `POST /api/v1/courses/:course_id/reset_content \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.Migrator` + :rtype: :class:`canvasapi.course.Course` """ - from canvasapi.content_migration import Migrator - - return PaginatedList( - Migrator, - self._requester, - "GET", - "courses/{}/content_migrations/migrators".format(self.id), - _kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "POST", "courses/{}/reset_content".format(self.id) ) + return Course(self._requester, response.json()) def set_quiz_extensions(self, quiz_extensions, **kwargs): """ @@ -2250,288 +2320,218 @@ def set_quiz_extensions(self, quiz_extensions, **kwargs): _kwargs=combine_kwargs(**kwargs), ) extension_list = response.json()["quiz_extensions"] - return [ - QuizExtension(self._requester, extension) for extension in extension_list - ] - - def submissions_bulk_update(self, **kwargs): - """ - Update the grading and comments on multiple student's assignment - submissions in an asynchronous job. - - :calls: `POST /api/v1/courses/:course_id/submissions/update_grades \ - `_ - - :rtype: :class:`canvasapi.progress.Progress` - """ - response = self._requester.request( - "POST", - "courses/{}/submissions/update_grades".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - return Progress(self._requester, response.json()) - - def get_blueprint(self, template="default", **kwargs): - """ - Return the blueprint of a given ID. - - :calls: `GET /api/v1/courses/:course_id/blueprint_templates/:template_id \ - `_ - - :param template: The object or ID of the blueprint template to get. - :type template: int or :class:`canvasapi.blueprint.BlueprintTemplate` - - :rtype: :class:`canvasapi.blueprint.BlueprintTemplate` - """ - from canvasapi.blueprint import BlueprintTemplate - - if template == "default": - template_id = template - else: - template_id = obj_or_id(template, "template", (BlueprintTemplate,)) - - response = self._requester.request( - "GET", - "courses/{}/blueprint_templates/{}".format(self.id, template_id), - _kwargs=combine_kwargs(**kwargs), - ) - return BlueprintTemplate(self._requester, response.json()) - - def list_blueprint_subscriptions(self, **kwargs): - """ - Return a list of blueprint subscriptions for the given course. - - :calls: `GET /api/v1/courses/:course_id/blueprint_subscriptions\ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.blueprint.BlueprintSubscription` - """ - - return PaginatedList( - BlueprintSubscription, - self._requester, - "GET", - "courses/{}/blueprint_subscriptions".format(self.id), - {"course_id": self.id}, - kwargs=combine_kwargs(**kwargs), - ) - - def import_outcome(self, attachment, **kwargs): - """ - Import outcome into canvas. - - :calls: `POST /api/v1/courses/:course_id/outcome_imports \ - `_ - - :param attachment: A file handler or path of the file to import. - :type attachment: file or str - - :rtype: :class:`canvasapi.outcome_import.OutcomeImport` - """ - - attachment, is_path = file_or_path(attachment) - - try: - response = self._requester.request( - "POST", - "courses/{}/outcome_imports".format(self.id), - file={"attachment": attachment}, - _kwargs=combine_kwargs(**kwargs), - ) - - response_json = response.json() - response_json.update({"course_id": self.id}) - - return OutcomeImport(self._requester, response_json) - finally: - if is_path: - attachment.close() + return [ + QuizExtension(self._requester, extension) for extension in extension_list + ] - def get_outcome_import_status(self, outcome_import, **kwargs): + def show_front_page(self): """ - Get the status of an already created Outcome import. - Pass 'latest' for the outcome import id for the latest import. + Retrieve the content of the front page. - :calls: `GET /api/v1/courses/:course_id/outcome_imports/:id \ - `_ + :calls: `GET /api/v1/courses/:course_id/front_page \ + `_ - :param outcome_import: The outcome import object or ID to get the status of. - :type outcome_import: :class:`canvasapi.outcome_import.OutcomeImport`, - int, or string: "latest" + :rtype: :class:`canvasapi.course.Course` + """ + response = self._requester.request( + "GET", "courses/{}/front_page".format(self.id) + ) + page_json = response.json() + page_json.update({"course_id": self.id}) - :rtype: :class:`canvasapi.outcome_import.OutcomeImport` + return Page(self._requester, page_json) + + def submissions_bulk_update(self, **kwargs): """ - if outcome_import == "latest": - outcome_import_id = "latest" - else: - outcome_import_id = obj_or_id( - outcome_import, "outcome_import", (OutcomeImport,) - ) + Update the grading and comments on multiple student's assignment + submissions in an asynchronous job. + + :calls: `POST /api/v1/courses/:course_id/submissions/update_grades \ + `_ + :rtype: :class:`canvasapi.progress.Progress` + """ response = self._requester.request( - "GET", - "courses/{}/outcome_imports/{}".format(self.id, outcome_import_id), + "POST", + "courses/{}/submissions/update_grades".format(self.id), _kwargs=combine_kwargs(**kwargs), ) + return Progress(self._requester, response.json()) - response_json = response.json() - response_json.update({"course_id": self.id}) + def submit_assignment(self, assignment, submission, **kwargs): + """ + Makes a submission for an assignment. - return OutcomeImport(self._requester, response_json) + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.assignment.Assignment.submit` instead. - def get_epub_export(self, epub, **kwargs): - """ - Get information about a single epub export. + :calls: `POST /api/v1/courses/:course_id/assignments/:assignment_id/submissions \ + `_ - :calls: `GET /api/v1/courses/:course_id/epub_exports/:id\ - `_ + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param epub: Object or ID of ePub Export - :type epub: int or :class:`canvasapi.course_epub_export.CourseEpubExport` + :param submission: The attributes of the submission. + :type submission: dict - :rtype: :class:`canvasapi.course_epub_export.CourseEpubExport` + :rtype: :class:`canvasapi.submission.Submission` """ + from canvasapi.assignment import Assignment - epub_id = obj_or_id(epub, "epub", (CourseEpubExport,)) + warnings.warn( + "Course.submit_assignment() is deprecated and will be removed in " + "the future. Use Assignment.submit() instead.", + DeprecationWarning, + ) - response = self._requester.request( - "GET", - "courses/{}/epub_exports/{}".format(self.id, epub_id), - _kwargs=combine_kwargs(**kwargs), + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + + assignment = Assignment( + self._requester, {"course_id": self.id, "id": assignment_id} ) - return CourseEpubExport(self._requester, response.json()) + return assignment.submit(submission, **kwargs) - def create_epub_export(self, **kwargs): + def update(self, **kwargs): """ - Create an ePub export for a course. + Update this course. - :calls: `POST /api/v1/courses/:course_id/epub_exports/:id\ - `_ + :calls: `PUT /api/v1/courses/:id \ + `_ - :rtype: :class:`canvasapi.course_epub_export.CourseEpubExport` + :returns: True if the course was updated, False otherwise. + :rtype: bool """ - response = self._requester.request( - "POST", - "courses/{}/epub_exports/".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "PUT", "courses/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - return CourseEpubExport(self._requester, response.json()) + if response.json().get("name"): + super(Course, self).set_attributes(response.json()) - def get_grading_periods(self, **kwargs): + return response.json().get("name") + + def update_assignment_overrides(self, assignment_overrides, **kwargs): """ - Return a list of grading periods for the associated course. + Update a list of specified overrides for each assignment. - :calls: `GET /api/v1/courses/:course_id/grading_periods\ - `_ + Note: All current overridden values must be supplied if they are to be retained. + + :calls: `PUT /api/v1/courses/:course_id/assignments/overrides \ + `_ + + :param assignment_overrides: Attributes for the updated assignment overrides. + :type assignment_overrides: list :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.grading_period.GradingPeriod` + :class:`canvasapi.assignment.AssignmentOverride` """ + from canvasapi.assignment import AssignmentOverride + + kwargs["assignment_overrides"] = assignment_overrides return PaginatedList( - GradingPeriod, + AssignmentOverride, self._requester, - "GET", - "courses/{}/grading_periods".format(self.id), + "PUT", + "courses/{}/assignments/overrides".format(self.id), {"course_id": self.id}, - _root="grading_periods", - kwargs=combine_kwargs(**kwargs), + _kwargs=combine_kwargs(**kwargs), ) - def get_grading_period(self, grading_period, **kwargs): + def update_settings(self, **kwargs): """ - Return a single grading period for the associated course and id. + Update a course's settings. - :calls: `GET /api/v1/courses/:course_id/grading_periods/:id\ - `_ - :param grading_period_id: The ID of the rubric. - :type grading_period_id: int + :calls: `PUT /api/v1/courses/:course_id/settings \ + `_ - :rtype: :class:`canvasapi.grading_period.GradingPeriod` + :rtype: dict """ - response = self._requester.request( - "GET", - "courses/{}/grading_periods/{}".format(self.id, grading_period), - _kwargs=combine_kwargs(**kwargs), + "PUT", "courses/{}/settings".format(self.id), **kwargs ) + return response.json() - response_grading_period = response.json()["grading_periods"][0] - response_grading_period.update({"course_id": self.id}) + def update_submission(self, assignment, user, **kwargs): + """ + Comment on and/or update the grading for a student's assignment submission. - return GradingPeriod(self._requester, response_grading_period) + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.submission.Submission.edit` instead. - def get_content_exports(self, **kwargs): - """ - Return a paginated list of the past and pending content export jobs for a course. + :calls: `PUT /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id \ + `_ - :calls: `GET /api/v1/courses/:course_id/content_exports\ - `_ + :param assignment: The object or ID of the related assignment + :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param user: The object or ID of the related user + :type user: :class:`canvasapi.user.User` or int - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_export.ContentExport` + :rtype: :class:`canvasapi.submission.Submission` """ - from canvasapi.content_export import ContentExport + from canvasapi.assignment import Assignment + from canvasapi.user import User - return PaginatedList( - ContentExport, - self._requester, - "GET", - "courses/{}/content_exports".format(self.id), - kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`Course.update_submission()` is deprecated and will be removed in a " + "future version. Use `Submission.edit()` instead", + DeprecationWarning, ) - def get_content_export(self, content_export, **kwargs): - """ - Return information about a single content export. + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + user_id = obj_or_id(user, "user", (User,)) - :calls: `GET /api/v1/courses/:course_id/content_exports/:id\ - `_ + submission = Submission( + self._requester, + {"course_id": self.id, "assignment_id": assignment_id, "user_id": user_id}, + ) - :param content_export: The object or ID of the content export to show. - :type content_export: int or :class:`canvasapi.content_export.ContentExport` + return submission.edit(**kwargs) - :rtype: :class:`canvasapi.content_export.ContentExport` + def update_tab(self, tab_id, **kwargs): """ - from canvasapi.content_export import ContentExport + Update a tab for a course. - export_id = obj_or_id(content_export, "content_export", (ContentExport,)) + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.tab.Tab.update` instead. - response = self._requester.request( - "GET", - "courses/{}/content_exports/{}".format(self.id, export_id), - _kwargs=combine_kwargs(**kwargs), - ) + :calls: `PUT /api/v1/courses/:course_id/tabs/:tab_id \ + `_ - return ContentExport(self._requester, response.json()) + :param tab_id: The ID of the tab + :type tab_id: str - def export_content(self, export_type, **kwargs): + :rtype: :class:`canvasapi.tab.Tab` """ - Begin a content export job for a course. - - :calls: `POST /api/v1/courses/:course_id/content_exports\ - `_ + warnings.warn( + "`Course.update_tab()` is being deprecated and will be removed in " + "a future version. Use `Tab.update()` instead", + DeprecationWarning, + ) - :param export_type: The type of content to export. - :type export_type: str + tab = Tab(self._requester, {"course_id": self.id, "id": tab_id}) + return tab.update(**kwargs) - :rtype: :class:`canvasapi.content_export.ContentExport` + def upload(self, file, **kwargs): """ - from canvasapi.content_export import ContentExport + Upload a file to this course. - kwargs["export_type"] = export_type + :calls: `POST /api/v1/courses/:course_id/files \ + `_ - response = self._requester.request( - "POST", - "courses/{}/content_exports".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - return ContentExport(self._requester, response.json()) + :param file: The file or path of the file to upload. + :type file: file or str + :returns: True if the file uploaded successfully, False otherwise, \ + and the JSON response from the API. + :rtype: tuple + """ + return Uploader( + self._requester, "courses/{}/files".format(self.id), file, **kwargs + ).start() @python_2_unicode_compatible diff --git a/canvasapi/current_user.py b/canvasapi/current_user.py index 1aee6813..d2d89a87 100644 --- a/canvasapi/current_user.py +++ b/canvasapi/current_user.py @@ -25,79 +25,63 @@ def __init__(self, _requester): def __str__(self): return "{} ({})".format(self.name, self.id) - def list_groups(self, **kwargs): - """ - Return the list of active groups for the user. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.current_user.CurrentUser.get_groups` instead. - - :calls: `GET /api/v1/users/self/groups \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + def add_favorite_course(self, course, use_sis_id=False, **kwargs): """ - warnings.warn( - "`list_groups` is being deprecated and will be removed in a " - "future version. Use `get_groups` instead", - DeprecationWarning, - ) + Add a course to the current user's favorites. If the course is already + in the user's favorites, nothing happens. - return self.get_groups(**kwargs) + :calls: `POST /api/v1/users/self/favorites/courses/:id \ + `_ - def get_groups(self, **kwargs): - """ - Return the list of active groups for the user. + :param course: The course or ID/SIS ID of the course. + :type course: :class:`canvasapi.course.Course` or int - :calls: `GET /api/v1/users/self/groups \ - `_ + :param use_sis_id: Whether or not `course` is an sis ID. + Defaults to `False`. + :type use_sis_id: bool - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + :rtype: :class:`canvasapi.favorite.Favorite` """ - from canvasapi.group import Group + if use_sis_id: + course_id = course + uri_str = "users/self/favorites/courses/sis_course_id:{}" + else: + course_id = obj_or_id(course, "course", (Course,)) + uri_str = "users/self/favorites/courses/{}" - return PaginatedList( - Group, - self._requester, - "GET", - "users/self/groups", - _kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "POST", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) ) + return Favorite(self._requester, response.json()) - def list_bookmarks(self, **kwargs): + def add_favorite_group(self, group, use_sis_id=False, **kwargs): """ - List bookmarks that the current user can view or manage. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.current_user.CurrentUser.get_bookmarks` instead. + Add a group to the current user's favorites. If the group is already + in the user's favorites, nothing happens. - :calls: `GET /api/v1/users/self/bookmarks \ - `_ + :calls: `POST /api/v1/users/self/favorites/groups/:id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.bookmark.Bookmark` - """ - warnings.warn( - "`list_bookmarks` is being deprecated and will be removed in a " - "future version. Use `get_bookmarks` instead", - DeprecationWarning, - ) + :param group: The ID or SIS ID of the group. + :type group: :class:`canvasapi.group.Group` or int - return self.get_bookmarks(**kwargs) + :param use_sis_id: Whether or not `group` is an sis ID. + Defaults to `False`. + :type use_sis_id: bool - def get_bookmarks(self, **kwargs): + :rtype: :class:`canvasapi.favorite.Favorite` """ - List bookmarks that the current user can view or manage. - - :calls: `GET /api/v1/users/self/bookmarks \ - `_ + if use_sis_id: + group_id = group + uri_str = "users/self/favorites/groups/sis_group_id:{}" + else: + group_id = obj_or_id(group, "group", (Group,)) + uri_str = "users/self/favorites/groups/{}" - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.bookmark.Bookmark` - """ - return PaginatedList(Bookmark, self._requester, "GET", "users/self/bookmarks") + response = self._requester.request( + "POST", uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) + ) + return Favorite(self._requester, response.json()) def create_bookmark(self, name, url, **kwargs): """ @@ -145,6 +129,18 @@ def get_bookmark(self, bookmark): ) return Bookmark(self._requester, response.json()) + def get_bookmarks(self, **kwargs): + """ + List bookmarks that the current user can view or manage. + + :calls: `GET /api/v1/users/self/bookmarks \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.bookmark.Bookmark` + """ + return PaginatedList(Bookmark, self._requester, "GET", "users/self/bookmarks") + def get_favorite_courses(self, **kwargs): """ Retrieve the paginated list of favorite courses for the current user. @@ -187,63 +183,67 @@ def get_favorite_groups(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def add_favorite_course(self, course, use_sis_id=False, **kwargs): + def get_groups(self, **kwargs): """ - Add a course to the current user's favorites. If the course is already - in the user's favorites, nothing happens. - - :calls: `POST /api/v1/users/self/favorites/courses/:id \ - `_ - - :param course: The course or ID/SIS ID of the course. - :type course: :class:`canvasapi.course.Course` or int + Return the list of active groups for the user. - :param use_sis_id: Whether or not `course` is an sis ID. - Defaults to `False`. - :type use_sis_id: bool + :calls: `GET /api/v1/users/self/groups \ + `_ - :rtype: :class:`canvasapi.favorite.Favorite` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` """ - if use_sis_id: - course_id = course - uri_str = "users/self/favorites/courses/sis_course_id:{}" - else: - course_id = obj_or_id(course, "course", (Course,)) - uri_str = "users/self/favorites/courses/{}" + from canvasapi.group import Group - response = self._requester.request( - "POST", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs) + return PaginatedList( + Group, + self._requester, + "GET", + "users/self/groups", + _kwargs=combine_kwargs(**kwargs), ) - return Favorite(self._requester, response.json()) - def add_favorite_group(self, group, use_sis_id=False, **kwargs): + def list_bookmarks(self, **kwargs): """ - Add a group to the current user's favorites. If the group is already - in the user's favorites, nothing happens. + List bookmarks that the current user can view or manage. - :calls: `POST /api/v1/users/self/favorites/groups/:id \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.current_user.CurrentUser.get_bookmarks` instead. - :param group: The ID or SIS ID of the group. - :type group: :class:`canvasapi.group.Group` or int + :calls: `GET /api/v1/users/self/bookmarks \ + `_ - :param use_sis_id: Whether or not `group` is an sis ID. - Defaults to `False`. - :type use_sis_id: bool + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.bookmark.Bookmark` + """ + warnings.warn( + "`list_bookmarks` is being deprecated and will be removed in a " + "future version. Use `get_bookmarks` instead", + DeprecationWarning, + ) - :rtype: :class:`canvasapi.favorite.Favorite` + return self.get_bookmarks(**kwargs) + + def list_groups(self, **kwargs): """ - if use_sis_id: - group_id = group - uri_str = "users/self/favorites/groups/sis_group_id:{}" - else: - group_id = obj_or_id(group, "group", (Group,)) - uri_str = "users/self/favorites/groups/{}" + Return the list of active groups for the user. - response = self._requester.request( - "POST", uri_str.format(group_id), _kwargs=combine_kwargs(**kwargs) + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.current_user.CurrentUser.get_groups` instead. + + :calls: `GET /api/v1/users/self/groups \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` + """ + warnings.warn( + "`list_groups` is being deprecated and will be removed in a " + "future version. Use `get_groups` instead", + DeprecationWarning, ) - return Favorite(self._requester, response.json()) + + return self.get_groups(**kwargs) def reset_favorite_courses(self, **kwargs): """ diff --git a/canvasapi/discussion_topic.py b/canvasapi/discussion_topic.py index a1e93b0d..d562ea3d 100644 --- a/canvasapi/discussion_topic.py +++ b/canvasapi/discussion_topic.py @@ -42,24 +42,6 @@ def _parent_type(self): else: raise ValueError("Discussion Topic does not have a course_id or group_id") - def get_parent(self): - """ - Return the object that spawned this discussion topic. - - :rtype: :class:`canvasapi.group.Group` or :class:`canvasapi.course.Course` - """ - from canvasapi.group import Group - from canvasapi.course import Course - - response = self._requester.request( - "GET", "{}s/{}".format(self._parent_type, self._parent_id) - ) - - if self._parent_type == "group": - return Group(self._requester, response.json()) - elif self._parent_type == "course": - return Course(self._requester, response.json()) - def delete(self): """ Deletes the discussion topic. This will also delete the assignment. @@ -81,79 +63,58 @@ def delete(self): ) return "deleted_at" in response.json() - def update(self, **kwargs): + def get_entries(self, ids, **kwargs): """ - Updates an existing discussion topic for the course or group. + Retrieve a paginated list of discussion entries, given a list + of ids. Entries will be returned in id order, smallest id first. - :calls: `PUT /api/v1/courses/:course_id/discussion_topics/:topic_id \ - `_ + :calls: `GET /api/v1/courses/:course_id/discussion_topics/:topic_id/entry_list \ + `_ - or `PUT /api/v1/groups/:group_id/discussion_topics/:topic_id \ - `_ + or `GET /api/v1/groups/:group_id/discussion_topics/:topic_id/entry_list \ + `_ - :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` - """ - response = self._requester.request( - "PUT", - "{}s/{}/discussion_topics/{}".format( - self._parent_type, self._parent_id, self.id - ), - _kwargs=combine_kwargs(**kwargs), - ) - return DiscussionTopic(self._requester, response.json()) + :param ids: A list of entry objects or IDs to retrieve. + :type ids: :class:`canvasapi.discussion_topic.DiscussionEntry`, or list or tuple of int - def post_entry(self, **kwargs): + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.discussion_topic.DiscussionEntry` """ - Creates a new entry in a discussion topic. - :calls: `POST /api/v1/courses/:course_id/discussion_topics/:topic_id/entries \ - `_ - - or `POST /api/v1/groups/:group_id/discussion_topics/:topic_id/entries \ - `_ + entry_ids = [obj_or_id(item, "ids", (DiscussionEntry,)) for item in ids] - :rtype: :class:`canvasapi.discussion_topic.DiscussionEntry` - """ - response = self._requester.request( - "POST", - "{}s/{}/discussion_topics/{}/entries".format( + kwargs.update(ids=entry_ids) + return PaginatedList( + DiscussionEntry, + self._requester, + "GET", + "{}s/{}/discussion_topics/{}/entry_list".format( self._parent_type, self._parent_id, self.id ), - _kwargs=combine_kwargs(**kwargs), - ) - response_json = response.json() - response_json.update( { "discussion_id": self.id, "{}_id".format(self._parent_type): self._parent_id, - } + }, + _kwargs=combine_kwargs(**kwargs), ) - return DiscussionEntry(self._requester, response_json) - def list_topic_entries(self, **kwargs): + def get_parent(self): """ - Retreive the top-level entries in a discussion topic. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.discussion_topic.DiscussionTopic.get_topic_entries` instead. - - :calls: `GET /api/v1/courses/:course_id/discussion_topics/:topic_id/entries \ - `_ - - or `GET /api/v1/groups/:group_id/discussion_topics/:topic_id/entries \ - `_ + Return the object that spawned this discussion topic. - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.discussion_topic.DiscussionEntry` + :rtype: :class:`canvasapi.group.Group` or :class:`canvasapi.course.Course` """ - warnings.warn( - "`list_topic_entries` is being deprecated and will be removed in " - "a future version. Use `get_topic_entries` instead", - DeprecationWarning, + from canvasapi.group import Group + from canvasapi.course import Course + + response = self._requester.request( + "GET", "{}s/{}".format(self._parent_type, self._parent_id) ) - return self.get_topic_entries(**kwargs) + if self._parent_type == "group": + return Group(self._requester, response.json()) + elif self._parent_type == "course": + return Course(self._requester, response.json()) def get_topic_entries(self, **kwargs): """ @@ -211,41 +172,31 @@ def list_entries(self, ids, **kwargs): return self.get_entries(ids, **kwargs) - def get_entries(self, ids, **kwargs): + def list_topic_entries(self, **kwargs): """ - Retrieve a paginated list of discussion entries, given a list - of ids. Entries will be returned in id order, smallest id first. + Retreive the top-level entries in a discussion topic. - :calls: `GET /api/v1/courses/:course_id/discussion_topics/:topic_id/entry_list \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.discussion_topic.DiscussionTopic.get_topic_entries` instead. - or `GET /api/v1/groups/:group_id/discussion_topics/:topic_id/entry_list \ - `_ + :calls: `GET /api/v1/courses/:course_id/discussion_topics/:topic_id/entries \ + `_ - :param ids: A list of entry objects or IDs to retrieve. - :type ids: :class:`canvasapi.discussion_topic.DiscussionEntry`, or list or tuple of int + or `GET /api/v1/groups/:group_id/discussion_topics/:topic_id/entries \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.discussion_topic.DiscussionEntry` """ - - entry_ids = [obj_or_id(item, "ids", (DiscussionEntry,)) for item in ids] - - kwargs.update(ids=entry_ids) - return PaginatedList( - DiscussionEntry, - self._requester, - "GET", - "{}s/{}/discussion_topics/{}/entry_list".format( - self._parent_type, self._parent_id, self.id - ), - { - "discussion_id": self.id, - "{}_id".format(self._parent_type): self._parent_id, - }, - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_topic_entries` is being deprecated and will be removed in " + "a future version. Use `get_topic_entries` instead", + DeprecationWarning, ) + return self.get_topic_entries(**kwargs) + def mark_as_read(self): """ Mark the initial text of the discussion topic as read. @@ -328,6 +279,34 @@ def mark_entries_as_unread(self, **kwargs): ) return response.status_code == 204 + def post_entry(self, **kwargs): + """ + Creates a new entry in a discussion topic. + + :calls: `POST /api/v1/courses/:course_id/discussion_topics/:topic_id/entries \ + `_ + + or `POST /api/v1/groups/:group_id/discussion_topics/:topic_id/entries \ + `_ + + :rtype: :class:`canvasapi.discussion_topic.DiscussionEntry` + """ + response = self._requester.request( + "POST", + "{}s/{}/discussion_topics/{}/entries".format( + self._parent_type, self._parent_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + response_json = response.json() + response_json.update( + { + "discussion_id": self.id, + "{}_id".format(self._parent_type): self._parent_id, + } + ) + return DiscussionEntry(self._requester, response_json) + def subscribe(self): """ Subscribe to a topic to receive notifications about new entries. @@ -368,6 +347,27 @@ def unsubscribe(self): ) return response.status_code == 204 + def update(self, **kwargs): + """ + Updates an existing discussion topic for the course or group. + + :calls: `PUT /api/v1/courses/:course_id/discussion_topics/:topic_id \ + `_ + + or `PUT /api/v1/groups/:group_id/discussion_topics/:topic_id \ + `_ + + :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` + """ + response = self._requester.request( + "PUT", + "{}s/{}/discussion_topics/{}".format( + self._parent_type, self._parent_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + return DiscussionTopic(self._requester, response.json()) + @python_2_unicode_compatible class DiscussionEntry(CanvasObject): @@ -402,57 +402,6 @@ def _discussion_parent_type(self): else: raise ValueError("Discussion Topic does not have a course_id or group_id") - def get_discussion(self): - """ - Return the discussion topic object this entry is related to - - :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` - """ - - response = self._requester.request( - "GET", - "{}s/{}/discussion_topics/{}".format( - self._discussion_parent_type, - self._discussion_parent_id, - self.discussion_id, - ), - ) - - response_json = response.json() - response_json.update( - {"{}_id".format(self._discussion_parent_type): self._discussion_parent_id} - ) - - return DiscussionTopic(self._requester, response.json()) - - def update(self, **kwargs): - """ - Updates an existing discussion entry. - - :calls: `PUT /api/v1/courses/:course_id/discussion_topics/:topic_id/entries/:id \ - `_ - - or `PUT /api/v1/groups/:group_id/discussion_topics/:topic_id/entries/:id \ - `_ - - :rtype: bool - """ - response = self._requester.request( - "PUT", - "{}s/{}/discussion_topics/{}/entries/{}".format( - self._discussion_parent_type, - self._discussion_parent_id, - self.discussion_id, - self.id, - ), - _kwargs=combine_kwargs(**kwargs), - ) - - if response.json().get("updated_at"): - super(DiscussionEntry, self).set_attributes(response.json()) - - return "updated_at" in response.json() - def delete(self, **kwargs): """ Delete this discussion entry. @@ -477,59 +426,28 @@ def delete(self, **kwargs): ) return "deleted_at" in response.json() - def post_reply(self, **kwargs): + def get_discussion(self): """ - Add a reply to this entry. - - :calls: `POST - /api/v1/courses/:course_id/discussion_topics/:topic_id/entries/:entry_id/replies - `_ - - or `POST /api/v1/groups/:group_id/discussion_topics/:topic_id/entries/:entry_id/replies - `_ + Return the discussion topic object this entry is related to - :rtype: :class:`canvasapi.discussion_topic.DiscussionEntry` + :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` """ + response = self._requester.request( - "POST", - "{}s/{}/discussion_topics/{}/entries/{}/replies".format( + "GET", + "{}s/{}/discussion_topics/{}".format( self._discussion_parent_type, self._discussion_parent_id, self.discussion_id, - self.id, ), - _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update(discussion_id=self.discussion_id) - return DiscussionEntry(self._requester, response_json) - - def list_replies(self, **kwargs): - """ - Retrieves the replies to a top-level entry in a discussion topic. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi. discussion_topic.DiscussionEntry.get_replies` instead. - :calls: `GET - /api/v1/courses/:course_id/discussion_topics/:topic_id/entries/:entry_id/replies \ - `_ - - or `GET - /api/v1/groups/:group_id/discussion_topics/:topic_id/entries/:entry_id/replies \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.discussion_topic.DiscussionEntry` - """ - warnings.warn( - "`list_replies` is being deprecated and will be removed in a " - "future version. Use `get_replies` instead.", - DeprecationWarning, + response_json = response.json() + response_json.update( + {"{}_id".format(self._discussion_parent_type): self._discussion_parent_id} ) - return self.get_replies(**kwargs) + return DiscussionTopic(self._requester, response.json()) def get_replies(self, **kwargs): """ @@ -565,7 +483,33 @@ def get_replies(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - # TODO: update to use correct class + def list_replies(self, **kwargs): + """ + Retrieves the replies to a top-level entry in a discussion topic. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi. discussion_topic.DiscussionEntry.get_replies` instead. + + :calls: `GET + /api/v1/courses/:course_id/discussion_topics/:topic_id/entries/:entry_id/replies \ + `_ + + or `GET + /api/v1/groups/:group_id/discussion_topics/:topic_id/entries/:entry_id/replies \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.discussion_topic.DiscussionEntry` + """ + warnings.warn( + "`list_replies` is being deprecated and will be removed in a " + "future version. Use `get_replies` instead.", + DeprecationWarning, + ) + + return self.get_replies(**kwargs) + def mark_as_read(self): """ Mark a discussion entry as read. @@ -589,7 +533,6 @@ def mark_as_read(self): ) return response.status_code == 204 - # TODO: update to use correct class def mark_as_unread(self): """ Mark a discussion entry as unread. @@ -615,6 +558,35 @@ def mark_as_unread(self): ) return response.status_code == 204 + # TODO: update to use correct class + def post_reply(self, **kwargs): + """ + Add a reply to this entry. + + :calls: `POST + /api/v1/courses/:course_id/discussion_topics/:topic_id/entries/:entry_id/replies + `_ + + or `POST /api/v1/groups/:group_id/discussion_topics/:topic_id/entries/:entry_id/replies + `_ + + :rtype: :class:`canvasapi.discussion_topic.DiscussionEntry` + """ + response = self._requester.request( + "POST", + "{}s/{}/discussion_topics/{}/entries/{}/replies".format( + self._discussion_parent_type, + self._discussion_parent_id, + self.discussion_id, + self.id, + ), + _kwargs=combine_kwargs(**kwargs), + ) + response_json = response.json() + response_json.update(discussion_id=self.discussion_id) + return DiscussionEntry(self._requester, response_json) + + # TODO: update to use correct class def rate(self, rating, **kwargs): """ Rate this discussion entry. @@ -646,3 +618,31 @@ def rate(self, rating, **kwargs): _kwargs=combine_kwargs(**kwargs), ) return response.status_code == 204 + + def update(self, **kwargs): + """ + Updates an existing discussion entry. + + :calls: `PUT /api/v1/courses/:course_id/discussion_topics/:topic_id/entries/:id \ + `_ + + or `PUT /api/v1/groups/:group_id/discussion_topics/:topic_id/entries/:id \ + `_ + + :rtype: bool + """ + response = self._requester.request( + "PUT", + "{}s/{}/discussion_topics/{}/entries/{}".format( + self._discussion_parent_type, + self._discussion_parent_id, + self.discussion_id, + self.id, + ), + _kwargs=combine_kwargs(**kwargs), + ) + + if response.json().get("updated_at"): + super(DiscussionEntry, self).set_attributes(response.json()) + + return "updated_at" in response.json() diff --git a/canvasapi/file.py b/canvasapi/file.py index 04b3356b..c8c70e70 100644 --- a/canvasapi/file.py +++ b/canvasapi/file.py @@ -22,15 +22,6 @@ def delete(self): response = self._requester.request("DELETE", "files/{}".format(self.id)) return File(self._requester, response.json()) - def get_contents(self): - """ - Download the contents of this file. - - :rtype: str - """ - response = self._requester.request("GET", _url=self.url) - return response.text - def download(self, location): """ Download the file to specified location. @@ -42,3 +33,12 @@ def download(self, location): with open(location, "wb") as file_out: file_out.write(response.content) + + def get_contents(self): + """ + Download the contents of this file. + + :rtype: str + """ + response = self._requester.request("GET", _url=self.url) + return response.text diff --git a/canvasapi/folder.py b/canvasapi/folder.py index 2b4412c9..894caaff 100644 --- a/canvasapi/folder.py +++ b/canvasapi/folder.py @@ -15,47 +15,49 @@ class Folder(CanvasObject): def __str__(self): return "{}".format(self.full_name) - def list_files(self, **kwargs): + def copy_file(self, source_file, **kwargs): """ - Returns the paginated list of files for the folder. + Copies a file into the current folder. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.folder.Folder.get_files` instead. + :calls: `POST /api/v1/folders/:dest_folder_id/copy_file \ + `_ - :calls: `GET /api/v1/folders/:id/files \ - `_ + :param source_file: The object or id of the source file. + :type source_file: int or :class:`canvasapi.file.File` - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` + :rtype: :class:`canvasapi.folder.Folder` """ - warnings.warn( - "`list_files` is being deprecated and will be removed in a future " - "version. Use `get_files` instead", - DeprecationWarning, + from canvasapi.file import File + + file_id = obj_or_id(source_file, "source_file", (File,)) + kwargs["source_file_id"] = file_id + + response = self._requester.request( + "POST", + "folders/{}/copy_file".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_files(**kwargs) + return File(self._requester, response.json()) - def get_files(self, **kwargs): + def create_folder(self, name, **kwargs): """ - Returns the paginated list of files for the folder. + Creates a folder within this folder. - :calls: `GET /api/v1/folders/:id/files \ - `_ + :calls: `POST /api/v1/folders/:folder_id/folders \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` + :param name: The name of the folder. + :type name: str + :rtype: :class:`canvasapi.folder.Folder` """ - from canvasapi.file import File - - return PaginatedList( - File, - self._requester, - "GET", - "folders/{}/files".format(self.id), + response = self._requester.request( + "POST", + "folders/{}/folders".format(self.id), + name=name, _kwargs=combine_kwargs(**kwargs), ) + return Folder(self._requester, response.json()) def delete(self, **kwargs): """ @@ -72,27 +74,25 @@ def delete(self, **kwargs): ) return Folder(self._requester, response.json()) - def list_folders(self, **kwargs): + def get_files(self, **kwargs): """ - Returns the paginated list of folders in the folder. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.folder.Folder.get_folders` instead. + Returns the paginated list of files for the folder. - :calls: `GET /api/v1/folders/:id/folders \ - `_ + :calls: `GET /api/v1/folders/:id/files \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.folder.Folder` + :class:`canvasapi.file.File` """ - warnings.warn( - "`list_folders` is being deprecated and will be removed in a " - "future version. Use `get_folders` instead", - DeprecationWarning, - ) + from canvasapi.file import File - return self.get_folders(**kwargs) + return PaginatedList( + File, + self._requester, + "GET", + "folders/{}/files".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) def get_folders(self, **kwargs): """ @@ -108,40 +108,49 @@ def get_folders(self, **kwargs): Folder, self._requester, "GET", "folders/{}/folders".format(self.id) ) - def create_folder(self, name, **kwargs): + def list_files(self, **kwargs): """ - Creates a folder within this folder. + Returns the paginated list of files for the folder. - :calls: `POST /api/v1/folders/:folder_id/folders \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.folder.Folder.get_files` instead. - :param name: The name of the folder. - :type name: str - :rtype: :class:`canvasapi.folder.Folder` + :calls: `GET /api/v1/folders/:id/files \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.file.File` """ - response = self._requester.request( - "POST", - "folders/{}/folders".format(self.id), - name=name, - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_files` is being deprecated and will be removed in a future " + "version. Use `get_files` instead", + DeprecationWarning, ) - return Folder(self._requester, response.json()) - def upload(self, file, **kwargs): + return self.get_files(**kwargs) + + def list_folders(self, **kwargs): """ - Upload a file to this folder. + Returns the paginated list of folders in the folder. - :calls: `POST /api/v1/folders/:folder_id/files \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.folder.Folder.get_folders` instead. - :param file: The file or path of the file to upload. - :type file: file or str - :returns: True if the file uploaded successfully, False otherwise, \ - and the JSON response from the API. - :rtype: tuple + :calls: `GET /api/v1/folders/:id/folders \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.folder.Folder` """ - my_path = "folders/{}/files".format(self.id) - return Uploader(self._requester, my_path, file, **kwargs).start() + warnings.warn( + "`list_folders` is being deprecated and will be removed in a " + "future version. Use `get_folders` instead", + DeprecationWarning, + ) + + return self.get_folders(**kwargs) def update(self, **kwargs): """ @@ -161,27 +170,18 @@ def update(self, **kwargs): return Folder(self._requester, response.json()) - def copy_file(self, source_file, **kwargs): + def upload(self, file, **kwargs): """ - Copies a file into the current folder. - - :calls: `POST /api/v1/folders/:dest_folder_id/copy_file \ - `_ + Upload a file to this folder. - :param source_file: The object or id of the source file. - :type source_file: int or :class:`canvasapi.file.File` + :calls: `POST /api/v1/folders/:folder_id/files \ + `_ - :rtype: :class:`canvasapi.folder.Folder` + :param file: The file or path of the file to upload. + :type file: file or str + :returns: True if the file uploaded successfully, False otherwise, \ + and the JSON response from the API. + :rtype: tuple """ - from canvasapi.file import File - - file_id = obj_or_id(source_file, "source_file", (File,)) - kwargs["source_file_id"] = file_id - - response = self._requester.request( - "POST", - "folders/{}/copy_file".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - - return File(self._requester, response.json()) + my_path = "folders/{}/files".format(self.id) + return Uploader(self._requester, my_path, file, **kwargs).start() diff --git a/canvasapi/grading_period.py b/canvasapi/grading_period.py index c43d91c3..842e4d57 100644 --- a/canvasapi/grading_period.py +++ b/canvasapi/grading_period.py @@ -12,6 +12,24 @@ class GradingPeriod(CanvasObject): def __str__(self): return "{} ({})".format(self.title, self.id) + def delete(self, **kwargs): + """ + Delete a grading period for a course. + + :calls: `DELETE /api/v1/courses/:course_id/grading_periods/:id \ + `_ + + :returns: Status code 204 if delete was successful + :rtype: int + """ + response = self._requester.request( + "DELETE", + "courses/{}/grading_periods/{}".format(self.course_id, self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + return response.status_code + def update(self, grading_period, **kwargs): """ Update a grading period for a course. @@ -46,21 +64,3 @@ def update(self, grading_period, **kwargs): grading_period.update({"course_id": self.course_id}) return GradingPeriod(self._requester, grading_period) - - def delete(self, **kwargs): - """ - Delete a grading period for a course. - - :calls: `DELETE /api/v1/courses/:course_id/grading_periods/:id \ - `_ - - :returns: Status code 204 if delete was successful - :rtype: int - """ - response = self._requester.request( - "DELETE", - "courses/{}/grading_periods/{}".format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs), - ) - - return response.status_code diff --git a/canvasapi/group.py b/canvasapi/group.py index f51a9db6..aadf81a9 100644 --- a/canvasapi/group.py +++ b/canvasapi/group.py @@ -18,130 +18,150 @@ class Group(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) - def create_page(self, wiki_page, **kwargs): + def create_content_migration(self, migration_type, **kwargs): """ - Create a new wiki page. + Create a content migration. - :calls: `POST /api/v1/groups/:group_id/pages \ - `_ + :calls: `POST /api/v1/groups/:group_id/content_migrations \ + `_ - :param wiki_page: Details about the page to create. - :type wiki_page: dict - :returns: The created page. - :rtype: :class:`canvasapi.page.Page` + :param migration_type: The migrator type to use in this migration + :type migration_type: str or :class:`canvasapi.content_migration.Migrator` + + :rtype: :class:`canvasapi.content_migration.ContentMigration` """ - from canvasapi.course import Page + from canvasapi.content_migration import ContentMigration, Migrator - if isinstance(wiki_page, dict) and "title" in wiki_page: - kwargs["wiki_page"] = wiki_page + if isinstance(migration_type, Migrator): + kwargs["migration_type"] = migration_type.type + elif isinstance(migration_type, string_types): + kwargs["migration_type"] = migration_type else: - raise RequiredFieldMissing("Dictionary with key 'title' is required.") + raise TypeError("Parameter migration_type must be of type Migrator or str") response = self._requester.request( - "POST", "groups/{}/pages".format(self.id), _kwargs=combine_kwargs(**kwargs) + "POST", + "groups/{}/content_migrations".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"group_id": self.id}) + response_json = response.json() + response_json.update({"group_id": self.id}) - return Page(self._requester, page_json) + return ContentMigration(self._requester, response_json) - def edit_front_page(self, **kwargs): + def create_discussion_topic(self, **kwargs): """ - Update the title or contents of the front page. + Creates a new discussion topic for the course or group. - :calls: `PUT /api/v1/groups/:group_id/front_page \ - `_ + :calls: `POST /api/v1/groups/:group_id/discussion_topics \ + `_ - :rtype: :class:`canvasapi.page.Page` + :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` """ - from canvasapi.course import Page - response = self._requester.request( - "PUT", - "groups/{}/front_page".format(self.id), + "POST", + "groups/{}/discussion_topics".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"group_id": self.id}) - return Page(self._requester, page_json) + response_json = response.json() + response_json.update({"group_id": self.id}) - def show_front_page(self): + return DiscussionTopic(self._requester, response_json) + + def create_external_feed(self, url, **kwargs): """ - Retrieve the content of the front page. + Create a new external feed for the group. - :calls: `GET /api/v1/groups/:group_id/front_page \ - `_ + :calls: `POST /api/v1/groups/:group_id/external_feeds \ + `_ - :rtype: :class:`canvasapi.group.Group` + :param url: The urlof the external rss or atom feed + :type url: str + :rtype: :class:`canvasapi.external_feed.ExternalFeed` """ - from canvasapi.course import Page + from canvasapi.external_feed import ExternalFeed response = self._requester.request( - "GET", "groups/{}/front_page".format(self.id) + "POST", + "groups/{}/external_feeds".format(self.id), + url=url, + _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"group_id": self.id}) - - return Page(self._requester, page_json) + return ExternalFeed(self._requester, response.json()) - def get_page(self, url): + def create_folder(self, name, **kwargs): """ - Retrieve the contents of a wiki page. + Creates a folder in this group. - :calls: `GET /api/v1/groups/:group_id/pages/:url \ - `_ + :calls: `POST /api/v1/groups/:group_id/folders \ + `_ - :param url: The url for the page. - :type url: str - :returns: The specified page. - :rtype: :class:`canvasapi.groups.Group` + :param name: The name of the folder. + :type name: str + :rtype: :class:`canvasapi.folder.Folder` """ - from canvasapi.course import Page - response = self._requester.request( - "GET", "groups/{}/pages/{}".format(self.id, url) + "POST", + "groups/{}/folders".format(self.id), + name=name, + _kwargs=combine_kwargs(**kwargs), ) - page_json = response.json() - page_json.update({"group_id": self.id}) - - return Page(self._requester, page_json) + return Folder(self._requester, response.json()) - def get_pages(self, **kwargs): + def create_membership(self, user, **kwargs): """ - List the wiki pages associated with a group. + Join, or request to join, a group, depending on the join_level of the group. + If the membership or join request already exists, then it is simply returned. - :calls: `GET /api/v1/groups/:group_id/pages \ - `_ + :calls: `POST /api/v1/groups/:group_id/memberships \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.page.Page` + :param user: The object or ID of the user. + :type user: :class:`canvasapi.user.User` or int + + :rtype: :class:`canvasapi.group.GroupMembership` """ - from canvasapi.course import Page + from canvasapi.user import User - return PaginatedList( - Page, - self._requester, - "GET", - "groups/{}/pages".format(self.id), - {"group_id": self.id}, + user_id = obj_or_id(user, "user", (User,)) + + response = self._requester.request( + "POST", + "groups/{}/memberships".format(self.id), + user_id=user_id, _kwargs=combine_kwargs(**kwargs), ) + return GroupMembership(self._requester, response.json()) - def edit(self, **kwargs): + def create_page(self, wiki_page, **kwargs): """ - Edit a group. + Create a new wiki page. - :calls: `PUT /api/v1/groups/:group_id \ - `_ + :calls: `POST /api/v1/groups/:group_id/pages \ + `_ - :rtype: :class:`canvasapi.group.Group` + :param wiki_page: Details about the page to create. + :type wiki_page: dict + :returns: The created page. + :rtype: :class:`canvasapi.page.Page` """ + from canvasapi.course import Page + + if isinstance(wiki_page, dict) and "title" in wiki_page: + kwargs["wiki_page"] = wiki_page + else: + raise RequiredFieldMissing("Dictionary with key 'title' is required.") + response = self._requester.request( - "PUT", "groups/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) + "POST", "groups/{}/pages".format(self.id), _kwargs=combine_kwargs(**kwargs) ) - return Group(self._requester, response.json()) + + page_json = response.json() + page_json.update({"group_id": self.id}) + + return Page(self._requester, page_json) def delete(self): """ @@ -155,300 +175,355 @@ def delete(self): response = self._requester.request("DELETE", "groups/{}".format(self.id)) return Group(self._requester, response.json()) - def invite(self, invitees): + def delete_external_feed(self, feed): """ - Invite users to group. + Deletes the external feed. - :calls: `POST /api/v1/groups/:group_id/invite \ - `_ + :calls: `DELETE /api/v1/groups/:group_id/external_feeds/:external_feed_id \ + `_ - :param invitees: list of user ids - :type invitees: integer list + :param feed: The object or id of the feed to be deleted. + :type feed: :class:`canvasapi.external_feed.ExternalFeed` or int - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupMembership` + :rtype: :class:`canvasapi.external_feed.ExternalFeed` """ - return PaginatedList( - GroupMembership, - self._requester, - "POST", - "groups/{}/invite".format(self.id), - invitees=invitees, + from canvasapi.external_feed import ExternalFeed + + feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) + + response = self._requester.request( + "DELETE", "groups/{}/external_feeds/{}".format(self.id, feed_id) ) + return ExternalFeed(self._requester, response.json()) - def list_users(self, **kwargs): + def edit(self, **kwargs): """ - List users in a group. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.group.Group.get_users` instead. + Edit a group. - :calls: `GET /api/v1/groups/:group_id/users \ - `_ + :calls: `PUT /api/v1/groups/:group_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.group.Group` """ - warnings.warn( - "`list_users` is being deprecated and will be removed in a future " - "version. Use `get_users` instead", - DeprecationWarning, + response = self._requester.request( + "PUT", "groups/{}".format(self.id), _kwargs=combine_kwargs(**kwargs) ) + return Group(self._requester, response.json()) - return self.get_users(**kwargs) - - def get_users(self, **kwargs): + def edit_front_page(self, **kwargs): """ - List users in a group. + Update the title or contents of the front page. - :calls: `GET /api/v1/groups/:group_id/users \ - `_ + :calls: `PUT /api/v1/groups/:group_id/front_page \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.page.Page` """ - from canvasapi.user import User + from canvasapi.course import Page - return PaginatedList( - User, - self._requester, - "GET", - "groups/{}/users".format(self.id), + response = self._requester.request( + "PUT", + "groups/{}/front_page".format(self.id), _kwargs=combine_kwargs(**kwargs), ) + page_json = response.json() + page_json.update({"group_id": self.id}) - def remove_user(self, user): - """ - Leave a group if allowed. + return Page(self._requester, page_json) - :calls: `DELETE /api/v1/groups/:group_id/users/:user_id \ - `_ + def export_content(self, export_type, **kwargs): + """ + Begin a content export job for a group. - :param user: The user object or ID to remove from the group. - :type user: :class:`canvasapi.user.User` or int + :calls: `POST /api/v1/groups/:group_id/content_exports\ + `_ - :rtype: :class:`canvasapi.user.User` + :param export_type: The type of content to export. + :type export_type: str + + :rtype: :class:`canvasapi.content_export.ContentExport` """ - from canvasapi.user import User + from canvasapi.content_export import ContentExport - user_id = obj_or_id(user, "user", (User,)) + kwargs["export_type"] = export_type response = self._requester.request( - "DELETE", "groups/{}/users/{}".format(self.id, user_id) + "POST", + "groups/{}/content_exports".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return User(self._requester, response.json()) + return ContentExport(self._requester, response.json()) - def upload(self, file, **kwargs): + def get_activity_stream_summary(self): """ - Upload a file to the group. - Only those with the 'Manage Files' permission on a group can upload files to the group. - By default, this is anybody participating in the group, or any admin over the group. + Return a summary of the current user's global activity stream. - :calls: `POST /api/v1/groups/:group_id/files \ - `_ + :calls: `GET /api/v1/groups/:group_id/activity_stream/summary \ + `_ - :param path: The path of the file to upload. - :type path: str - :param file: The file or path of the file to upload. - :type file: file or str - :returns: True if the file uploaded successfully, False otherwise, \ - and the JSON response from the API. - :rtype: tuple + :rtype: dict """ - from canvasapi.upload import Uploader - - return Uploader( - self._requester, "groups/{}/files".format(self.id), file, **kwargs - ).start() + response = self._requester.request( + "GET", "groups/{}/activity_stream/summary".format(self.id) + ) + return response.json() - def preview_html(self, html): + def get_assignment_override(self, assignment, **kwargs): """ - Preview HTML content processed for this course. + Return override for the specified assignment for this group. - :calls: `POST /api/v1/groups/:group_id/preview_html \ - `_ + :param assignment: The assignment to get an override for + :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param html: The HTML code to preview. - :type html: str - :rtype: str + :calls: `GET /api/v1/groups/:group_id/assignments/:assignment_id/override \ + `_ + + :rtype: :class:`canvasapi.assignment.AssignmentOverride` """ + from canvasapi.assignment import Assignment, AssignmentOverride + + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + response = self._requester.request( - "POST", "groups/{}/preview_html".format(self.id), html=html + "GET", "groups/{}/assignments/{}/override".format(self.id, assignment_id) ) - return response.json().get("html", "") + response_json = response.json() + response_json.update({"course_id": self.course_id}) - def get_activity_stream_summary(self): + return AssignmentOverride(self._requester, response_json) + + def get_content_export(self, content_export, **kwargs): """ - Return a summary of the current user's global activity stream. + Return information about a single content export. - :calls: `GET /api/v1/groups/:group_id/activity_stream/summary \ - `_ + :calls: `GET /api/v1/groups/:group_id/content_exports/:id\ + `_ - :rtype: dict + :param content_export: The object or ID of the content export to show. + :type content_export: int or :class:`canvasapi.content_export.ContentExport` + + :rtype: :class:`canvasapi.content_export.ContentExport` """ + from canvasapi.content_export import ContentExport + + export_id = obj_or_id(content_export, "content_export", (ContentExport,)) + response = self._requester.request( - "GET", "groups/{}/activity_stream/summary".format(self.id) + "GET", + "groups/{}/content_exports/{}".format(self.id, export_id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() - def list_memberships(self, **kwargs): - """ - List users in a group. + return ContentExport(self._requester, response.json()) - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.group.Group.get_memberships` instead. + def get_content_exports(self, **kwargs): + """ + Return a paginated list of the past and pending content export jobs for a group. - :calls: `GET /api/v1/groups/:group_id/memberships \ - `_ + :calls: `GET /api/v1/groups/:group_id/content_exports\ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupMembership` + :class:`canvasapi.content_export.ContentExport` """ - warnings.warn( - "`list_memberships` is being deprecated and will be removed in a " - "future version. Use `get_memberships` instead.", - DeprecationWarning, + from canvasapi.content_export import ContentExport + + return PaginatedList( + ContentExport, + self._requester, + "GET", + "groups/{}/content_exports".format(self.id), + kwargs=combine_kwargs(**kwargs), ) - return self.get_memberships(**kwargs) + def get_content_migration(self, content_migration, **kwargs): + """ + Retrive a content migration by its ID - def get_memberships(self, **kwargs): + :calls: `GET /api/v1/groups/:group_id/content_migrations/:id \ + `_ + + :param content_migration: The object or ID of the content migration to retrieve. + :type content_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + + :rtype: :class:`canvasapi.content_migration.ContentMigration` """ - List users in a group. + from canvasapi.content_migration import ContentMigration - :calls: `GET /api/v1/groups/:group_id/memberships \ - `_ + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) + ) + + response = self._requester.request( + "GET", + "groups/{}/content_migrations/{}".format(self.id, migration_id), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({"group_id": self.id}) + + return ContentMigration(self._requester, response_json) + + def get_content_migrations(self, **kwargs): + """ + List content migrations that the current account can view or manage. + + :calls: `GET /api/v1/groups/:group_id/content_migrations/ \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.group.GroupMembership` + :class:`canvasapi.content_migration.ContentMigration` """ + from canvasapi.content_migration import ContentMigration + return PaginatedList( - GroupMembership, + ContentMigration, self._requester, "GET", - "groups/{}/memberships".format(self.id), + "groups/{}/content_migrations".format(self.id), + {"group_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) - def get_membership(self, user, membership_type): + def get_discussion_topic(self, topic): """ - List users in a group. - - :calls: `GET /api/v1/groups/:group_id/users/:user_id \ - `_ + Return data on an individual discussion topic. - or `GET /api/v1/groups/:group_id/memberships/:membership_id - `_ + :calls: `GET /api/v1/groups/:group_id/discussion_topics/:topic_id \ + `_ - :param user: list of user ids - :type user: :class:`canvasapi.user.User` or int + :param topic: The object or ID of the discussion topic. + :type topic: :class:`canvasapi.discussion_topic.DiscussionTopic` or int - :rtype: :class:`canvasapi.group.GroupMembership` + :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` """ - from canvasapi.user import User - - user_id = obj_or_id(user, "user", (User,)) + topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) response = self._requester.request( - "GET", "groups/{}/{}/{}".format(self.id, membership_type, user_id) + "GET", "groups/{}/discussion_topics/{}".format(self.id, topic_id) ) - return GroupMembership(self._requester, response.json()) - def create_membership(self, user, **kwargs): + response_json = response.json() + response_json.update({"group_id": self.id}) + + return DiscussionTopic(self._requester, response_json) + + def get_discussion_topics(self, **kwargs): """ - Join, or request to join, a group, depending on the join_level of the group. - If the membership or join request already exists, then it is simply returned. + Returns the paginated list of discussion topics for this course or group. - :calls: `POST /api/v1/groups/:group_id/memberships \ - `_ + :calls: `GET /api/v1/groups/:group_id/discussion_topics \ + `_ - :param user: The object or ID of the user. - :type user: :class:`canvasapi.user.User` or int + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.discussion_topic.DiscussionTopic` + """ - :rtype: :class:`canvasapi.group.GroupMembership` + return PaginatedList( + DiscussionTopic, + self._requester, + "GET", + "groups/{}/discussion_topics".format(self.id), + {"group_id": self.id}, + _kwargs=combine_kwargs(**kwargs), + ) + + def get_external_feeds(self, **kwargs): """ - from canvasapi.user import User + Returns the list of External Feeds this group. - user_id = obj_or_id(user, "user", (User,)) + :calls: `GET /api/v1/groups/:group_id/external_feeds \ + `_ - response = self._requester.request( - "POST", - "groups/{}/memberships".format(self.id), - user_id=user_id, - _kwargs=combine_kwargs(**kwargs), + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.external_feed.ExternalFeed` + """ + from canvasapi.external_feed import ExternalFeed + + return PaginatedList( + ExternalFeed, + self._requester, + "GET", + "groups/{}/external_feeds".format(self.id), ) - return GroupMembership(self._requester, response.json()) - def update_membership(self, user, **kwargs): + def get_file(self, file, **kwargs): """ - Accept a membership request, or add/remove moderator rights. + Return the standard attachment json object for a file. - :calls: `PUT /api/v1/groups/:group_id/users/:user_id \ - `_ + :calls: `GET /api/v1/groups/:group_id/files/:id \ + `_ - :param user: The object or ID of the user. - :type user: :class:`canvasapi.user.User` or int + :param file: The object or ID of the file to retrieve. + :type file: :class:`canvasapi.file.File` or int - :rtype: :class:`canvasapi.group.GroupMembership` + :rtype: :class:`canvasapi.file.File` """ - from canvasapi.user import User + from canvasapi.file import File - user_id = obj_or_id(user, "user", (User,)) + file_id = obj_or_id(file, "file", (File,)) response = self._requester.request( - "PUT", - "groups/{}/users/{}".format(self.id, user_id), + "GET", + "groups/{}/files/{}".format(self.id, file_id), + _kwargs=combine_kwargs(**kwargs), + ) + return File(self._requester, response.json()) + + def get_files(self, **kwargs): + """ + Returns the paginated list of files for the group. + + :calls: `GET /api/v1/groups/:group_id/files \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.file.File` + """ + from canvasapi.file import File + + return PaginatedList( + File, + self._requester, + "GET", + "groups/{}/files".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return GroupMembership(self._requester, response.json()) - def get_discussion_topic(self, topic): + def get_folder(self, folder): """ - Return data on an individual discussion topic. + Returns the details for a group's folder - :calls: `GET /api/v1/groups/:group_id/discussion_topics/:topic_id \ - `_ + :calls: `GET /api/v1/groups/:group_id/folders/:id \ + `_ - :param topic: The object or ID of the discussion topic. - :type topic: :class:`canvasapi.discussion_topic.DiscussionTopic` or int + :param folder: The object or ID of the folder to retrieve. + :type folder: :class:`canvasapi.folder.Folder` or int - :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` + :rtype: :class:`canvasapi.folder.Folder` """ - topic_id = obj_or_id(topic, "topic", (DiscussionTopic,)) + folder_id = obj_or_id(folder, "folder", (Folder,)) response = self._requester.request( - "GET", "groups/{}/discussion_topics/{}".format(self.id, topic_id) + "GET", "groups/{}/folders/{}".format(self.id, folder_id) ) + return Folder(self._requester, response.json()) - response_json = response.json() - response_json.update({"group_id": self.id}) - - return DiscussionTopic(self._requester, response_json) - - def get_file(self, file, **kwargs): + def get_folders(self, **kwargs): """ - Return the standard attachment json object for a file. - - :calls: `GET /api/v1/groups/:group_id/files/:id \ - `_ + Returns the paginated list of all folders for the given group. This will be returned as a + flat list containing all subfolders as well. - :param file: The object or ID of the file to retrieve. - :type file: :class:`canvasapi.file.File` or int + :calls: `GET /api/v1/groups/:group_id/folders \ + `_ - :rtype: :class:`canvasapi.file.File` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.folder.Folder` """ - from canvasapi.file import File - - file_id = obj_or_id(file, "file", (File,)) - - response = self._requester.request( - "GET", - "groups/{}/files/{}".format(self.id, file_id), - _kwargs=combine_kwargs(**kwargs), + return PaginatedList( + Folder, self._requester, "GET", "groups/{}/folders".format(self.id) ) - return File(self._requester, response.json()) def get_full_discussion_topic(self, topic): """ @@ -469,157 +544,193 @@ def get_full_discussion_topic(self, topic): ) return response.json() - def get_discussion_topics(self, **kwargs): + def get_membership(self, user, membership_type): """ - Returns the paginated list of discussion topics for this course or group. + List users in a group. - :calls: `GET /api/v1/groups/:group_id/discussion_topics \ - `_ + :calls: `GET /api/v1/groups/:group_id/users/:user_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.discussion_topic.DiscussionTopic` + or `GET /api/v1/groups/:group_id/memberships/:membership_id + `_ + + :param user: list of user ids + :type user: :class:`canvasapi.user.User` or int + + :rtype: :class:`canvasapi.group.GroupMembership` + """ + from canvasapi.user import User + + user_id = obj_or_id(user, "user", (User,)) + + response = self._requester.request( + "GET", "groups/{}/{}/{}".format(self.id, membership_type, user_id) + ) + return GroupMembership(self._requester, response.json()) + + def get_memberships(self, **kwargs): """ + List users in a group. + + :calls: `GET /api/v1/groups/:group_id/memberships \ + `_ + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.group.GroupMembership` + """ return PaginatedList( - DiscussionTopic, + GroupMembership, self._requester, "GET", - "groups/{}/discussion_topics".format(self.id), - {"group_id": self.id}, + "groups/{}/memberships".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def create_discussion_topic(self, **kwargs): + def get_migration_systems(self, **kwargs): """ - Creates a new discussion topic for the course or group. + Return a list of migration systems. - :calls: `POST /api/v1/groups/:group_id/discussion_topics \ - `_ + :calls: `GET /api/v1/groups/:group_id/content_migrations/migrators \ + `_ - :rtype: :class:`canvasapi.discussion_topic.DiscussionTopic` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.content_migration.Migrator` """ - response = self._requester.request( - "POST", - "groups/{}/discussion_topics".format(self.id), + from canvasapi.content_migration import Migrator + + return PaginatedList( + Migrator, + self._requester, + "GET", + "groups/{}/content_migrations/migrators".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({"group_id": self.id}) - - return DiscussionTopic(self._requester, response_json) - - def reorder_pinned_topics(self, order): + def get_page(self, url): """ - Puts the pinned discussion topics in the specified order. - All pinned topics should be included. - - :calls: `POST /api/v1/groups/:group_id/discussion_topics/reorder \ - `_ + Retrieve the contents of a wiki page. - :param order: The ids of the pinned discussion topics in the desired order. - e.g. [104, 102, 103] - :type order: iterable sequence of values + :calls: `GET /api/v1/groups/:group_id/pages/:url \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.discussion_topic.DiscussionTopic` + :param url: The url for the page. + :type url: str + :returns: The specified page. + :rtype: :class:`canvasapi.groups.Group` """ - # Convert list or tuple to comma-separated string - if is_multivalued(order): - order = ",".join([text_type(topic_id) for topic_id in order]) - - # Check if is a string with commas - if not isinstance(order, text_type) or "," not in order: - raise ValueError("Param `order` must be a list, tuple, or string.") + from canvasapi.course import Page response = self._requester.request( - "POST", "groups/{}/discussion_topics/reorder".format(self.id), order=order + "GET", "groups/{}/pages/{}".format(self.id, url) ) + page_json = response.json() + page_json.update({"group_id": self.id}) - return response.json().get("reorder") + return Page(self._requester, page_json) - def list_external_feeds(self, **kwargs): + def get_pages(self, **kwargs): """ - Returns the list of External Feeds this group. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.group.Group.get_external_feeds` instead. + List the wiki pages associated with a group. - :calls: `GET /api/v1/groups/:group_id/external_feeds \ - `_ + :calls: `GET /api/v1/groups/:group_id/pages \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.external_feed.ExternalFeed` + :class:`canvasapi.page.Page` """ - warnings.warn( - "`list_external_feeds` is being deprecated and will be removed in " - "a future version. Use `get_external_feeds` instead", - DeprecationWarning, - ) + from canvasapi.course import Page - return self.get_external_feeds(**kwargs) + return PaginatedList( + Page, + self._requester, + "GET", + "groups/{}/pages".format(self.id), + {"group_id": self.id}, + _kwargs=combine_kwargs(**kwargs), + ) - def get_external_feeds(self, **kwargs): + def get_tabs(self, **kwargs): """ - Returns the list of External Feeds this group. + List available tabs for a group. + Returns a list of navigation tabs available in the current context. - :calls: `GET /api/v1/groups/:group_id/external_feeds \ - `_ + :calls: `GET /api/v1/groups/:group_id/tabs \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.external_feed.ExternalFeed` + :class:`canvasapi.tab.Tab` """ - from canvasapi.external_feed import ExternalFeed - return PaginatedList( - ExternalFeed, + Tab, self._requester, "GET", - "groups/{}/external_feeds".format(self.id), + "groups/{}/tabs".format(self.id), + {"group_id": self.id}, + _kwargs=combine_kwargs(**kwargs), ) - def create_external_feed(self, url, **kwargs): + def get_users(self, **kwargs): """ - Create a new external feed for the group. + List users in a group. - :calls: `POST /api/v1/groups/:group_id/external_feeds \ - `_ + :calls: `GET /api/v1/groups/:group_id/users \ + `_ - :param url: The urlof the external rss or atom feed - :type url: str - :rtype: :class:`canvasapi.external_feed.ExternalFeed` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.user.User` """ - from canvasapi.external_feed import ExternalFeed + from canvasapi.user import User - response = self._requester.request( - "POST", - "groups/{}/external_feeds".format(self.id), - url=url, + return PaginatedList( + User, + self._requester, + "GET", + "groups/{}/users".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return ExternalFeed(self._requester, response.json()) - def delete_external_feed(self, feed): + def invite(self, invitees): """ - Deletes the external feed. + Invite users to group. - :calls: `DELETE /api/v1/groups/:group_id/external_feeds/:external_feed_id \ - `_ + :calls: `POST /api/v1/groups/:group_id/invite \ + `_ - :param feed: The object or id of the feed to be deleted. - :type feed: :class:`canvasapi.external_feed.ExternalFeed` or int + :param invitees: list of user ids + :type invitees: integer list - :rtype: :class:`canvasapi.external_feed.ExternalFeed` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.group.GroupMembership` """ - from canvasapi.external_feed import ExternalFeed + return PaginatedList( + GroupMembership, + self._requester, + "POST", + "groups/{}/invite".format(self.id), + invitees=invitees, + ) + + def list_external_feeds(self, **kwargs): + """ + Returns the list of External Feeds this group. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.group.Group.get_external_feeds` instead. - feed_id = obj_or_id(feed, "feed", (ExternalFeed,)) + :calls: `GET /api/v1/groups/:group_id/external_feeds \ + `_ - response = self._requester.request( - "DELETE", "groups/{}/external_feeds/{}".format(self.id, feed_id) + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.external_feed.ExternalFeed` + """ + warnings.warn( + "`list_external_feeds` is being deprecated and will be removed in " + "a future version. Use `get_external_feeds` instead", + DeprecationWarning, ) - return ExternalFeed(self._requester, response.json()) + + return self.get_external_feeds(**kwargs) def list_files(self, **kwargs): """ @@ -643,45 +754,6 @@ def list_files(self, **kwargs): return self.get_files(**kwargs) - def get_files(self, **kwargs): - """ - Returns the paginated list of files for the group. - - :calls: `GET /api/v1/groups/:group_id/files \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` - """ - from canvasapi.file import File - - return PaginatedList( - File, - self._requester, - "GET", - "groups/{}/files".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - - def get_folder(self, folder): - """ - Returns the details for a group's folder - - :calls: `GET /api/v1/groups/:group_id/folders/:id \ - `_ - - :param folder: The object or ID of the folder to retrieve. - :type folder: :class:`canvasapi.folder.Folder` or int - - :rtype: :class:`canvasapi.folder.Folder` - """ - folder_id = obj_or_id(folder, "folder", (Folder,)) - - response = self._requester.request( - "GET", "groups/{}/folders/{}".format(self.id, folder_id) - ) - return Folder(self._requester, response.json()) - def list_folders(self, **kwargs): """ Returns the paginated list of all folders for the given group. This will be returned as a @@ -705,39 +777,27 @@ def list_folders(self, **kwargs): return self.get_folders(**kwargs) - def get_folders(self, **kwargs): + def list_memberships(self, **kwargs): """ - Returns the paginated list of all folders for the given group. This will be returned as a - flat list containing all subfolders as well. + List users in a group. - :calls: `GET /api/v1/groups/:group_id/folders \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.group.Group.get_memberships` instead. + + :calls: `GET /api/v1/groups/:group_id/memberships \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.folder.Folder` + :class:`canvasapi.group.GroupMembership` """ - return PaginatedList( - Folder, self._requester, "GET", "groups/{}/folders".format(self.id) + warnings.warn( + "`list_memberships` is being deprecated and will be removed in a " + "future version. Use `get_memberships` instead.", + DeprecationWarning, ) - def create_folder(self, name, **kwargs): - """ - Creates a folder in this group. - - :calls: `POST /api/v1/groups/:group_id/folders \ - `_ - - :param name: The name of the folder. - :type name: str - :rtype: :class:`canvasapi.folder.Folder` - """ - response = self._requester.request( - "POST", - "groups/{}/folders".format(self.id), - name=name, - _kwargs=combine_kwargs(**kwargs), - ) - return Folder(self._requester, response.json()) + return self.get_memberships(**kwargs) def list_tabs(self, **kwargs): """ @@ -762,218 +822,158 @@ def list_tabs(self, **kwargs): return self.get_tabs(**kwargs) - def get_tabs(self, **kwargs): + def list_users(self, **kwargs): """ - List available tabs for a group. - Returns a list of navigation tabs available in the current context. + List users in a group. - :calls: `GET /api/v1/groups/:group_id/tabs \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.group.Group.get_users` instead. + + :calls: `GET /api/v1/groups/:group_id/users \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.tab.Tab` + :class:`canvasapi.user.User` """ - return PaginatedList( - Tab, - self._requester, - "GET", - "groups/{}/tabs".format(self.id), - {"group_id": self.id}, - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_users` is being deprecated and will be removed in a future " + "version. Use `get_users` instead", + DeprecationWarning, ) - def create_content_migration(self, migration_type, **kwargs): - """ - Create a content migration. - - :calls: `POST /api/v1/groups/:group_id/content_migrations \ - `_ - - :param migration_type: The migrator type to use in this migration - :type migration_type: str or :class:`canvasapi.content_migration.Migrator` + return self.get_users(**kwargs) - :rtype: :class:`canvasapi.content_migration.ContentMigration` + def preview_html(self, html): """ - from canvasapi.content_migration import ContentMigration, Migrator + Preview HTML content processed for this course. - if isinstance(migration_type, Migrator): - kwargs["migration_type"] = migration_type.type - elif isinstance(migration_type, string_types): - kwargs["migration_type"] = migration_type - else: - raise TypeError("Parameter migration_type must be of type Migrator or str") + :calls: `POST /api/v1/groups/:group_id/preview_html \ + `_ + :param html: The HTML code to preview. + :type html: str + :rtype: str + """ response = self._requester.request( - "POST", - "groups/{}/content_migrations".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "POST", "groups/{}/preview_html".format(self.id), html=html ) + return response.json().get("html", "") - response_json = response.json() - response_json.update({"group_id": self.id}) - - return ContentMigration(self._requester, response_json) - - def get_content_migration(self, content_migration, **kwargs): + def remove_user(self, user): """ - Retrive a content migration by its ID + Leave a group if allowed. - :calls: `GET /api/v1/groups/:group_id/content_migrations/:id \ - `_ + :calls: `DELETE /api/v1/groups/:group_id/users/:user_id \ + `_ - :param content_migration: The object or ID of the content migration to retrieve. - :type content_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + :param user: The user object or ID to remove from the group. + :type user: :class:`canvasapi.user.User` or int - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :rtype: :class:`canvasapi.user.User` """ - from canvasapi.content_migration import ContentMigration + from canvasapi.user import User - migration_id = obj_or_id( - content_migration, "content_migration", (ContentMigration,) - ) + user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - "GET", - "groups/{}/content_migrations/{}".format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs), + "DELETE", "groups/{}/users/{}".format(self.id, user_id) ) + return User(self._requester, response.json()) - response_json = response.json() - response_json.update({"group_id": self.id}) - - return ContentMigration(self._requester, response_json) - - def get_content_migrations(self, **kwargs): - """ - List content migrations that the current account can view or manage. - - :calls: `GET /api/v1/groups/:group_id/content_migrations/ \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.ContentMigration` + def reorder_pinned_topics(self, order): """ - from canvasapi.content_migration import ContentMigration - - return PaginatedList( - ContentMigration, - self._requester, - "GET", - "groups/{}/content_migrations".format(self.id), - {"group_id": self.id}, - _kwargs=combine_kwargs(**kwargs), - ) + Puts the pinned discussion topics in the specified order. + All pinned topics should be included. - def get_migration_systems(self, **kwargs): - """ - Return a list of migration systems. + :calls: `POST /api/v1/groups/:group_id/discussion_topics/reorder \ + `_ - :calls: `GET /api/v1/groups/:group_id/content_migrations/migrators \ - `_ + :param order: The ids of the pinned discussion topics in the desired order. + e.g. [104, 102, 103] + :type order: iterable sequence of values :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.Migrator` - """ - from canvasapi.content_migration import Migrator - - return PaginatedList( - Migrator, - self._requester, - "GET", - "groups/{}/content_migrations/migrators".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - - def get_assignment_override(self, assignment, **kwargs): - """ - Return override for the specified assignment for this group. - - :param assignment: The assignment to get an override for - :type assignment: :class:`canvasapi.assignment.Assignment` or int - - :calls: `GET /api/v1/groups/:group_id/assignments/:assignment_id/override \ - `_ - - :rtype: :class:`canvasapi.assignment.AssignmentOverride` + :class:`canvasapi.discussion_topic.DiscussionTopic` """ - from canvasapi.assignment import Assignment, AssignmentOverride + # Convert list or tuple to comma-separated string + if is_multivalued(order): + order = ",".join([text_type(topic_id) for topic_id in order]) - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + # Check if is a string with commas + if not isinstance(order, text_type) or "," not in order: + raise ValueError("Param `order` must be a list, tuple, or string.") response = self._requester.request( - "GET", "groups/{}/assignments/{}/override".format(self.id, assignment_id) + "POST", "groups/{}/discussion_topics/reorder".format(self.id), order=order ) - response_json = response.json() - response_json.update({"course_id": self.course_id}) - return AssignmentOverride(self._requester, response_json) + return response.json().get("reorder") - def get_content_exports(self, **kwargs): + def show_front_page(self): """ - Return a paginated list of the past and pending content export jobs for a group. + Retrieve the content of the front page. - :calls: `GET /api/v1/groups/:group_id/content_exports\ - `_ + :calls: `GET /api/v1/groups/:group_id/front_page \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_export.ContentExport` + :rtype: :class:`canvasapi.group.Group` """ - from canvasapi.content_export import ContentExport + from canvasapi.course import Page - return PaginatedList( - ContentExport, - self._requester, - "GET", - "groups/{}/content_exports".format(self.id), - kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "GET", "groups/{}/front_page".format(self.id) ) + page_json = response.json() + page_json.update({"group_id": self.id}) - def get_content_export(self, content_export, **kwargs): + return Page(self._requester, page_json) + + def update_membership(self, user, **kwargs): """ - Return information about a single content export. + Accept a membership request, or add/remove moderator rights. - :calls: `GET /api/v1/groups/:group_id/content_exports/:id\ - `_ + :calls: `PUT /api/v1/groups/:group_id/users/:user_id \ + `_ - :param content_export: The object or ID of the content export to show. - :type content_export: int or :class:`canvasapi.content_export.ContentExport` + :param user: The object or ID of the user. + :type user: :class:`canvasapi.user.User` or int - :rtype: :class:`canvasapi.content_export.ContentExport` + :rtype: :class:`canvasapi.group.GroupMembership` """ - from canvasapi.content_export import ContentExport + from canvasapi.user import User - export_id = obj_or_id(content_export, "content_export", (ContentExport,)) + user_id = obj_or_id(user, "user", (User,)) response = self._requester.request( - "GET", - "groups/{}/content_exports/{}".format(self.id, export_id), + "PUT", + "groups/{}/users/{}".format(self.id, user_id), _kwargs=combine_kwargs(**kwargs), ) + return GroupMembership(self._requester, response.json()) - return ContentExport(self._requester, response.json()) - - def export_content(self, export_type, **kwargs): + def upload(self, file, **kwargs): """ - Begin a content export job for a group. - - :calls: `POST /api/v1/groups/:group_id/content_exports\ - `_ + Upload a file to the group. + Only those with the 'Manage Files' permission on a group can upload files to the group. + By default, this is anybody participating in the group, or any admin over the group. - :param export_type: The type of content to export. - :type export_type: str + :calls: `POST /api/v1/groups/:group_id/files \ + `_ - :rtype: :class:`canvasapi.content_export.ContentExport` + :param path: The path of the file to upload. + :type path: str + :param file: The file or path of the file to upload. + :type file: file or str + :returns: True if the file uploaded successfully, False otherwise, \ + and the JSON response from the API. + :rtype: tuple """ - from canvasapi.content_export import ContentExport - - kwargs["export_type"] = export_type + from canvasapi.upload import Uploader - response = self._requester.request( - "POST", - "groups/{}/content_exports".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - return ContentExport(self._requester, response.json()) + return Uploader( + self._requester, "groups/{}/files".format(self.id), file, **kwargs + ).start() @python_2_unicode_compatible @@ -981,22 +981,20 @@ class GroupMembership(CanvasObject): def __str__(self): return "{} - {} ({})".format(self.user_id, self.group_id, self.id) - def update(self, **kwargs): + def remove_self(self): """ - Accept a membership request, or add/remove moderator rights. + Leave a group if allowed. - :calls: `PUT /api/v1/groups/:group_id/memberships/:membership_id \ - `_ + :calls: `DELETE /api/v1/groups/:group_id/memberships/:membership_id \ + `_ - :rtype: :class:`canvasapi.group.GroupMembership` + :returns: An empty dictionary + :rtype: dict """ - response = self._requester.request( - "PUT", - "groups/{}/memberships/{}".format(self.group_id, self.id), - _kwargs=combine_kwargs(**kwargs), + "DELETE", "groups/{}/memberships/self".format(self.id) ) - return GroupMembership(self._requester, response.json()) + return response.json() def remove_user(self, user): """ @@ -1020,20 +1018,22 @@ def remove_user(self, user): ) return response.json() - def remove_self(self): + def update(self, **kwargs): """ - Leave a group if allowed. + Accept a membership request, or add/remove moderator rights. - :calls: `DELETE /api/v1/groups/:group_id/memberships/:membership_id \ - `_ + :calls: `PUT /api/v1/groups/:group_id/memberships/:membership_id \ + `_ - :returns: An empty dictionary - :rtype: dict + :rtype: :class:`canvasapi.group.GroupMembership` """ + response = self._requester.request( - "DELETE", "groups/{}/memberships/self".format(self.id) + "PUT", + "groups/{}/memberships/{}".format(self.group_id, self.id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() + return GroupMembership(self._requester, response.json()) @python_2_unicode_compatible @@ -1041,6 +1041,32 @@ class GroupCategory(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) + def assign_members(self, sync=False): + """ + Assign unassigned members. + + :calls: `POST /api/v1/group_categories/:group_category_id/assign_unassigned_members \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` + or :class:`canvasapi.progress.Progress` + """ + from canvasapi.user import User + from canvasapi.progress import Progress + + if sync: + return PaginatedList( + User, + self._requester, + "POST", + "group_categories/{}/assign_unassigned_members".format(self.id), + ) + else: + response = self._requester.request( + "POST", "group_categories/{}/assign_unassigned_members".format(self.id) + ) + return Progress(self._requester, response.json()) + def create_group(self, **kwargs): """ Create a group. @@ -1057,22 +1083,6 @@ def create_group(self, **kwargs): ) return Group(self._requester, response.json()) - def update(self, **kwargs): - """ - Update a group category. - - :calls: `PUT /api/v1/group_categories/:group_category_id \ - `_ - - :rtype: :class:`canvasapi.group.GroupCategory` - """ - response = self._requester.request( - "PUT", - "group_categories/{}".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - return GroupCategory(self._requester, response.json()) - def delete(self): """ Delete a group category. @@ -1087,42 +1097,62 @@ def delete(self): ) return response.json() - def list_groups(self, **kwargs): + def get_groups(self, **kwargs): """ List groups in group category. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.group.GroupCategory.get_groups` instead. - :calls: `GET /api/v1/group_categories/:group_category_id/groups \ `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` """ - warnings.warn( - "`list_groups` is being deprecated and will be removed in a " - "future version. Use `get_groups` instead.", - DeprecationWarning, + return PaginatedList( + Group, self._requester, "GET", "group_categories/{}/groups".format(self.id) ) - return self.get_groups(**kwargs) + def get_users(self, **kwargs): + """ + List users in group category. - def get_groups(self, **kwargs): + :calls: `GET /api/v1/group_categories/:group_category_id/users \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.user.User` + """ + from canvasapi.user import User + + return PaginatedList( + User, + self._requester, + "GET", + "group_categories/{}/users".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + def list_groups(self, **kwargs): """ List groups in group category. + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.group.GroupCategory.get_groups` instead. + :calls: `GET /api/v1/group_categories/:group_category_id/groups \ `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.group.Group` """ - return PaginatedList( - Group, self._requester, "GET", "group_categories/{}/groups".format(self.id) + warnings.warn( + "`list_groups` is being deprecated and will be removed in a " + "future version. Use `get_groups` instead.", + DeprecationWarning, ) + return self.get_groups(**kwargs) + def list_users(self, **kwargs): """ List users in group category. @@ -1145,48 +1175,18 @@ def list_users(self, **kwargs): return self.get_users(**kwargs) - def get_users(self, **kwargs): + def update(self, **kwargs): """ - List users in group category. + Update a group category. - :calls: `GET /api/v1/group_categories/:group_category_id/users \ - `_ + :calls: `PUT /api/v1/group_categories/:group_category_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :rtype: :class:`canvasapi.group.GroupCategory` """ - from canvasapi.user import User - - return PaginatedList( - User, - self._requester, - "GET", - "group_categories/{}/users".format(self.id), + response = self._requester.request( + "PUT", + "group_categories/{}".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - - def assign_members(self, sync=False): - """ - Assign unassigned members. - - :calls: `POST /api/v1/group_categories/:group_category_id/assign_unassigned_members \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.user.User` - or :class:`canvasapi.progress.Progress` - """ - from canvasapi.user import User - from canvasapi.progress import Progress - - if sync: - return PaginatedList( - User, - self._requester, - "POST", - "group_categories/{}/assign_unassigned_members".format(self.id), - ) - else: - response = self._requester.request( - "POST", "group_categories/{}/assign_unassigned_members".format(self.id) - ) - return Progress(self._requester, response.json()) + return GroupCategory(self._requester, response.json()) diff --git a/canvasapi/page.py b/canvasapi/page.py index 3e523589..342fbbcc 100644 --- a/canvasapi/page.py +++ b/canvasapi/page.py @@ -13,6 +13,20 @@ class Page(CanvasObject): def __str__(self): return "{} ({})".format(self.title, self.url) + def delete(self): + """ + Delete this page. + + :calls: `DELETE /api/v1/courses/:course_id/pages/:url \ + `_ + + :rtype: :class:`canvasapi.page.Page` + """ + response = self._requester.request( + "DELETE", "courses/{}/pages/{}".format(self.course_id, self.url) + ) + return Page(self._requester, response.json()) + def edit(self, **kwargs): """ Update the title or the contents of a specified wiki @@ -35,48 +49,6 @@ def edit(self, **kwargs): return self - def delete(self): - """ - Delete this page. - - :calls: `DELETE /api/v1/courses/:course_id/pages/:url \ - `_ - - :rtype: :class:`canvasapi.page.Page` - """ - response = self._requester.request( - "DELETE", "courses/{}/pages/{}".format(self.course_id, self.url) - ) - return Page(self._requester, response.json()) - - @property - def parent_id(self): - """ - Return the id of the course or group that spawned this page. - - :rtype: int - """ - if hasattr(self, "course_id"): - return self.course_id - elif hasattr(self, "group_id"): - return self.group_id - else: - raise ValueError("Page does not have a course_id or group_id") - - @property - def parent_type(self): - """ - Return whether the page was spawned from a course or group. - - :rtype: str - """ - if hasattr(self, "course_id"): - return "course" - elif hasattr(self, "group_id"): - return "group" - else: - raise ValueError("ExternalTool does not have a course_id or group_id") - def get_parent(self): """ Return the object that spawned this page. @@ -100,24 +72,6 @@ def get_parent(self): elif self.parent_type == "course": return Course(self._requester, response.json()) - def show_latest_revision(self, **kwargs): - """ - Retrieve the contents of the latest revision. - - :calls: `GET /api/v1/courses/:course_id/pages/:url/revisions/latest \ - `_ - - :rtype: :class:`canvasapi.pagerevision.PageRevision` - """ - response = self._requester.request( - "GET", - "{}s/{}/pages/{}/revisions/latest".format( - self.parent_type, self.parent_id, self.url - ), - _kwargs=combine_kwargs(**kwargs), - ) - return PageRevision(self._requester, response.json()) - def get_revision_by_id(self, revision, **kwargs): """ Retrieve the contents of the revision by the id. @@ -148,6 +102,26 @@ def get_revision_by_id(self, revision, **kwargs): return PageRevision(self._requester, pagerev_json) + def get_revisions(self, **kwargs): + """ + List the revisions of a page. + + :calls: `GET /api/v1/courses/:course_id/pages/:url/revisions \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.pagerevision.PageRevision` + """ + return PaginatedList( + PageRevision, + self._requester, + "GET", + "{}s/{}/pages/{}/revisions".format( + self.parent_type, self.parent_id, self.url + ), + _kwargs=combine_kwargs(**kwargs), + ) + def list_revisions(self, **kwargs): """ List the revisions of a page. @@ -170,25 +144,33 @@ def list_revisions(self, **kwargs): return self.get_revisions(**kwargs) - def get_revisions(self, **kwargs): + @property + def parent_id(self): """ - List the revisions of a page. + Return the id of the course or group that spawned this page. - :calls: `GET /api/v1/courses/:course_id/pages/:url/revisions \ - `_ + :rtype: int + """ + if hasattr(self, "course_id"): + return self.course_id + elif hasattr(self, "group_id"): + return self.group_id + else: + raise ValueError("Page does not have a course_id or group_id") - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.pagerevision.PageRevision` + @property + def parent_type(self): """ - return PaginatedList( - PageRevision, - self._requester, - "GET", - "{}s/{}/pages/{}/revisions".format( - self.parent_type, self.parent_id, self.url - ), - _kwargs=combine_kwargs(**kwargs), - ) + Return whether the page was spawned from a course or group. + + :rtype: str + """ + if hasattr(self, "course_id"): + return "course" + elif hasattr(self, "group_id"): + return "group" + else: + raise ValueError("ExternalTool does not have a course_id or group_id") def revert_to_revision(self, revision): """ @@ -218,12 +200,53 @@ def revert_to_revision(self, revision): return PageRevision(self._requester, pagerev_json) + def show_latest_revision(self, **kwargs): + """ + Retrieve the contents of the latest revision. + + :calls: `GET /api/v1/courses/:course_id/pages/:url/revisions/latest \ + `_ + + :rtype: :class:`canvasapi.pagerevision.PageRevision` + """ + response = self._requester.request( + "GET", + "{}s/{}/pages/{}/revisions/latest".format( + self.parent_type, self.parent_id, self.url + ), + _kwargs=combine_kwargs(**kwargs), + ) + return PageRevision(self._requester, response.json()) + @python_2_unicode_compatible class PageRevision(CanvasObject): def __str__(self): return "{} ({})".format(self.updated_at, self.revision_id) + def get_parent(self): + """ + Return the object that spawned this page. + + :calls: `GET /api/v1/groups/:group_id \ + `_ + or :calls: `GET /api/v1/courses/:id \ + `_ + + :rtype: :class:`canvasapi.group.Group` or :class:`canvasapi.course.Course` + """ + from canvasapi.group import Group + from canvasapi.course import Course + + response = self._requester.request( + "GET", "{}s/{}".format(self.parent_type, self.parent_id) + ) + + if self.parent_type == "group": + return Group(self._requester, response.json()) + elif self.parent_type == "course": + return Course(self._requester, response.json()) + @property def parent_id(self): """ @@ -251,26 +274,3 @@ def parent_type(self): return "group" else: raise ValueError("ExternalTool does not have a course_id or group_id") - - def get_parent(self): - """ - Return the object that spawned this page. - - :calls: `GET /api/v1/groups/:group_id \ - `_ - or :calls: `GET /api/v1/courses/:id \ - `_ - - :rtype: :class:`canvasapi.group.Group` or :class:`canvasapi.course.Course` - """ - from canvasapi.group import Group - from canvasapi.course import Course - - response = self._requester.request( - "GET", "{}s/{}".format(self.parent_type, self.parent_id) - ) - - if self.parent_type == "group": - return Group(self._requester, response.json()) - elif self.parent_type == "course": - return Course(self._requester, response.json()) diff --git a/canvasapi/paginated_list.py b/canvasapi/paginated_list.py index 1b4c9391..21cceaab 100644 --- a/canvasapi/paginated_list.py +++ b/canvasapi/paginated_list.py @@ -8,6 +8,14 @@ class PaginatedList(object): `_. """ + def __getitem__(self, index): + assert isinstance(index, (int, slice)) + if isinstance(index, int): + self._get_up_to_index(index) + return self._elements[index] + else: + return self._Slice(self, index) + def __init__( self, content_class, @@ -32,14 +40,6 @@ def __init__( self._request_method = request_method self._root = _root - def __getitem__(self, index): - assert isinstance(index, (int, slice)) - if isinstance(index, int): - self._get_up_to_index(index) - return self._elements[index] - else: - return self._Slice(self, index) - def __iter__(self): for element in self._elements: yield element @@ -51,21 +51,6 @@ def __iter__(self): def __repr__(self): return "".format(self._content_class.__name__) - def _is_larger_than(self, index): - return len(self._elements) > index or self._has_next() - - def _get_up_to_index(self, index): - while len(self._elements) <= index and self._has_next(): - self._grow() - - def _grow(self): - new_elements = self._get_next_page() - self._elements += new_elements - return new_elements - - def _has_next(self): - return self._next_url is not None - def _get_next_page(self): response = self._requester.request( self._request_method, self._next_url, **self._next_params @@ -98,6 +83,21 @@ def _get_next_page(self): return content + def _get_up_to_index(self, index): + while len(self._elements) <= index and self._has_next(): + self._grow() + + def _grow(self): + new_elements = self._get_next_page() + self._elements += new_elements + return new_elements + + def _has_next(self): + return self._next_url is not None + + def _is_larger_than(self, index): + return len(self._elements) > index or self._has_next() + class _Slice(object): def __init__(self, the_list, the_slice): self._list = the_list diff --git a/canvasapi/quiz.py b/canvasapi/quiz.py index cbd9768c..3326286a 100644 --- a/canvasapi/quiz.py +++ b/canvasapi/quiz.py @@ -16,68 +16,25 @@ class Quiz(CanvasObject): def __str__(self): return "{} ({})".format(self.title, self.id) - def edit(self, **kwargs): - """ - Modify this quiz. - - :calls: `PUT /api/v1/courses/:course_id/quizzes/:id \ - `_ - - :returns: The updated quiz. - :rtype: :class:`canvasapi.quiz.Quiz` - """ - response = self._requester.request( - "PUT", - "courses/{}/quizzes/{}".format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs), - ) - quiz_json = response.json() - quiz_json.update({"course_id": self.course_id}) - - return Quiz(self._requester, quiz_json) - - def delete(self, **kwargs): - """ - Delete this quiz. - - :calls: `DELETE /api/v1/courses/:course_id/quizzes/:id \ - `_ - - :rtype: :class:`canvasapi.quiz.Quiz` + def create_question(self, **kwargs): """ - response = self._requester.request( - "DELETE", - "courses/{}/quizzes/{}".format(self.course_id, self.id), - _kwargs=combine_kwargs(**kwargs), - ) - quiz_json = response.json() - quiz_json.update({"course_id": self.course_id}) + Create a new quiz question for this quiz. - return Quiz(self._requester, quiz_json) + :calls: `POST /api/v1/courses/:course_id/quizzes/:quiz_id/questions \ + `_ - def get_quiz_group(self, id, **kwargs): + :rtype: :class:`canvasapi.quiz.QuizQuestion` """ - Get details of the quiz group with the given id - :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \ - `_ - - :param id: The ID of the question group. - :type id: int - - :returns: `QuizGroup` object - :rtype: :class:`canvasapi.quiz_group.QuizGroup` - """ response = self._requester.request( - "GET", - "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.id, id), + "POST", + "courses/{}/quizzes/{}/questions".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({"course_id": self.id}) + response_json.update({"course_id": self.course_id}) - return QuizGroup(self._requester, response_json) + return QuizQuestion(self._requester, response_json) def create_question_group(self, quiz_groups, **kwargs): """ @@ -125,25 +82,86 @@ def create_question_group(self, quiz_groups, **kwargs): return QuizGroup(self._requester, response_json.get("quiz_groups")[0]) - def create_question(self, **kwargs): + def create_submission(self, **kwargs): """ - Create a new quiz question for this quiz. + Start taking a Quiz by creating a QuizSubmission can be used to answer + questions and submit answers. - :calls: `POST /api/v1/courses/:course_id/quizzes/:quiz_id/questions \ - `_ + :calls: `POST /api/v1/courses/:course_id/quizzes/:quiz_id/submissions \ + `_ - :rtype: :class:`canvasapi.quiz.QuizQuestion` + :rtype: :class:`canvasapi.quiz.QuizSubmission` """ - response = self._requester.request( "POST", - "courses/{}/quizzes/{}/questions".format(self.course_id, self.id), + "courses/{}/quizzes/{}/submissions".format(self.course_id, self.id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() + + response_json = response.json()["quiz_submissions"][0] response_json.update({"course_id": self.course_id}) - return QuizQuestion(self._requester, response_json) + return QuizSubmission(self._requester, response_json) + + def delete(self, **kwargs): + """ + Delete this quiz. + + :calls: `DELETE /api/v1/courses/:course_id/quizzes/:id \ + `_ + + :rtype: :class:`canvasapi.quiz.Quiz` + """ + response = self._requester.request( + "DELETE", + "courses/{}/quizzes/{}".format(self.course_id, self.id), + _kwargs=combine_kwargs(**kwargs), + ) + quiz_json = response.json() + quiz_json.update({"course_id": self.course_id}) + + return Quiz(self._requester, quiz_json) + + def edit(self, **kwargs): + """ + Modify this quiz. + + :calls: `PUT /api/v1/courses/:course_id/quizzes/:id \ + `_ + + :returns: The updated quiz. + :rtype: :class:`canvasapi.quiz.Quiz` + """ + response = self._requester.request( + "PUT", + "courses/{}/quizzes/{}".format(self.course_id, self.id), + _kwargs=combine_kwargs(**kwargs), + ) + quiz_json = response.json() + quiz_json.update({"course_id": self.course_id}) + + return Quiz(self._requester, quiz_json) + + def get_all_quiz_submissions(self, **kwargs): + """ + Get a list of all submissions for this quiz. + + .. warning:: + .. deprecated:: 0.13.0 + Use :func:`canvasapi.quiz.Quiz.get_submissions` instead. + + :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/submissions \ + `_ + + :rtype: list of :class:`canvasapi.quiz.QuizSubmission` + """ + warnings.warn( + "`get_all_quiz_submissions` is being deprecated and will be removed in a " + "future version. Use `get_submissions` instead", + DeprecationWarning, + ) + + return self.get_submissions(**kwargs) def get_question(self, question, **kwargs): """ @@ -190,6 +208,78 @@ def get_questions(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_quiz_group(self, id, **kwargs): + """ + Get details of the quiz group with the given id + + :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \ + `_ + + :param id: The ID of the question group. + :type id: int + + :returns: `QuizGroup` object + :rtype: :class:`canvasapi.quiz_group.QuizGroup` + """ + response = self._requester.request( + "GET", + "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.id, id), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({"course_id": self.id}) + + return QuizGroup(self._requester, response_json) + + def get_quiz_submission(self, quiz_submission, **kwargs): + """ + Get a single quiz submission. + + :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/submissions/:id \ + `_ + + :param quiz_submission: The object or ID of the quiz submission to retrieve. + :type quiz_submission: int, string, :class:`canvasapi.quiz.QuizSubmission` + + :rtype: :class:`canvasapi.quiz.QuizSubmission` + """ + quiz_submission_id = obj_or_id( + quiz_submission, "quiz_submission", (QuizSubmission,) + ) + + response = self._requester.request( + "GET", + "courses/{}/quizzes/{}/submissions/{}".format( + self.course_id, self.id, quiz_submission_id + ), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json()["quiz_submissions"][0] + response_json.update({"course_id": self.course_id}) + + return QuizSubmission(self._requester, response_json) + + def get_submissions(self, **kwargs): + """ + Get a list of all submissions for this quiz. + + :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/submissions \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.quiz.QuizSubmission` + """ + return PaginatedList( + QuizSubmission, + self._requester, + "GET", + "courses/{}/quizzes/{}/submissions".format(self.course_id, self.id), + _root="quiz_submissions", + _kwargs=combine_kwargs(**kwargs), + ) + def set_extensions(self, quiz_extensions, **kwargs): """ Set extensions for student quiz submissions. @@ -244,101 +334,56 @@ def set_extensions(self, quiz_extensions, **kwargs): QuizExtension(self._requester, extension) for extension in extension_list ] - def get_all_quiz_submissions(self, **kwargs): - """ - Get a list of all submissions for this quiz. - - .. warning:: - .. deprecated:: 0.13.0 - Use :func:`canvasapi.quiz.Quiz.get_submissions` instead. - - :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/submissions \ - `_ - :rtype: list of :class:`canvasapi.quiz.QuizSubmission` - """ - warnings.warn( - "`get_all_quiz_submissions` is being deprecated and will be removed in a " - "future version. Use `get_submissions` instead", - DeprecationWarning, - ) - - return self.get_submissions(**kwargs) - - def get_submissions(self, **kwargs): - """ - Get a list of all submissions for this quiz. - - :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/submissions \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.quiz.QuizSubmission` - """ - return PaginatedList( - QuizSubmission, - self._requester, - "GET", - "courses/{}/quizzes/{}/submissions".format(self.course_id, self.id), - _root="quiz_submissions", - _kwargs=combine_kwargs(**kwargs), - ) - - def get_quiz_submission(self, quiz_submission, **kwargs): - """ - Get a single quiz submission. - - :calls: `GET /api/v1/courses/:course_id/quizzes/:quiz_id/submissions/:id \ - `_ - - :param quiz_submission: The object or ID of the quiz submission to retrieve. - :type quiz_submission: int, string, :class:`canvasapi.quiz.QuizSubmission` +@python_2_unicode_compatible +class QuizSubmission(CanvasObject): + def __str__(self): + return "Quiz {} - User {} ({})".format(self.quiz_id, self.user_id, self.id) - :rtype: :class:`canvasapi.quiz.QuizSubmission` + def answer_submission_questions(self, validation_token=None, **kwargs): """ - quiz_submission_id = obj_or_id( - quiz_submission, "quiz_submission", (QuizSubmission,) - ) - - response = self._requester.request( - "GET", - "courses/{}/quizzes/{}/submissions/{}".format( - self.course_id, self.id, quiz_submission_id - ), - _kwargs=combine_kwargs(**kwargs), - ) - - response_json = response.json()["quiz_submissions"][0] - response_json.update({"course_id": self.course_id}) + Provide or update an answer to one or more quiz questions. - return QuizSubmission(self._requester, response_json) + :calls: `POST /api/v1/quiz_submissions/:quiz_submission_id/questions \ + `_ - def create_submission(self, **kwargs): + :param validation_token: (Optional) The unique validation token for this quiz submission. + If one is not provided, canvasapi will attempt to use `self.validation_token`. + :type validation_token: str + :returns: A list of quiz submission questions. + :rtype: list of :class:`canvasapi.quiz.QuizSubmissionQuestion` """ - Start taking a Quiz by creating a QuizSubmission can be used to answer - questions and submit answers. + try: + kwargs["validation_token"] = validation_token or self.validation_token + except AttributeError: + raise RequiredFieldMissing( + "`validation_token` not set on this QuizSubmission, must be passed" + " as a function argument." + ) - :calls: `POST /api/v1/courses/:course_id/quizzes/:quiz_id/submissions \ - `_ + # Only the latest attempt for a quiz submission can be updated, and Canvas + # automatically returns the latest attempt with every quiz submission response, + # so we can just use that. + kwargs["attempt"] = self.attempt - :rtype: :class:`canvasapi.quiz.QuizSubmission` - """ response = self._requester.request( "POST", - "courses/{}/quizzes/{}/submissions".format(self.course_id, self.id), + "quiz_submissions/{}/questions".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json()["quiz_submissions"][0] - response_json.update({"course_id": self.course_id}) - - return QuizSubmission(self._requester, response_json) - + questions = list() + for question in response.json().get("quiz_submission_questions", []): + question.update( + { + "quiz_submission_id": self.id, + "validation_token": kwargs["validation_token"], + "attempt": self.attempt, + } + ) + questions.append(QuizSubmissionQuestion(self._requester, question)) -@python_2_unicode_compatible -class QuizSubmission(CanvasObject): - def __str__(self): - return "Quiz {} - User {} ({})".format(self.quiz_id, self.user_id, self.id) + return questions def complete(self, validation_token=None, **kwargs): """ @@ -378,6 +423,29 @@ def complete(self, validation_token=None, **kwargs): response_json = response.json()["quiz_submissions"][0] return QuizSubmission(self._requester, response_json) + def get_submission_questions(self, **kwargs): + """ + Get a list of all the question records for this quiz submission. + + :calls: `GET /api/v1/quiz_submissions/:quiz_submission_id/questions \ + `_ + + :returns: A list of quiz submission questions. + :rtype: list of :class:`canvasapi.quiz.QuizSubmissionQuestion` + """ + response = self._requester.request( + "GET", + "quiz_submissions/{}/questions".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + questions = list() + for question in response.json().get("quiz_submission_questions", []): + question.update({"quiz_submission_id": self.id, "attempt": self.attempt}) + questions.append(QuizSubmissionQuestion(self._requester, question)) + + return questions + def get_times(self, **kwargs): """ Get the current timing data for the quiz attempt, both the end_at timestamp and the @@ -421,74 +489,6 @@ def update_score_and_comments(self, **kwargs): return QuizSubmission(self._requester, response_json) - def get_submission_questions(self, **kwargs): - """ - Get a list of all the question records for this quiz submission. - - :calls: `GET /api/v1/quiz_submissions/:quiz_submission_id/questions \ - `_ - - :returns: A list of quiz submission questions. - :rtype: list of :class:`canvasapi.quiz.QuizSubmissionQuestion` - """ - response = self._requester.request( - "GET", - "quiz_submissions/{}/questions".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - - questions = list() - for question in response.json().get("quiz_submission_questions", []): - question.update({"quiz_submission_id": self.id, "attempt": self.attempt}) - questions.append(QuizSubmissionQuestion(self._requester, question)) - - return questions - - def answer_submission_questions(self, validation_token=None, **kwargs): - """ - Provide or update an answer to one or more quiz questions. - - :calls: `POST /api/v1/quiz_submissions/:quiz_submission_id/questions \ - `_ - - :param validation_token: (Optional) The unique validation token for this quiz submission. - If one is not provided, canvasapi will attempt to use `self.validation_token`. - :type validation_token: str - :returns: A list of quiz submission questions. - :rtype: list of :class:`canvasapi.quiz.QuizSubmissionQuestion` - """ - try: - kwargs["validation_token"] = validation_token or self.validation_token - except AttributeError: - raise RequiredFieldMissing( - "`validation_token` not set on this QuizSubmission, must be passed" - " as a function argument." - ) - - # Only the latest attempt for a quiz submission can be updated, and Canvas - # automatically returns the latest attempt with every quiz submission response, - # so we can just use that. - kwargs["attempt"] = self.attempt - - response = self._requester.request( - "POST", - "quiz_submissions/{}/questions".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - - questions = list() - for question in response.json().get("quiz_submission_questions", []): - question.update( - { - "quiz_submission_id": self.id, - "validation_token": kwargs["validation_token"], - "attempt": self.attempt, - } - ) - questions.append(QuizSubmissionQuestion(self._requester, question)) - - return questions - @python_2_unicode_compatible class QuizExtension(CanvasObject): diff --git a/canvasapi/quiz_group.py b/canvasapi/quiz_group.py index ccb78d28..65df15bd 100644 --- a/canvasapi/quiz_group.py +++ b/canvasapi/quiz_group.py @@ -12,48 +12,6 @@ class QuizGroup(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) - def update(self, id, quiz_groups, **kwargs): - """ - Update a question group given by id. - - :calls: `PUT /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \ - `_ - - :param id: The ID of the question group. - :type id: int - :param quiz_groups: The name, pick count, and/or question points. - All of these parameters are optional, but at least one must exist - (even if empty) to recieve a response. - The request expects a list, but will only update 1 question group per request. - :type quiz_groups: list[dict] - - :returns: `True` if the QuizGroup was updated. `False` otherwise. - :rtype: bool - """ - if not isinstance(quiz_groups, list) or len(quiz_groups) <= 0: - raise ValueError("Param `quiz_groups` must be a non-empty list.") - - if not isinstance(quiz_groups[0], dict): - raise ValueError("Param `quiz_groups` must contain a dictionary") - - param_list = ["name", "pick_count", "question_points"] - if not any(param in quiz_groups[0] for param in param_list): - raise RequiredFieldMissing("quiz_groups must contain at least 1 parameter.") - - kwargs["quiz_groups"] = quiz_groups - - response = self._requester.request( - "PUT", - "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.quiz_id, id), - _kwargs=combine_kwargs(**kwargs), - ) - - successful = "name" in response.json().get("quiz_groups")[0] - if successful: - super(QuizGroup, self).set_attributes(response.json().get("quiz_groups")[0]) - - return successful - def delete(self, id): """ Get details of the quiz group with the given id. @@ -113,3 +71,45 @@ def reorder_question_group(self, id, order, **kwargs): ) return response.status_code == 204 + + def update(self, id, quiz_groups, **kwargs): + """ + Update a question group given by id. + + :calls: `PUT /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \ + `_ + + :param id: The ID of the question group. + :type id: int + :param quiz_groups: The name, pick count, and/or question points. + All of these parameters are optional, but at least one must exist + (even if empty) to recieve a response. + The request expects a list, but will only update 1 question group per request. + :type quiz_groups: list[dict] + + :returns: `True` if the QuizGroup was updated. `False` otherwise. + :rtype: bool + """ + if not isinstance(quiz_groups, list) or len(quiz_groups) <= 0: + raise ValueError("Param `quiz_groups` must be a non-empty list.") + + if not isinstance(quiz_groups[0], dict): + raise ValueError("Param `quiz_groups` must contain a dictionary") + + param_list = ["name", "pick_count", "question_points"] + if not any(param in quiz_groups[0] for param in param_list): + raise RequiredFieldMissing("quiz_groups must contain at least 1 parameter.") + + kwargs["quiz_groups"] = quiz_groups + + response = self._requester.request( + "PUT", + "courses/{}/quizzes/{}/groups/{}".format(self.course_id, self.quiz_id, id), + _kwargs=combine_kwargs(**kwargs), + ) + + successful = "name" in response.json().get("quiz_groups")[0] + if successful: + super(QuizGroup, self).set_attributes(response.json().get("quiz_groups")[0]) + + return successful diff --git a/canvasapi/requester.py b/canvasapi/requester.py index 164156e2..36ad89c9 100644 --- a/canvasapi/requester.py +++ b/canvasapi/requester.py @@ -37,6 +37,85 @@ def __init__(self, base_url, access_token): self._session = requests.Session() self._cache = [] + def _delete_request(self, url, headers, data=None): + """ + Issue a DELETE request to the specified endpoint with the data provided. + + :param url: The URL to request. + :type url: str + :param headers: The HTTP headers to send with this request. + :type headers: dict + :param data: The data to send with this request. + :type data: dict + """ + return self._session.delete(url, headers=headers, data=data) + + def _get_request(self, url, headers, params=None): + """ + Issue a GET request to the specified endpoint with the data provided. + + :param url: The URL to request. + :type url: str + :param headers: The HTTP headers to send with this request. + :type headers: dict + :param params: The parameters to send with this request. + :type params: dict + """ + return self._session.get(url, headers=headers, params=params) + + def _patch_request(self, url, headers, data=None): + """ + Issue a PATCH request to the specified endpoint with the data provided. + + :param url: The URL to request. + :type url: str + :param headers: The HTTP headers to send with this request. + :type headers: dict + :param data: The data to send with this request. + :type data: dict + """ + return self._session.patch(url, headers=headers, data=data) + + def _post_request(self, url, headers, data=None): + """ + Issue a POST request to the specified endpoint with the data provided. + + :param url: The URL to request. + :type url: str + :param headers: The HTTP headers to send with this request. + :type headers: dict + :param data: The data to send with this request. + :type data: dict + """ + + # Grab file from data. + files = None + for field, value in data: + if field == "file": + if isinstance(value, dict): + files = value + else: + files = {"file": value} + break + + # Remove file entry from data. + data[:] = [tup for tup in data if tup[0] != "file"] + + return self._session.post(url, headers=headers, data=data, files=files) + + def _put_request(self, url, headers, data=None): + """ + Issue a PUT request to the specified endpoint with the data provided. + + :param url: The URL to request. + :type url: str + :param headers: The HTTP headers to send with this request. + :type headers: dict + :param data: The data to send with this request. + :type data: dict + """ + return self._session.put(url, headers=headers, data=data) + def request( self, method, @@ -159,82 +238,3 @@ def request( ) return response - - def _get_request(self, url, headers, params=None): - """ - Issue a GET request to the specified endpoint with the data provided. - - :param url: The URL to request. - :type url: str - :param headers: The HTTP headers to send with this request. - :type headers: dict - :param params: The parameters to send with this request. - :type params: dict - """ - return self._session.get(url, headers=headers, params=params) - - def _post_request(self, url, headers, data=None): - """ - Issue a POST request to the specified endpoint with the data provided. - - :param url: The URL to request. - :type url: str - :param headers: The HTTP headers to send with this request. - :type headers: dict - :param data: The data to send with this request. - :type data: dict - """ - - # Grab file from data. - files = None - for field, value in data: - if field == "file": - if isinstance(value, dict): - files = value - else: - files = {"file": value} - break - - # Remove file entry from data. - data[:] = [tup for tup in data if tup[0] != "file"] - - return self._session.post(url, headers=headers, data=data, files=files) - - def _delete_request(self, url, headers, data=None): - """ - Issue a DELETE request to the specified endpoint with the data provided. - - :param url: The URL to request. - :type url: str - :param headers: The HTTP headers to send with this request. - :type headers: dict - :param data: The data to send with this request. - :type data: dict - """ - return self._session.delete(url, headers=headers, data=data) - - def _patch_request(self, url, headers, data=None): - """ - Issue a PATCH request to the specified endpoint with the data provided. - - :param url: The URL to request. - :type url: str - :param headers: The HTTP headers to send with this request. - :type headers: dict - :param data: The data to send with this request. - :type data: dict - """ - return self._session.patch(url, headers=headers, data=data) - - def _put_request(self, url, headers, data=None): - """ - Issue a PUT request to the specified endpoint with the data provided. - - :param url: The URL to request. - :type url: str - :param headers: The HTTP headers to send with this request. - :type headers: dict - :param data: The data to send with this request. - :type data: dict - """ - return self._session.put(url, headers=headers, data=data) diff --git a/canvasapi/section.py b/canvasapi/section.py index fb358dc8..1e9d77d7 100644 --- a/canvasapi/section.py +++ b/canvasapi/section.py @@ -17,50 +17,6 @@ class Section(CanvasObject): def __str__(self): return "{} - {} ({})".format(self.name, self.course_id, self.id) - def get_assignment_override(self, assignment, **kwargs): - """ - Return override for the specified assignment for this section. - - :param assignment: The assignment to get an override for - :type assignment: :class:`canvasapi.assignment.Assignment` or int - - :calls: `GET /api/v1/sections/:course_section_id/assignments/:assignment_id/override \ - `_ - - :rtype: :class:`canvasapi.assignment.AssignmentOverride` - """ - from canvasapi.assignment import Assignment, AssignmentOverride - - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - - response = self._requester.request( - "GET", "sections/{}/assignments/{}/override".format(self.id, assignment_id) - ) - response_json = response.json() - response_json.update({"course_id": self.course_id}) - - return AssignmentOverride(self._requester, response_json) - - def get_enrollments(self, **kwargs): - """ - List all of the enrollments for the current user. - - :calls: `GET /api/v1/sections/:section_id/enrollments \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.enrollment.Enrollment` - """ - from canvasapi.enrollment import Enrollment - - return PaginatedList( - Enrollment, - self._requester, - "GET", - "sections/{}/enrollments".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - def cross_list_section(self, new_course): """ Move the Section to another course. @@ -96,6 +52,18 @@ def decross_list_section(self): ) return Section(self._requester, response.json()) + def delete(self): + """ + Delete a target section. + + :calls: `DELETE /api/v1/sections/:id \ + `_ + + :rtype: :class:`canvasapi.section.Section` + """ + response = self._requester.request("DELETE", "sections/{}".format(self.id)) + return Section(self._requester, response.json()) + def edit(self, **kwargs): """ Edit contents of a target section. @@ -114,108 +82,50 @@ def edit(self, **kwargs): return self - def delete(self): + def get_assignment_override(self, assignment, **kwargs): """ - Delete a target section. + Return override for the specified assignment for this section. - :calls: `DELETE /api/v1/sections/:id \ - `_ + :param assignment: The assignment to get an override for + :type assignment: :class:`canvasapi.assignment.Assignment` or int - :rtype: :class:`canvasapi.section.Section` - """ - response = self._requester.request("DELETE", "sections/{}".format(self.id)) - return Section(self._requester, response.json()) + :calls: `GET /api/v1/sections/:course_section_id/assignments/:assignment_id/override \ + `_ - def submit_assignment(self, assignment, submission, **kwargs): + :rtype: :class:`canvasapi.assignment.AssignmentOverride` """ - Makes a submission for an assignment. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.assignment.Assignment.submit` instead. - - :calls: `POST /api/v1/sections/:section_id/assignments/:assignment_id/submissions \ - `_ - - :param assignment: The object or ID of the assignment. - :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param submission: The attributes of the submission. - :type submission: dict + from canvasapi.assignment import Assignment, AssignmentOverride - :rtype: :class:`canvasapi.submission.Submission` - """ - from canvasapi.assignment import Assignment + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - warnings.warn( - "Section.submit_assignment() is deprecated and will be removed " - "in the future. Use Assignment.submit() instead.", - DeprecationWarning, + response = self._requester.request( + "GET", "sections/{}/assignments/{}/override".format(self.id, assignment_id) ) + response_json = response.json() + response_json.update({"course_id": self.course_id}) - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - assignment = Assignment( - self._requester, - {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, - ) - return assignment.submit(submission, **kwargs) + return AssignmentOverride(self._requester, response_json) - def list_submissions(self, assignment, **kwargs): + def get_enrollments(self, **kwargs): """ - Get all existing submissions for an assignment. - - .. warning:: - .. deprecated:: 0.9.0 - Use :func:`canvasapi.assignment.Assignment.get_submissions` instead. - - :calls: `GET /api/v1/sections/:section_id/assignments/:assignment_id/submissions \ - `_ + List all of the enrollments for the current user. - :param assignment: The object or ID of the assignment. - :type assignment: :class:`canvasapi.assignment.Assignment` or int + :calls: `GET /api/v1/sections/:section_id/enrollments \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.submission.Submission` + :class:`canvasapi.enrollment.Enrollment` """ - from canvasapi.assignment import Assignment - - warnings.warn( - "Section.list_submissions() is deprecated and will be removed " - "in the future. Use Assignment.get_submissions() instead.", - DeprecationWarning, - ) + from canvasapi.enrollment import Enrollment - assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - assignment = Assignment( + return PaginatedList( + Enrollment, self._requester, - {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, - ) - - return assignment.get_submissions(**kwargs) - - def list_multiple_submissions(self, **kwargs): - """ - List submissions for multiple assignments. - Get all existing submissions for a given set of students and assignments. - - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.section.Section.get_multiple_submissions` instead. - - :calls: `GET /api/v1/sections/:section_id/students/submissions \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.submission.Submission` - """ - warnings.warn( - "`list_multiple_submissions`" - " is being deprecated and will be removed in a future version." - " Use `get_multiple_submissions` instead", - DeprecationWarning, + "GET", + "sections/{}/enrollments".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_multiple_submissions(**kwargs) - def get_multiple_submissions(self, **kwargs): """ List submissions for multiple assignments. @@ -278,46 +188,62 @@ def get_submission(self, assignment, user, **kwargs): return assignment.get_submission(user, **kwargs) - def update_submission(self, assignment, user, **kwargs): + def list_multiple_submissions(self, **kwargs): """ - Comment on and/or update the grading for a student's assignment submission. + List submissions for multiple assignments. + Get all existing submissions for a given set of students and assignments. + + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.section.Section.get_multiple_submissions` instead. + + :calls: `GET /api/v1/sections/:section_id/students/submissions \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.submission.Submission` + """ + warnings.warn( + "`list_multiple_submissions`" + " is being deprecated and will be removed in a future version." + " Use `get_multiple_submissions` instead", + DeprecationWarning, + ) + + return self.get_multiple_submissions(**kwargs) + + def list_submissions(self, assignment, **kwargs): + """ + Get all existing submissions for an assignment. .. warning:: .. deprecated:: 0.9.0 - Use :func:`canvasapi.submission.Submission.edit` instead. + Use :func:`canvasapi.assignment.Assignment.get_submissions` instead. - :calls: `PUT /api/v1/sections/:section_id/assignments/:assignment_id/submissions/:user_id \ - `_ + :calls: `GET /api/v1/sections/:section_id/assignments/:assignment_id/submissions \ + `_ :param assignment: The object or ID of the assignment. :type assignment: :class:`canvasapi.assignment.Assignment` or int - :param user: The object or ID of the user. - :type user: :class:`canvasapi.user.User` or int or str - :rtype: :class:`canvasapi.submission.Submission` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.submission.Submission` """ from canvasapi.assignment import Assignment - from canvasapi.user import User warnings.warn( - "Section.update_submission() is deprecated and will be removed " - "in the future. Use Submission.edit() instead.", + "Section.list_submissions() is deprecated and will be removed " + "in the future. Use Assignment.get_submissions() instead.", DeprecationWarning, ) assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) - user_id = obj_or_id(user, "user", (User,)) - - submission = Submission( + assignment = Assignment( self._requester, - { - "course_id": self.course_id, - "assignment_id": assignment_id, - "user_id": user_id, - }, + {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, ) - return submission.edit(**kwargs) + return assignment.get_submissions(**kwargs) def mark_submission_as_read(self, assignment, user, **kwargs): """ @@ -417,3 +343,77 @@ def submissions_bulk_update(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) return Progress(self._requester, response.json()) + + def submit_assignment(self, assignment, submission, **kwargs): + """ + Makes a submission for an assignment. + + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.assignment.Assignment.submit` instead. + + :calls: `POST /api/v1/sections/:section_id/assignments/:assignment_id/submissions \ + `_ + + :param assignment: The object or ID of the assignment. + :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param submission: The attributes of the submission. + :type submission: dict + + :rtype: :class:`canvasapi.submission.Submission` + """ + from canvasapi.assignment import Assignment + + warnings.warn( + "Section.submit_assignment() is deprecated and will be removed " + "in the future. Use Assignment.submit() instead.", + DeprecationWarning, + ) + + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + assignment = Assignment( + self._requester, + {"course_id": self.course_id, "section_id": self.id, "id": assignment_id}, + ) + return assignment.submit(submission, **kwargs) + + def update_submission(self, assignment, user, **kwargs): + """ + Comment on and/or update the grading for a student's assignment submission. + + .. warning:: + .. deprecated:: 0.9.0 + Use :func:`canvasapi.submission.Submission.edit` instead. + + :calls: `PUT /api/v1/sections/:section_id/assignments/:assignment_id/submissions/:user_id \ + `_ + + :param assignment: The object or ID of the assignment. + :type assignment: :class:`canvasapi.assignment.Assignment` or int + :param user: The object or ID of the user. + :type user: :class:`canvasapi.user.User` or int or str + + :rtype: :class:`canvasapi.submission.Submission` + """ + from canvasapi.assignment import Assignment + from canvasapi.user import User + + warnings.warn( + "Section.update_submission() is deprecated and will be removed " + "in the future. Use Submission.edit() instead.", + DeprecationWarning, + ) + + assignment_id = obj_or_id(assignment, "assignment", (Assignment,)) + user_id = obj_or_id(user, "user", (User,)) + + submission = Submission( + self._requester, + { + "course_id": self.course_id, + "assignment_id": assignment_id, + "user_id": user_id, + }, + ) + + return submission.edit(**kwargs) diff --git a/canvasapi/submission.py b/canvasapi/submission.py index f4d87a0f..588a24a3 100644 --- a/canvasapi/submission.py +++ b/canvasapi/submission.py @@ -89,6 +89,27 @@ def edit(self, **kwargs): super(Submission, self).set_attributes(response_json) return self + def get_submission_peer_reviews(self, **kwargs): + """ + Get a list of all Peer Reviews this submission. + + :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/ \ + submissions/:submission_id/peer_reviews \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.peer_review.PeerReview` + """ + return PaginatedList( + PeerReview, + self._requester, + "GET", + "courses/{}/assignments/{}/submissions/{}/peer_reviews".format( + self.course_id, self.assignment_id, self.id + ), + _kwargs=combine_kwargs(**kwargs), + ) + def mark_read(self, **kwargs): """ Mark submission as read. No request fields are necessary. @@ -127,27 +148,6 @@ def mark_unread(self, **kwargs): ) return response.status_code == 204 - def get_submission_peer_reviews(self, **kwargs): - """ - Get a list of all Peer Reviews this submission. - - :calls: `GET /api/v1/courses/:course_id/assignments/:assignment_id/ \ - submissions/:submission_id/peer_reviews \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.peer_review.PeerReview` - """ - return PaginatedList( - PeerReview, - self._requester, - "GET", - "courses/{}/assignments/{}/submissions/{}/peer_reviews".format( - self.course_id, self.assignment_id, self.id - ), - _kwargs=combine_kwargs(**kwargs), - ) - def upload_comment(self, file, **kwargs): """ Upload a file to attach to this submission as a comment. @@ -178,11 +178,6 @@ def upload_comment(self, file, **kwargs): @python_2_unicode_compatible class GroupedSubmission(CanvasObject): - def __str__(self): - return "{} submission(s) for User #{}".format( - len(self.submissions), self.user_id - ) - def __init__(self, requester, attributes): try: self.submissions = [ @@ -194,3 +189,8 @@ def __init__(self, requester, attributes): self.submissions = list() super(GroupedSubmission, self).__init__(requester, attributes) + + def __str__(self): + return "{} submission(s) for User #{}".format( + len(self.submissions), self.user_id + ) diff --git a/canvasapi/upload.py b/canvasapi/upload.py index 1a3017dd..28a005c8 100644 --- a/canvasapi/upload.py +++ b/canvasapi/upload.py @@ -33,22 +33,6 @@ def __init__(self, requester, url, file, **kwargs): self.file = file self.kwargs = kwargs - def start(self): - """ - Kick off uploading process. Handles open/closing file if a path - is passed. - - :calls: request_upload_token - :returns: True if the file uploaded successfully, False \ - otherwise, and the JSON response from the API. - :rtype: tuple - """ - if self._using_filename: - with open(self.file, "rb") as file: - return self.request_upload_token(file) - else: - return self.request_upload_token(self.file) - def request_upload_token(self, file): """ Request an upload token. @@ -67,6 +51,22 @@ def request_upload_token(self, file): return self.upload(response, file) + def start(self): + """ + Kick off uploading process. Handles open/closing file if a path + is passed. + + :calls: request_upload_token + :returns: True if the file uploaded successfully, False \ + otherwise, and the JSON response from the API. + :rtype: tuple + """ + if self._using_filename: + with open(self.file, "rb") as file: + return self.request_upload_token(file) + else: + return self.request_upload_token(self.file) + def upload(self, response, file): """ Upload the file. diff --git a/canvasapi/user.py b/canvasapi/user.py index aebe15b2..400c1b2b 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -17,144 +17,107 @@ class User(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) - def get_profile(self, **kwargs): - """ - Retrieve this user's profile. - - :calls: `GET /api/v1/users/:user_id/profile \ - `_ - - :rtype: dict - """ - response = self._requester.request("GET", "users/{}/profile".format(self.id)) - return response.json() - - def get_page_views(self, **kwargs): + def add_observee(self, observee_id): """ - Retrieve this user's page views. + Registers a user as being observed by the given user. - :calls: `GET /api/v1/users/:user_id/page_views \ - `_ + :calls: `PUT /api/v1/users/:user_id/observees/:observee_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.PageView` + :param observee_id: The login id for the user to observe. + :type observee_id: int + :rtype: :class: `canvasapi.user.User` """ - from canvasapi.page_view import PageView - return PaginatedList( - PageView, - self._requester, - "GET", - "users/{}/page_views".format(self.id), - _kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "PUT", "users/{}/observees/{}".format(self.id, observee_id) ) + return User(self._requester, response.json()) - def get_courses(self, **kwargs): + def add_observee_with_credentials(self, **kwargs): """ - Retrieve all courses this user is enrolled in. + Register the given user to observe another user, given the observee's credentials. - :calls: `GET /api/v1/users/:user_id/courses \ - `_ + :calls: `POST /api/v1/users/:user_id/observees \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.course.Course` + :rtype: :class:`canvasapi.user.User` """ - from canvasapi.course import Course - return PaginatedList( - Course, - self._requester, - "GET", - "users/{}/courses".format(self.id), + response = self._requester.request( + "POST", + "users/{}/observees".format(self.id), _kwargs=combine_kwargs(**kwargs), ) + return User(self._requester, response.json()) - def get_missing_submissions(self): + def create_communication_channel(self, **kwargs): """ - Retrieve all past-due assignments for which the student does not - have a submission. + Create a communication channel for this user - :calls: `GET /api/v1/users/:user_id/missing_submissions \ - `_ + :calls: `POST /api/v1/users/:user_id/communication_channels \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.assignment.Assignment` + :rtype: :class:`canvasapi.communication_channel.CommunicationChannel` """ - from canvasapi.assignment import Assignment - - return PaginatedList( - Assignment, - self._requester, - "GET", - "users/{}/missing_submissions".format(self.id), + response = self._requester.request( + "POST", + "users/{}/communication_channels".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - def update_settings(self, **kwargs): + return CommunicationChannel(self._requester, response.json()) + + def create_content_migration(self, migration_type, **kwargs): """ - Update this user's settings. + Create a content migration. - :calls: `PUT /api/v1/users/:id/settings \ - `_ + :calls: `POST /api/v1/users/:user_id/content_migrations \ + `_ - :rtype: dict - """ - response = self._requester.request( - "PUT", "users/{}/settings".format(self.id), _kwargs=combine_kwargs(**kwargs) - ) - return response.json() + :param migration_type: The migrator type to use in this migration + :type migration_type: str or :class:`canvasapi.content_migration.Migrator` - def get_color(self, asset_string): + :rtype: :class:`canvasapi.content_migration.ContentMigration` """ - Return the custom colors that have been saved by this user for a given context. - - The `asset_string` parameter should be in the format 'context_id', for example 'course_42'. + from canvasapi.content_migration import ContentMigration, Migrator - :calls: `GET /api/v1/users/:id/colors/:asset_string \ - `_ + if isinstance(migration_type, Migrator): + kwargs["migration_type"] = migration_type.type + elif isinstance(migration_type, string_types): + kwargs["migration_type"] = migration_type + else: + raise TypeError("Parameter migration_type must be of type Migrator or str") - :param asset_string: The asset to retrieve the color from. - :type asset_string: str - :rtype: dict - """ response = self._requester.request( - "GET", "users/{}/colors/{}".format(self.id, asset_string) + "POST", + "users/{}/content_migrations".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return response.json() - def get_colors(self): - """ - Return all custom colors that have been saved by this user. - - :calls: `GET /api/v1/users/:id/colors \ - `_ + response_json = response.json() + response_json.update({"user_id": self.id}) - :rtype: dict - """ - response = self._requester.request("GET", "users/{}/colors".format(self.id)) - return response.json() + return ContentMigration(self._requester, response_json) - def update_color(self, asset_string, hexcode): + def create_folder(self, name, **kwargs): """ - Update a custom color for this user for a given context. - - This allows colors for the calendar and elsewhere to be customized on a user basis. - - The `asset_string` parameter should be in the format 'context_id', for example 'course_42'. - The `hexcode` parameter need not include the '#'. + Creates a folder in this user. - :calls: `PUT /api/v1/users/:id/colors/:asset_string \ - `_ + :calls: `POST /api/v1/users/:user_id/folders \ + `_ - :param asset_string: The asset to modify the color for. - :type asset_string: str - :param hexcode: The hexcode of the color to use. - :type hexcode: str - :rtype: dict + :param name: The name of the folder. + :type name: str + :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( - "PUT", "users/{}/colors/{}".format(self.id, asset_string), hexcode=hexcode + "POST", + "users/{}/folders".format(self.id), + name=name, + _kwargs=combine_kwargs(**kwargs), ) - return response.json() + return Folder(self._requester, response.json()) def edit(self, **kwargs): """ @@ -171,41 +134,28 @@ def edit(self, **kwargs): super(User, self).set_attributes(response.json()) return self - def merge_into(self, destination_user): + def export_content(self, export_type, **kwargs): """ - Merge this user into another user. - - :calls: `PUT /api/v1/users/:id/merge_into/:destination_user_id \ - `_ - - :param destination_user: The object or ID of the user to merge into. - :type destination_user: :class:`canvasapi.user.User` or int + Begin a content export job for a user. - :rtype: :class:`canvasapi.user.User` - """ - dest_user_id = obj_or_id(destination_user, "destination_user", (User,)) + :calls: `POST /api/v1/users/:user_id/content_exports\ + `_ - response = self._requester.request( - "PUT", "users/{}/merge_into/{}".format(self.id, dest_user_id) - ) - super(User, self).set_attributes(response.json()) - return self + :param export_type: The type of content to export. + :type export_type: str - def get_avatars(self): + :rtype: :class:`canvasapi.content_export.ContentExport` """ - Retrieve the possible user avatar options that can be set with the user update endpoint. - - :calls: `GET /api/v1/users/:user_id/avatars \ - `_ + from canvasapi.content_export import ContentExport - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.avatar.Avatar` - """ - from canvasapi.avatar import Avatar + kwargs["export_type"] = export_type - return PaginatedList( - Avatar, self._requester, "GET", "users/{}/avatars".format(self.id) + response = self._requester.request( + "POST", + "users/{}/content_exports".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) + return ContentExport(self._requester, response.json()) def get_assignments(self, course, **kwargs): """ @@ -234,111 +184,90 @@ def get_assignments(self, course, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def get_enrollments(self, **kwargs): + def get_avatars(self): """ - List all of the enrollments for this user. + Retrieve the possible user avatar options that can be set with the user update endpoint. - :calls: `GET /api/v1/users/:user_id/enrollments \ - `_ + :calls: `GET /api/v1/users/:user_id/avatars \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.enrollment.Enrollment` + :class:`canvasapi.avatar.Avatar` """ - from canvasapi.enrollment import Enrollment + from canvasapi.avatar import Avatar return PaginatedList( - Enrollment, - self._requester, - "GET", - "users/{}/enrollments".format(self.id), - _kwargs=combine_kwargs(**kwargs), + Avatar, self._requester, "GET", "users/{}/avatars".format(self.id) ) - def upload(self, file, **kwargs): - """ - Upload a file for a user. - - NOTE: You *must* have authenticated with this user's API key to - upload on their behalf no matter what permissions the issuer of the - request has. - - :calls: `POST /api/v1/users/:user_id/files \ - `_ - - :param file: The file or path of the file to upload. - :type file: file or str - :returns: True if the file uploaded successfully, False otherwise, \ - and the JSON response from the API. - :rtype: tuple - """ - return Uploader( - self._requester, "users/{}/files".format(self.id), file, **kwargs - ).start() - - def list_calendar_events_for_user(self, **kwargs): + def get_calendar_events_for_user(self, **kwargs): """ List calendar events that the current user can view or manage. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.user.User.get_calendar_events_for_user` instead. - :calls: `GET /api/v1/users/:user_id/calendar_events \ `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.calendar_event.CalendarEvent` """ - warnings.warn( - "`list_calendar_events_for_user`" - " is being deprecated and will be removed in a future version." - " Use `get_calendar_events_for_user` instead", - DeprecationWarning, - ) - - return self.get_calendar_events_for_user(**kwargs) - - def get_calendar_events_for_user(self, **kwargs): + return PaginatedList( + CalendarEvent, + self._requester, + "GET", + "users/{}/calendar_events".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + def get_closed_poll_sessions(self, **kwargs): """ - List calendar events that the current user can view or manage. + Returns a paginated list of all closed poll sessions available to the current user. - :calls: `GET /api/v1/users/:user_id/calendar_events \ - `_ + :calls: `GET /api/v1/poll_sessions/closed \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.calendar_event.CalendarEvent` + :class:`canvasapi.poll_session.PollSession` """ + from canvasapi.poll_session import PollSession + return PaginatedList( - CalendarEvent, + PollSession, self._requester, "GET", - "users/{}/calendar_events".format(self.id), + "poll_sessions/closed", + _root="poll_sessions", _kwargs=combine_kwargs(**kwargs), ) - def list_communication_channels(self, **kwargs): + def get_color(self, asset_string): """ - List communication channels for the specified user, sorted by - position. + Return the custom colors that have been saved by this user for a given context. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.user.User.get_communication_channels` instead. + The `asset_string` parameter should be in the format 'context_id', for example 'course_42'. - :calls: `GET /api/v1/users/:user_id/communication_channels \ - `_ + :calls: `GET /api/v1/users/:id/colors/:asset_string \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.communication_channel.CommunicationChannel` + :param asset_string: The asset to retrieve the color from. + :type asset_string: str + :rtype: dict """ - warnings.warn( - "`list_communication_channels`" - " is being deprecated and will be removed in a future version." - " Use `get_communication_channels` instead", - DeprecationWarning, + response = self._requester.request( + "GET", "users/{}/colors/{}".format(self.id, asset_string) ) + return response.json() - return self.get_communication_channels(**kwargs) + def get_colors(self): + """ + Return all custom colors that have been saved by this user. + + :calls: `GET /api/v1/users/:id/colors \ + `_ + + :rtype: dict + """ + response = self._requester.request("GET", "users/{}/colors".format(self.id)) + return response.json() def get_communication_channels(self, **kwargs): """ @@ -359,62 +288,137 @@ def get_communication_channels(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def create_communication_channel(self, **kwargs): + def get_content_export(self, content_export, **kwargs): """ - Create a communication channel for this user + Return information about a single content export. - :calls: `POST /api/v1/users/:user_id/communication_channels \ - `_ + :calls: `GET /api/v1/users/:user_id/content_exports/:id\ + `_ - :rtype: :class:`canvasapi.communication_channel.CommunicationChannel` + :param content_export: The object or ID of the content export to show. + :type content_export: int or :class:`canvasapi.content_export.ContentExport` + + :rtype: :class:`canvasapi.content_export.ContentExport` """ + from canvasapi.content_export import ContentExport + + export_id = obj_or_id(content_export, "content_export", (ContentExport,)) + response = self._requester.request( - "POST", - "users/{}/communication_channels".format(self.id), + "GET", + "users/{}/content_exports/{}".format(self.id, export_id), _kwargs=combine_kwargs(**kwargs), ) - return CommunicationChannel(self._requester, response.json()) + return ContentExport(self._requester, response.json()) - def list_files(self, **kwargs): + def get_content_exports(self, **kwargs): """ - Returns the paginated list of files for the user. + Return a paginated list of the past and pending content export jobs for a user. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.user.User.get_files` instead. + :calls: `GET /api/v1/users/:user_id/content_exports\ + `_ - :calls: `GET /api/v1/users/:user_id/files \ - `_ + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.content_export.ContentExport` + """ + from canvasapi.content_export import ContentExport + + return PaginatedList( + ContentExport, + self._requester, + "GET", + "users/{}/content_exports".format(self.id), + kwargs=combine_kwargs(**kwargs), + ) + + def get_content_migration(self, content_migration, **kwargs): + """ + Retrive a content migration by its ID + + :calls: `GET /api/v1/users/:user_id/content_migrations/:id \ + `_ + + :param content_migration: The object or ID of the content migration to retrieve. + :type content_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + + :rtype: :class:`canvasapi.content_migration.ContentMigration` + """ + from canvasapi.content_migration import ContentMigration + + migration_id = obj_or_id( + content_migration, "content_migration", (ContentMigration,) + ) + + response = self._requester.request( + "GET", + "users/{}/content_migrations/{}".format(self.id, migration_id), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({"user_id": self.id}) + + return ContentMigration(self._requester, response_json) + + def get_content_migrations(self, **kwargs): + """ + List content migrations that the current account can view or manage. + + :calls: `GET /api/v1/users/:user_id/content_migrations/ \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` + :class:`canvasapi.content_migration.ContentMigration` """ - warnings.warn( - "`list_files` is being deprecated and will be removed in a future " - "version. Use `get_files` instead", - DeprecationWarning, + from canvasapi.content_migration import ContentMigration + + return PaginatedList( + ContentMigration, + self._requester, + "GET", + "users/{}/content_migrations".format(self.id), + {"user_id": self.id}, + _kwargs=combine_kwargs(**kwargs), ) - return self.get_files(**kwargs) + def get_courses(self, **kwargs): + """ + Retrieve all courses this user is enrolled in. - def get_files(self, **kwargs): + :calls: `GET /api/v1/users/:user_id/courses \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.course.Course` """ - Returns the paginated list of files for the user. + from canvasapi.course import Course - :calls: `GET /api/v1/users/:user_id/files \ - `_ + return PaginatedList( + Course, + self._requester, + "GET", + "users/{}/courses".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + def get_enrollments(self, **kwargs): + """ + List all of the enrollments for this user. + + :calls: `GET /api/v1/users/:user_id/enrollments \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.file.File` + :class:`canvasapi.enrollment.Enrollment` """ - from canvasapi.file import File + from canvasapi.enrollment import Enrollment return PaginatedList( - File, + Enrollment, self._requester, "GET", - "users/{}/files".format(self.id), + "users/{}/enrollments".format(self.id), _kwargs=combine_kwargs(**kwargs), ) @@ -441,6 +445,26 @@ def get_file(self, file, **kwargs): ) return File(self._requester, response.json()) + def get_files(self, **kwargs): + """ + Returns the paginated list of files for the user. + + :calls: `GET /api/v1/users/:user_id/files \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.file.File` + """ + from canvasapi.file import File + + return PaginatedList( + File, + self._requester, + "GET", + "users/{}/files".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_folder(self, folder): """ Returns the details for a user's folder @@ -462,88 +486,136 @@ def get_folder(self, folder): ) return Folder(self._requester, response.json()) - def list_folders(self, **kwargs): + def get_folders(self, **kwargs): """ Returns the paginated list of all folders for the given user. This will be returned as a flat list containing all subfolders as well. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.user.User.get_folders` instead. - :calls: `GET /api/v1/users/:user_id/folders \ `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.folder.Folder` """ - warnings.warn( - "`list_folders` is being deprecated and will be removed in a " - "future version. Use `get_folders` instead.", - DeprecationWarning, + return PaginatedList( + Folder, + self._requester, + "GET", + "users/{}/folders".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_folders(**kwargs) - - def get_folders(self, **kwargs): + def get_migration_systems(self, **kwargs): """ - Returns the paginated list of all folders for the given user. This will be returned as a - flat list containing all subfolders as well. + Return a list of migration systems. - :calls: `GET /api/v1/users/:user_id/folders \ - `_ + :calls: `GET /api/v1/users/:user_id/content_migrations/migrators \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.folder.Folder` + :class:`canvasapi.content_migration.Migrator` """ + from canvasapi.content_migration import Migrator + return PaginatedList( - Folder, + Migrator, self._requester, "GET", - "users/{}/folders".format(self.id), + "users/{}/content_migrations/migrators".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - def create_folder(self, name, **kwargs): + def get_missing_submissions(self): """ - Creates a folder in this user. + Retrieve all past-due assignments for which the student does not + have a submission. - :calls: `POST /api/v1/users/:user_id/folders \ - `_ + :calls: `GET /api/v1/users/:user_id/missing_submissions \ + `_ - :param name: The name of the folder. - :type name: str - :rtype: :class:`canvasapi.folder.Folder` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.assignment.Assignment` """ - response = self._requester.request( - "POST", - "users/{}/folders".format(self.id), - name=name, + from canvasapi.assignment import Assignment + + return PaginatedList( + Assignment, + self._requester, + "GET", + "users/{}/missing_submissions".format(self.id), + ) + + def get_observees(self, **kwargs): + """ + List the users that the given user is observing + + :calls: `GET /api/v1/users/:user_id/observees \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.user.User` + """ + + return PaginatedList( + User, + self._requester, + "GET", + "users/{}/observees".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return Folder(self._requester, response.json()) - def list_user_logins(self, **kwargs): + def get_open_poll_sessions(self, **kwargs): """ - Given a user ID, return that user's logins for the given account. + Returns a paginated list of all opened poll sessions available to the current user. - .. warning:: - .. deprecated:: 0.10.0 - Use :func:`canvasapi.user.User.get_user_logins` instead. + :calls: `GET /api/v1/poll_sessions/opened \ + `_ - :calls: `GET /api/v1/users/:user_id/logins \ - `_ + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.poll_session.PollSession` + """ + from canvasapi.poll_session import PollSession + + return PaginatedList( + PollSession, + self._requester, + "GET", + "poll_sessions/opened", + _root="poll_sessions", + _kwargs=combine_kwargs(**kwargs), + ) + + def get_page_views(self, **kwargs): + """ + Retrieve this user's page views. + + :calls: `GET /api/v1/users/:user_id/page_views \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.login.Login` + :class:`canvasapi.course.PageView` """ - warnings.warn( - "`list_user_logins` is being deprecated and will be removed in a future version." - " Use `get_user_logins` instead", - DeprecationWarning, + from canvasapi.page_view import PageView + + return PaginatedList( + PageView, + self._requester, + "GET", + "users/{}/page_views".format(self.id), + _kwargs=combine_kwargs(**kwargs), ) - return self.get_user_logins(**kwargs) + def get_profile(self, **kwargs): + """ + Retrieve this user's profile. + + :calls: `GET /api/v1/users/:user_id/profile \ + `_ + + :rtype: dict + """ + response = self._requester.request("GET", "users/{}/profile".format(self.id)) + return response.json() def get_user_logins(self, **kwargs): """ @@ -565,325 +637,253 @@ def get_user_logins(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def list_observees(self, **kwargs): + def list_calendar_events_for_user(self, **kwargs): """ - List the users that the given user is observing + List calendar events that the current user can view or manage. .. warning:: .. deprecated:: 0.10.0 - Use :func:`canvasapi.user.User.get_observees` instead. + Use :func:`canvasapi.user.User.get_calendar_events_for_user` instead. - :calls: `GET /api/v1/users/:user_id/observees \ - `_ + :calls: `GET /api/v1/users/:user_id/calendar_events \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :class:`canvasapi.calendar_event.CalendarEvent` """ warnings.warn( - "`list_observees` is being deprecated and will be removed in a " - "future version. Use `get_observees` instead", + "`list_calendar_events_for_user`" + " is being deprecated and will be removed in a future version." + " Use `get_calendar_events_for_user` instead", DeprecationWarning, ) - return self.get_observees(**kwargs) + return self.get_calendar_events_for_user(**kwargs) - def get_observees(self, **kwargs): + def list_communication_channels(self, **kwargs): """ - List the users that the given user is observing + List communication channels for the specified user, sorted by + position. - :calls: `GET /api/v1/users/:user_id/observees \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.user.User.get_communication_channels` instead. + + :calls: `GET /api/v1/users/:user_id/communication_channels \ + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.user.User` + :class:`canvasapi.communication_channel.CommunicationChannel` """ - - return PaginatedList( - User, - self._requester, - "GET", - "users/{}/observees".format(self.id), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_communication_channels`" + " is being deprecated and will be removed in a future version." + " Use `get_communication_channels` instead", + DeprecationWarning, ) - def add_observee_with_credentials(self, **kwargs): - """ - Register the given user to observe another user, given the observee's credentials. - - :calls: `POST /api/v1/users/:user_id/observees \ - `_ + return self.get_communication_channels(**kwargs) - :rtype: :class:`canvasapi.user.User` + def list_files(self, **kwargs): """ + Returns the paginated list of files for the user. - response = self._requester.request( - "POST", - "users/{}/observees".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - return User(self._requester, response.json()) - - def show_observee(self, observee_id): - """ - Gets information about an observed user. + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.user.User.get_files` instead. - :calls: `GET /api/v1/users/:user_id/observees/:observee_id \ - `_ + :calls: `GET /api/v1/users/:user_id/files \ + `_ - :param observee_id: The login id for the user to observe. - :type observee_id: int - :rtype: :class: `canvasapi.user.User` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.file.File` """ - - response = self._requester.request( - "GET", "users/{}/observees/{}".format(self.id, observee_id) + warnings.warn( + "`list_files` is being deprecated and will be removed in a future " + "version. Use `get_files` instead", + DeprecationWarning, ) - return User(self._requester, response.json()) - - def add_observee(self, observee_id): - """ - Registers a user as being observed by the given user. - :calls: `PUT /api/v1/users/:user_id/observees/:observee_id \ - `_ + return self.get_files(**kwargs) - :param observee_id: The login id for the user to observe. - :type observee_id: int - :rtype: :class: `canvasapi.user.User` + def list_folders(self, **kwargs): """ + Returns the paginated list of all folders for the given user. This will be returned as a + flat list containing all subfolders as well. - response = self._requester.request( - "PUT", "users/{}/observees/{}".format(self.id, observee_id) - ) - return User(self._requester, response.json()) - - def remove_observee(self, observee_id): - """ - Unregisters a user as being observed by the given user. + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.user.User.get_folders` instead. - :calls: `DELETE /api/v1/users/:user_id/observees/:observee_id \ - `_ + :calls: `GET /api/v1/users/:user_id/folders \ + `_ - :param observee_id: The login id for the user to observe. - :type observee_id: int - :rtype: :class: `canvasapi.user.User` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.folder.Folder` """ - - response = self._requester.request( - "DELETE", "users/{}/observees/{}".format(self.id, observee_id) + warnings.warn( + "`list_folders` is being deprecated and will be removed in a " + "future version. Use `get_folders` instead.", + DeprecationWarning, ) - return User(self._requester, response.json()) - def create_content_migration(self, migration_type, **kwargs): + return self.get_folders(**kwargs) + + def list_observees(self, **kwargs): """ - Create a content migration. + List the users that the given user is observing - :calls: `POST /api/v1/users/:user_id/content_migrations \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.user.User.get_observees` instead. - :param migration_type: The migrator type to use in this migration - :type migration_type: str or :class:`canvasapi.content_migration.Migrator` + :calls: `GET /api/v1/users/:user_id/observees \ + `_ - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.user.User` """ - from canvasapi.content_migration import ContentMigration, Migrator - - if isinstance(migration_type, Migrator): - kwargs["migration_type"] = migration_type.type - elif isinstance(migration_type, string_types): - kwargs["migration_type"] = migration_type - else: - raise TypeError("Parameter migration_type must be of type Migrator or str") - - response = self._requester.request( - "POST", - "users/{}/content_migrations".format(self.id), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_observees` is being deprecated and will be removed in a " + "future version. Use `get_observees` instead", + DeprecationWarning, ) - response_json = response.json() - response_json.update({"user_id": self.id}) - - return ContentMigration(self._requester, response_json) + return self.get_observees(**kwargs) - def get_content_migration(self, content_migration, **kwargs): + def list_user_logins(self, **kwargs): """ - Retrive a content migration by its ID + Given a user ID, return that user's logins for the given account. - :calls: `GET /api/v1/users/:user_id/content_migrations/:id \ - `_ + .. warning:: + .. deprecated:: 0.10.0 + Use :func:`canvasapi.user.User.get_user_logins` instead. - :param content_migration: The object or ID of the content migration to retrieve. - :type content_migration: int, str or :class:`canvasapi.content_migration.ContentMigration` + :calls: `GET /api/v1/users/:user_id/logins \ + `_ - :rtype: :class:`canvasapi.content_migration.ContentMigration` + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.login.Login` """ - from canvasapi.content_migration import ContentMigration - - migration_id = obj_or_id( - content_migration, "content_migration", (ContentMigration,) - ) - - response = self._requester.request( - "GET", - "users/{}/content_migrations/{}".format(self.id, migration_id), - _kwargs=combine_kwargs(**kwargs), + warnings.warn( + "`list_user_logins` is being deprecated and will be removed in a future version." + " Use `get_user_logins` instead", + DeprecationWarning, ) - response_json = response.json() - response_json.update({"user_id": self.id}) - - return ContentMigration(self._requester, response_json) - - def get_content_migrations(self, **kwargs): - """ - List content migrations that the current account can view or manage. - - :calls: `GET /api/v1/users/:user_id/content_migrations/ \ - `_ + return self.get_user_logins(**kwargs) - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.ContentMigration` + def merge_into(self, destination_user): """ - from canvasapi.content_migration import ContentMigration - - return PaginatedList( - ContentMigration, - self._requester, - "GET", - "users/{}/content_migrations".format(self.id), - {"user_id": self.id}, - _kwargs=combine_kwargs(**kwargs), - ) + Merge this user into another user. - def get_migration_systems(self, **kwargs): - """ - Return a list of migration systems. + :calls: `PUT /api/v1/users/:id/merge_into/:destination_user_id \ + `_ - :calls: `GET /api/v1/users/:user_id/content_migrations/migrators \ - `_ + :param destination_user: The object or ID of the user to merge into. + :type destination_user: :class:`canvasapi.user.User` or int - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_migration.Migrator` + :rtype: :class:`canvasapi.user.User` """ - from canvasapi.content_migration import Migrator + dest_user_id = obj_or_id(destination_user, "destination_user", (User,)) - return PaginatedList( - Migrator, - self._requester, - "GET", - "users/{}/content_migrations/migrators".format(self.id), - _kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "PUT", "users/{}/merge_into/{}".format(self.id, dest_user_id) ) + super(User, self).set_attributes(response.json()) + return self - def get_content_exports(self, **kwargs): + def remove_observee(self, observee_id): """ - Return a paginated list of the past and pending content export jobs for a user. + Unregisters a user as being observed by the given user. - :calls: `GET /api/v1/users/:user_id/content_exports\ - `_ + :calls: `DELETE /api/v1/users/:user_id/observees/:observee_id \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.content_export.ContentExport` + :param observee_id: The login id for the user to observe. + :type observee_id: int + :rtype: :class: `canvasapi.user.User` """ - from canvasapi.content_export import ContentExport - return PaginatedList( - ContentExport, - self._requester, - "GET", - "users/{}/content_exports".format(self.id), - kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "DELETE", "users/{}/observees/{}".format(self.id, observee_id) ) + return User(self._requester, response.json()) - def get_content_export(self, content_export, **kwargs): + def show_observee(self, observee_id): """ - Return information about a single content export. - - :calls: `GET /api/v1/users/:user_id/content_exports/:id\ - `_ + Gets information about an observed user. - :param content_export: The object or ID of the content export to show. - :type content_export: int or :class:`canvasapi.content_export.ContentExport` + :calls: `GET /api/v1/users/:user_id/observees/:observee_id \ + `_ - :rtype: :class:`canvasapi.content_export.ContentExport` + :param observee_id: The login id for the user to observe. + :type observee_id: int + :rtype: :class: `canvasapi.user.User` """ - from canvasapi.content_export import ContentExport - - export_id = obj_or_id(content_export, "content_export", (ContentExport,)) response = self._requester.request( - "GET", - "users/{}/content_exports/{}".format(self.id, export_id), - _kwargs=combine_kwargs(**kwargs), + "GET", "users/{}/observees/{}".format(self.id, observee_id) ) + return User(self._requester, response.json()) - return ContentExport(self._requester, response.json()) - - def export_content(self, export_type, **kwargs): + def update_color(self, asset_string, hexcode): """ - Begin a content export job for a user. - - :calls: `POST /api/v1/users/:user_id/content_exports\ - `_ + Update a custom color for this user for a given context. - :param export_type: The type of content to export. - :type export_type: str + This allows colors for the calendar and elsewhere to be customized on a user basis. - :rtype: :class:`canvasapi.content_export.ContentExport` - """ - from canvasapi.content_export import ContentExport + The `asset_string` parameter should be in the format 'context_id', for example 'course_42'. + The `hexcode` parameter need not include the '#'. - kwargs["export_type"] = export_type + :calls: `PUT /api/v1/users/:id/colors/:asset_string \ + `_ + :param asset_string: The asset to modify the color for. + :type asset_string: str + :param hexcode: The hexcode of the color to use. + :type hexcode: str + :rtype: dict + """ response = self._requester.request( - "POST", - "users/{}/content_exports".format(self.id), - _kwargs=combine_kwargs(**kwargs), + "PUT", "users/{}/colors/{}".format(self.id, asset_string), hexcode=hexcode ) - return ContentExport(self._requester, response.json()) + return response.json() - def get_open_poll_sessions(self, **kwargs): + def update_settings(self, **kwargs): """ - Returns a paginated list of all opened poll sessions available to the current user. + Update this user's settings. - :calls: `GET /api/v1/poll_sessions/opened \ - `_ + :calls: `PUT /api/v1/users/:id/settings \ + `_ - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.poll_session.PollSession` + :rtype: dict """ - from canvasapi.poll_session import PollSession - - return PaginatedList( - PollSession, - self._requester, - "GET", - "poll_sessions/opened", - _root="poll_sessions", - _kwargs=combine_kwargs(**kwargs), + response = self._requester.request( + "PUT", "users/{}/settings".format(self.id), _kwargs=combine_kwargs(**kwargs) ) + return response.json() - def get_closed_poll_sessions(self, **kwargs): + def upload(self, file, **kwargs): """ - Returns a paginated list of all closed poll sessions available to the current user. + Upload a file for a user. - :calls: `GET /api/v1/poll_sessions/closed \ - `_ + NOTE: You *must* have authenticated with this user's API key to + upload on their behalf no matter what permissions the issuer of the + request has. - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of - :class:`canvasapi.poll_session.PollSession` - """ - from canvasapi.poll_session import PollSession + :calls: `POST /api/v1/users/:user_id/files \ + `_ - return PaginatedList( - PollSession, - self._requester, - "GET", - "poll_sessions/closed", - _root="poll_sessions", - _kwargs=combine_kwargs(**kwargs), - ) + :param file: The file or path of the file to upload. + :type file: file or str + :returns: True if the file uploaded successfully, False otherwise, \ + and the JSON response from the API. + :rtype: tuple + """ + return Uploader( + self._requester, "users/{}/files".format(self.id), file, **kwargs + ).start() @python_2_unicode_compatible diff --git a/scripts/alphabetic.py b/scripts/alphabetic.py new file mode 100644 index 00000000..9c66f29f --- /dev/null +++ b/scripts/alphabetic.py @@ -0,0 +1,91 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +import inspect +import operator +import os +import sys + +sys.path.append(os.path.join(sys.path[0], "..")) + +import canvasapi # noqa + + +def main(): + error_count = 0 + + for _, module in inspect.getmembers(canvasapi, inspect.ismodule): + # print(module.__name__) + for class_name, theclass in inspect.getmembers(module, inspect.isclass): + # Only process classes in this module + if inspect.getmodule(theclass).__name__ != module.__name__: + continue + + functions = list() + for func_name, func in inspect.getmembers(theclass, inspect.isfunction): + # Only add function if it is part of this class. + # Get function's class name from qualified name. + if func.__qualname__.split(".")[0] == class_name: + functions.append((func_name, inspect.getsourcelines(func)[1])) + + error_count += check_alphabetical( + functions, theclass.__module__, theclass.__name__ + ) + + return error_count + + +def check_alphabetical(methods, module_name, class_name): + """ + Verify that the methods are in alphabetical order + + :param methods: A list of tuples with the method name and line + number of each method. + :type methods: list + :param module_name: The name of the module being checked + :type module_name: str + + :returns: The number of mis-ordered methods found + :rtype int: + """ + prev_func = "" + prev_line = 0 + error_count = 0 + + methods = sorted(methods, key=operator.itemgetter(0)) + + for func_name, line_no in methods: + if line_no < prev_line: + if error_count == 0: + print("\n" + module_name + "." + class_name + "\n-----------") + + print( + ( + "{func_name} ({module_name}:{line_no}) came before " + "{prev_func} ({module_name}:{prev_line})" + ).format( + func_name=func_name, + line_no=line_no, + prev_func=prev_func, + prev_line=prev_line, + module_name=module_name, + ) + ) + error_count += 1 + + prev_func = func_name + prev_line = line_no + + return error_count + + +if __name__ == "__main__": + error_count = main() + if error_count: + print( + "\nFound {error_count} method(s) not in alphabetical order.".format( + error_count=error_count + ) + ) + else: + print("All methods are alphabetical!") + sys.exit(error_count > 0) diff --git a/scripts/run_black.sh b/scripts/run_black.sh index b3c1e96f..de5ab377 100755 --- a/scripts/run_black.sh +++ b/scripts/run_black.sh @@ -1,5 +1,5 @@ #!/bin/bash -set -ev +set -e PYTHON_VERSION=`python -c 'import sys; version=sys.version_info[:3]; print("{0}.{1}".format(*version))'` diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index 6b054aae..60e52843 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -5,3 +5,5 @@ coverage report coverage html flake8 canvasapi tests mdl . .github +./scripts/run_black.sh +python scripts/alphabetic.py From 77ce4cc3121820b012ced8b1c7896b6d983a3515 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Thu, 11 Jul 2019 10:47:51 -0400 Subject: [PATCH 09/65] Add black and alphabetical test to contributing guide --- .github/CONTRIBUTING.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 0ce3178f..587e43bc 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -213,6 +213,18 @@ We use `flake8` for linting: flake8 canvasapi tests ``` +We use `black` for auto-formatting. When you run the command below, `black` will automatically convert your code to our desired style. + +```sh +black canvasapi tests +``` + +We require methods to be in alphabetical order for ease of reading. Run this script to confirm order: + +```sh +python scripts/alphabetic.py +``` + ### Foolish consistency > A foolish consistency is the hobgoblin of little minds. -- Ralph Waldo Emerson From bc708e7f98e17a6adf53cf25bfcbd5fc7fec9bde Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Fri, 12 Jul 2019 12:18:14 -0400 Subject: [PATCH 10/65] add feature class, add get_features method to course --- canvasapi/course.py | 19 +++++++++++++++++++ canvasapi/feature.py | 11 +++++++++++ tests/fixtures/course.json | 17 +++++++++++++++++ tests/test_course.py | 10 ++++++++++ tests/test_feature.py | 25 +++++++++++++++++++++++++ 5 files changed, 82 insertions(+) create mode 100644 canvasapi/feature.py create mode 100644 tests/test_feature.py diff --git a/canvasapi/course.py b/canvasapi/course.py index 9e4d6873..e1f91f01 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -11,6 +11,7 @@ from canvasapi.grading_standard import GradingStandard from canvasapi.grading_period import GradingPeriod from canvasapi.exceptions import RequiredFieldMissing +from canvasapi.feature import Feature from canvasapi.folder import Folder from canvasapi.outcome_import import OutcomeImport from canvasapi.page import Page @@ -992,6 +993,24 @@ def get_external_tools(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_features(self, **kwargs): + """ + Lists all features of a course. + + :calls: `GET /api/v1/courses/:course_id/features \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.feature.Feature` + """ + return PaginatedList( + Feature, + self._requester, + "GET", + "courses/{}/features".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_file(self, file, **kwargs): """ Return the standard attachment json object for a file. diff --git a/canvasapi/feature.py b/canvasapi/feature.py new file mode 100644 index 00000000..c0fca43b --- /dev/null +++ b/canvasapi/feature.py @@ -0,0 +1,11 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +from six import python_2_unicode_compatible + +from canvasapi.canvas_object import CanvasObject + + +@python_2_unicode_compatible +class Feature(CanvasObject): + def __str__(self): + return "{} {}".format(self.display_name, self.applies_to) diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 8b0df0d3..36a16932 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1759,5 +1759,22 @@ "export_type": "d" }, "status_code": 200 + }, + "get_features": { + "method": "GET", + "endpoint": "courses/1/features", + "data": [ + { + "name": "feature_test", + "display_name": "Feature Test", + "applies_to": "Course" + }, + { + "name": "feature_second", + "display_name": "Feature Second", + "applies_to": "Course" + } + ], + "status_code": 200 } } diff --git a/tests/test_course.py b/tests/test_course.py index 44372110..b9402415 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -20,6 +20,7 @@ from canvasapi.exceptions import ResourceDoesNotExist, RequiredFieldMissing from canvasapi.external_feed import ExternalFeed from canvasapi.external_tool import ExternalTool +from canvasapi.feature import Feature from canvasapi.file import File from canvasapi.folder import Folder from canvasapi.grading_period import GradingPeriod @@ -1698,6 +1699,15 @@ def test_export_content(self, m): self.assertIsInstance(content_export, ContentExport) self.assertTrue(hasattr(content_export, "export_type")) + # get_features() + def test_get_features(self, m): + register_uris({"course": ["get_features"]}, m) + + features = self.course.get_features() + + self.assertIsInstance(features, PaginatedList) + self.assertIsInstance(features[0], Feature) + @requests_mock.Mocker() class TestCourseNickname(unittest.TestCase): diff --git a/tests/test_feature.py b/tests/test_feature.py new file mode 100644 index 00000000..8326675a --- /dev/null +++ b/tests/test_feature.py @@ -0,0 +1,25 @@ +from __future__ import absolute_import, division, print_function, unicode_literals +import unittest + +import requests_mock + +from canvasapi import Canvas +from tests import settings +from tests.util import register_uris + + +@requests_mock.Mocker() +class TestFeature(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + with requests_mock.Mocker() as m: + requires = {"course": ["get_by_id", "get_features"]} + register_uris(requires, m) + + self.course = self.canvas.get_course(1) + self.feature = self.course.get_features()[0] + + def test__str__(self, m): + string = str(self.feature) + self.assertIsInstance(string, str) From d15961f633b4c4e72ad0679b382bfe4f98931355 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Mon, 15 Jul 2019 10:56:18 -0400 Subject: [PATCH 11/65] add get_features method to account and user --- canvasapi/account.py | 21 ++++++++++++++++++++- canvasapi/user.py | 19 +++++++++++++++++++ tests/fixtures/account.json | 17 +++++++++++++++++ tests/fixtures/user.json | 17 +++++++++++++++++ tests/test_account.py | 10 ++++++++++ tests/test_user.py | 19 +++++++++++++++---- 6 files changed, 98 insertions(+), 5 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 11ed6015..992a7222 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -6,9 +6,10 @@ from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import CanvasException, RequiredFieldMissing +from canvasapi.feature import Feature from canvasapi.grading_standard import GradingStandard -from canvasapi.outcome_import import OutcomeImport from canvasapi.grading_period import GradingPeriod +from canvasapi.outcome_import import OutcomeImport from canvasapi.paginated_list import PaginatedList from canvasapi.rubric import Rubric from canvasapi.sis_import import SisImport @@ -965,6 +966,24 @@ def get_external_tools(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_features(self, **kwargs): + """ + Lists all of the features of an account. + + :calls: `GET /api/v1/accounts/:account_id/features \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.feature.Feature` + """ + return PaginatedList( + Feature, + self._requester, + "GET", + "accounts/{}/features".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_grading_periods(self, **kwargs): """ Return a list of grading periods for the associated account. diff --git a/canvasapi/user.py b/canvasapi/user.py index 400c1b2b..7beb5e89 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -6,6 +6,7 @@ from canvasapi.calendar_event import CalendarEvent from canvasapi.canvas_object import CanvasObject from canvasapi.communication_channel import CommunicationChannel +from canvasapi.feature import Feature from canvasapi.folder import Folder from canvasapi.paginated_list import PaginatedList from canvasapi.upload import Uploader @@ -422,6 +423,24 @@ def get_enrollments(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_features(self, **kwargs): + """ + Lists all of the features for this user. + + :calls: `GET /api/v1/users/:user_id/features \ + ` + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.feature.Feature` + """ + return PaginatedList( + Feature, + self._requester, + "GET", + "users/{}/features".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_file(self, file, **kwargs): """ Return the standard attachment json object for a file. diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 46fcc327..e818ff52 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -1525,5 +1525,22 @@ }, "workflow_state": "active" } + }, + "get_features": { + "method": "GET", + "endpoint": "accounts/1/features", + "data": [ + { + "name": "feature_one", + "display_name": "Feature One", + "applies_to": "Account" + }, + { + "name": "feature_two", + "display_name": "Feature Two", + "applies_to": "Account" + } + ], + "status_code": 200 } } diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json index 9e9b164f..fd98be6b 100644 --- a/tests/fixtures/user.json +++ b/tests/fixtures/user.json @@ -857,5 +857,22 @@ "export_type": "d" }, "status_code": 200 + }, + "get_features": { + "method": "GET", + "endpoint": "users/1/features", + "data": [ + { + "name": "feature_one", + "display_name": "Feature One", + "applies_to": "User" + }, + { + "name": "feature_two", + "display_name": "Feature Two", + "applies_to": "User" + } + ], + "status_code": 200 } } diff --git a/tests/test_account.py b/tests/test_account.py index 646af870..30b0db41 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -21,6 +21,7 @@ from canvasapi.enrollment_term import EnrollmentTerm from canvasapi.external_tool import ExternalTool from canvasapi.exceptions import CanvasException, RequiredFieldMissing +from canvasapi.feature import Feature from canvasapi.grading_period import GradingPeriod from canvasapi.grading_standard import GradingStandard from canvasapi.group import Group, GroupCategory @@ -1176,3 +1177,12 @@ def test_delete_grading_periods(self, m): ) self.assertTrue(self.account.delete_grading_period(1)) self.assertTrue(self.account.delete_grading_period(self.grading_period)) + + # get_features() + def test_get_features(self, m): + register_uris({"account": ["get_features"]}, m) + + features = self.account.get_features() + + self.assertIsInstance(features, PaginatedList) + self.assertIsInstance(features[0], Feature) diff --git a/tests/test_user.py b/tests/test_user.py index ef92ea75..efaa3f6a 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -10,15 +10,17 @@ from canvasapi.avatar import Avatar from canvasapi.calendar_event import CalendarEvent from canvasapi.communication_channel import CommunicationChannel +from canvasapi.content_export import ContentExport +from canvasapi.content_migration import ContentMigration, Migrator from canvasapi.course import Course +from canvasapi.enrollment import Enrollment +from canvasapi.feature import Feature from canvasapi.file import File from canvasapi.folder import Folder -from canvasapi.enrollment import Enrollment +from canvasapi.login import Login from canvasapi.page_view import PageView +from canvasapi.paginated_list import PaginatedList from canvasapi.user import User -from canvasapi.login import Login -from canvasapi.content_migration import ContentMigration, Migrator -from canvasapi.content_export import ContentExport from tests import settings from tests.util import cleanup_file, register_uris @@ -530,6 +532,15 @@ def test_export_content(self, m): self.assertIsInstance(content_export, ContentExport) self.assertTrue(hasattr(content_export, "export_type")) + # get_features() + def test_get_features(self, m): + register_uris({"user": ["get_features"]}, m) + + features = self.user.get_features() + + self.assertIsInstance(features, PaginatedList) + self.assertIsInstance(features[0], Feature) + @requests_mock.Mocker() class TestUserDisplay(unittest.TestCase): From 58ae9e297adfca55a271a6c386a86e201de8ac1d Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Mon, 15 Jul 2019 12:50:50 -0400 Subject: [PATCH 12/65] add get_enabled_features() to account, course and user --- canvasapi/account.py | 18 ++++++++++++++++++ canvasapi/course.py | 18 ++++++++++++++++++ canvasapi/user.py | 20 +++++++++++++++++++- tests/fixtures/account.json | 17 +++++++++++++++++ tests/fixtures/course.json | 17 +++++++++++++++++ tests/fixtures/user.json | 17 +++++++++++++++++ tests/test_account.py | 9 +++++++++ tests/test_course.py | 9 +++++++++ tests/test_user.py | 9 +++++++++ 9 files changed, 133 insertions(+), 1 deletion(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 992a7222..5db3fdcd 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -880,6 +880,24 @@ def get_department_level_statistics_with_given_term(self, term_id): ) return response.json() + def get_enabled_features(self, **kwargs): + """ + Lists all enabled features in an account. + + :calls: `GET /api/v1/accounts/:account_id/features/enabled \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.feature.Feature` + """ + return PaginatedList( + Feature, + self._requester, + "GET", + "accounts/{}/features/enabled".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_enrollment(self, enrollment, **kwargs): """ Get an enrollment object by ID. diff --git a/canvasapi/course.py b/canvasapi/course.py index e1f91f01..566ce4ab 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -889,6 +889,24 @@ def get_discussion_topics(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_enabled_features(self, **kwargs): + """ + Lists all enabled features in a course. + + :calls: `GET /api/v1/courses/:course_id/features/enabled \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.feature.Feature` + """ + return PaginatedList( + Feature, + self._requester, + "GET", + "courses/{}/features/enabled".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_enrollments(self, **kwargs): """ List all of the enrollments in this course. diff --git a/canvasapi/user.py b/canvasapi/user.py index 7beb5e89..e219df25 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -403,6 +403,24 @@ def get_courses(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_enabled_features(self, **kwargs): + """ + Lists all of the enabled features for a user. + + :calls: `GET /api/v1/users/:user_id/features/enabled \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of + :class:`canvasapi.feature.Feature` + """ + return PaginatedList( + Feature, + self._requester, + "GET", + "users/{}/features/enabled".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_enrollments(self, **kwargs): """ List all of the enrollments for this user. @@ -428,7 +446,7 @@ def get_features(self, **kwargs): Lists all of the features for this user. :calls: `GET /api/v1/users/:user_id/features \ - ` + `_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.feature.Feature` diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index e818ff52..ffc9db9e 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -1542,5 +1542,22 @@ } ], "status_code": 200 + }, + "get_enabled_features": { + "method": "GET", + "endpoint": "accounts/1/features/enabled", + "data": [ + { + "name": "feature_one", + "display_name": "Feature One", + "applies_to": "Account" + }, + { + "name": "feature_two", + "display_name": "Feature Two", + "applies_to": "Account" + } + ], + "status_code": 200 } } diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 36a16932..ed804f9f 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1776,5 +1776,22 @@ } ], "status_code": 200 + }, + "get_enabled_features": { + "method": "GET", + "endpoint": "courses/1/features/enabled", + "data": [ + { + "name": "feature_test", + "display_name": "Feature Test", + "applies_to": "Course" + }, + { + "name": "feature_second", + "display_name": "Feature Second", + "applies_to": "Course" + } + ], + "status_code": 200 } } diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json index fd98be6b..c70e466d 100644 --- a/tests/fixtures/user.json +++ b/tests/fixtures/user.json @@ -874,5 +874,22 @@ } ], "status_code": 200 + }, + "get_enabled_features": { + "method": "GET", + "endpoint": "users/1/features/enabled", + "data": [ + { + "name": "feature_one", + "display_name": "Feature One", + "applies_to": "User" + }, + { + "name": "feature_two", + "display_name": "Feature Two", + "applies_to": "User" + } + ], + "status_code": 200 } } diff --git a/tests/test_account.py b/tests/test_account.py index 30b0db41..f09aa5d4 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -1186,3 +1186,12 @@ def test_get_features(self, m): self.assertIsInstance(features, PaginatedList) self.assertIsInstance(features[0], Feature) + + # get_enabled_features() + def test_get_enabled_features(self, m): + register_uris({"account": ["get_enabled_features"]}, m) + + features = self.account.get_enabled_features() + + self.assertIsInstance(features, PaginatedList) + self.assertIsInstance(features[0], Feature) diff --git a/tests/test_course.py b/tests/test_course.py index b9402415..182425f5 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -1708,6 +1708,15 @@ def test_get_features(self, m): self.assertIsInstance(features, PaginatedList) self.assertIsInstance(features[0], Feature) + # get_enabled_features() + def test_get__enabled_features(self, m): + register_uris({"course": ["get_enabled_features"]}, m) + + enabled_features = self.course.get_enabled_features() + + self.assertIsInstance(enabled_features, PaginatedList) + self.assertIsInstance(enabled_features[0], Feature) + @requests_mock.Mocker() class TestCourseNickname(unittest.TestCase): diff --git a/tests/test_user.py b/tests/test_user.py index efaa3f6a..950f40a9 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -541,6 +541,15 @@ def test_get_features(self, m): self.assertIsInstance(features, PaginatedList) self.assertIsInstance(features[0], Feature) + # get_enabled_features() + def test_get_enabled_features(self, m): + register_uris({"user": ["get_enabled_features"]}, m) + + features = self.user.get_enabled_features() + + self.assertIsInstance(features, PaginatedList) + self.assertIsInstance(features[0], Feature) + @requests_mock.Mocker() class TestUserDisplay(unittest.TestCase): From 2aa3a2582372aa343e25842e3f1f993f8cd5b4ea Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Wed, 17 Jul 2019 10:53:41 -0400 Subject: [PATCH 13/65] Removed overzealous global enabling of DeprecationWarning. --- AUTHORS.md | 1 + CHANGELOG.md | 5 +++++ canvasapi/canvas.py | 3 --- canvasapi/course.py | 3 --- canvasapi/section.py | 2 -- tests/test_group.py | 2 ++ tests/test_outcome.py | 2 ++ tests/test_user.py | 2 ++ 8 files changed, 12 insertions(+), 8 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index 8469b681..5708dbb5 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -44,6 +44,7 @@ Patches and Suggestions - Philip Austin [@phaustin](https://github.com/phaustin) - Philip Carter [@phillyc](https://github.com/phillyc) - Ralph Baird [@rmanbaird](https://github.com/rmanbaird) +- [@Screeeech](https://github.com/Screeeech) - Sigurður Baldursson [@sigurdurb](https://github.com/sigurdurb) - Spencer Rogers [@spencer1248](https://github.com/spencer1248) - Stephen Woosley [@stephenwoosley](https://github.com/stephenwoosley) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cfcabda..acba9542 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +### General + +- Removed overzealous global enabling of `DeprecationWarning`. (Thanks, [@Screeeech](https://github.com/Screeeech)) + - *Note:* `DeprecationWarnings` are disabled by default, so you may need to run your code with `python -Wd` to see them. + ## [0.13.0] - 2019-07-08 ### New Endpoint Coverage diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py index 37aeaca7..ec235a71 100644 --- a/canvasapi/canvas.py +++ b/canvasapi/canvas.py @@ -17,9 +17,6 @@ from canvasapi.util import combine_kwargs, get_institution_url, obj_or_id -warnings.simplefilter("always", DeprecationWarning) - - class Canvas(object): """ The main class to be instantiated to provide access to Canvas's API. diff --git a/canvasapi/course.py b/canvasapi/course.py index 9e4d6873..fccd6874 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -30,9 +30,6 @@ from canvasapi.rubric import Rubric -warnings.simplefilter("always", DeprecationWarning) - - @python_2_unicode_compatible class Course(CanvasObject): def __str__(self): diff --git a/canvasapi/section.py b/canvasapi/section.py index 1e9d77d7..9d179930 100644 --- a/canvasapi/section.py +++ b/canvasapi/section.py @@ -9,8 +9,6 @@ from canvasapi.submission import GroupedSubmission, Submission from canvasapi.util import combine_kwargs, obj_or_id, normalize_bool -warnings.simplefilter("always", DeprecationWarning) - @python_2_unicode_compatible class Section(CanvasObject): diff --git a/tests/test_group.py b/tests/test_group.py index 672c6147..10f66173 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -26,6 +26,8 @@ @requests_mock.Mocker() class TestGroup(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: diff --git a/tests/test_outcome.py b/tests/test_outcome.py index 0f20a7d3..22b8fdc9 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -13,6 +13,8 @@ @requests_mock.Mocker() class TestOutcome(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: diff --git a/tests/test_user.py b/tests/test_user.py index ef92ea75..cea126ef 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -26,6 +26,8 @@ @requests_mock.Mocker() class TestUser(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: From 461a1232feab018bd8571b2275297d53e20bebb6 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Wed, 17 Jul 2019 11:44:07 -0400 Subject: [PATCH 14/65] Enable DeprecationWarning for more test cases --- tests/test_course.py | 2 ++ tests/test_page.py | 2 ++ tests/test_section.py | 2 ++ tests/test_submission.py | 2 ++ 4 files changed, 8 insertions(+) diff --git a/tests/test_course.py b/tests/test_course.py index 44372110..9f2480d7 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -45,6 +45,8 @@ @requests_mock.Mocker() class TestCourse(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: diff --git a/tests/test_page.py b/tests/test_page.py index e0699453..f7bbb3f7 100644 --- a/tests/test_page.py +++ b/tests/test_page.py @@ -15,6 +15,8 @@ @requests_mock.Mocker() class TestPage(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: diff --git a/tests/test_section.py b/tests/test_section.py index 140adc13..9dcada3a 100644 --- a/tests/test_section.py +++ b/tests/test_section.py @@ -18,6 +18,8 @@ @requests_mock.Mocker() class TestSection(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: diff --git a/tests/test_submission.py b/tests/test_submission.py index 9daa067a..ffe0731f 100644 --- a/tests/test_submission.py +++ b/tests/test_submission.py @@ -15,6 +15,8 @@ @requests_mock.Mocker() class TestSubmission(unittest.TestCase): def setUp(self): + warnings.simplefilter("always", DeprecationWarning) + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: From 0626995e576691d1aa4c0d0cc6ff348a3fc432e0 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Wed, 17 Jul 2019 14:32:11 -0400 Subject: [PATCH 15/65] Add obj_or_str function to util.py --- canvasapi/util.py | 30 ++++++++++++++++++++++++++++++ tests/test_util.py | 43 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/canvasapi/util.py b/canvasapi/util.py index 2c02beac..30fd1b2d 100644 --- a/canvasapi/util.py +++ b/canvasapi/util.py @@ -134,6 +134,36 @@ def obj_or_id(parameter, param_name, object_types): raise TypeError(message) +def obj_or_str(obj, attr, object_types): + """ + Accepts an object. If the object has the attribute, return the + corresponding string. Otherwise, throw an exception. + + :param obj: object + :param attr: str + :param object_types: tuple + :rtype: str + """ + try: + return text_type(getattr(obj, attr)) + except (AttributeError, TypeError): + if not isinstance(attr, string_types): + raise TypeError( + "Atttibute parameter {} must be of type string".format(attr) + ) + for obj_type in object_types: + if isinstance(obj, obj_type): + try: + return text_type(getattr(obj, attr)) + except AttributeError: + raise AttributeError("{} object does not have {} attribute").format( + obj, attr + ) + + obj_type_list = ",".join([obj_type.__name__ for obj_type in object_types]) + raise TypeError("Parameter {} must be of type {}.".format(obj, obj_type_list)) + + def get_institution_url(base_url): """ Clean up a given base URL. diff --git a/tests/test_util.py b/tests/test_util.py index 9d86b4b7..e10972ab 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -13,11 +13,12 @@ get_institution_url, is_multivalued, obj_or_id, + obj_or_str, file_or_path, normalize_bool, ) from itertools import chain -from six import integer_types, iterkeys, itervalues, iteritems, text_type +from six import integer_types, iterkeys, itervalues, iteritems, string_types, text_type from six.moves import zip from tests import settings from tests.util import cleanup_file, register_uris @@ -434,6 +435,46 @@ def test_obj_or_id_nonuser_self(self, m): with self.assertRaises(TypeError): obj_or_id("self", "user_id", (CourseNickname,)) + # obj_or_str() + def test_obj_or_str_obj_attr(self, m): + register_uris({"user": ["get_by_id"]}, m) + + user = self.canvas.get_user(1) + + user_name = obj_or_str(user, "name", (User,)) + + self.assertIsInstance(user_name, string_types) + self.assertEqual(user_name, "John Doe") + + def test_obj_or_str_obj_no_attr(self, m): + register_uris({"user": ["get_by_id"]}, m) + + user = self.canvas.get_user(1) + + with self.assertRaises(AttributeError): + obj_or_str(user, "display_name", (User,)) + + def test_obj_or_str_mult_obj(self, m): + register_uris({"user": ["get_by_id"]}, m) + + user = self.canvas.get_user(1) + + user_name = obj_or_str(user, "name", (CourseNickname, User)) + + self.assertIsInstance(user_name, string_types) + + def test_obj_or_str_invalid_attr_parameter(self, m): + register_uris({"user": ["get_by_id"]}, m) + + user = self.canvas.get_user(1) + + with self.assertRaises(TypeError): + obj_or_str(user, user, (User,)) + + def test_obj_or_str_invalid_obj_type(self, m): + with self.assertRaises(TypeError): + obj_or_str("user", "name", (User,)) + # get_institution_url() def test_get_institution_url(self, m): correct_url = "https://my.canvas.edu" From 9bafd0c3ab592ad07ac21b4f482415786e36b551 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Thu, 18 Jul 2019 11:03:02 -0400 Subject: [PATCH 16/65] add FeatureFlag class to feature --- canvasapi/feature.py | 8 ++++++++ tests/test_feature.py | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/canvasapi/feature.py b/canvasapi/feature.py index c0fca43b..eaa9d66d 100644 --- a/canvasapi/feature.py +++ b/canvasapi/feature.py @@ -9,3 +9,11 @@ class Feature(CanvasObject): def __str__(self): return "{} {}".format(self.display_name, self.applies_to) + + +@python_2_unicode_compatible +class FeatureFlag(CanvasObject): + def __str__(self): + return "{} {} {} {}".format( + self.context_type, self.context_id, self.feature, self.state + ) diff --git a/tests/test_feature.py b/tests/test_feature.py index 8326675a..b0be104b 100644 --- a/tests/test_feature.py +++ b/tests/test_feature.py @@ -20,6 +20,26 @@ def setUp(self): self.course = self.canvas.get_course(1) self.feature = self.course.get_features()[0] + # __str__() def test__str__(self, m): string = str(self.feature) self.assertIsInstance(string, str) + + +@requests_mock.Mocker() +class TestFeatureFlag(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + with requests_mock.Mocker() as m: + requires = {"course": ["get_by_id", "get_features", "get_feature_flag"]} + register_uris(requires, m) + + self.course = self.canvas.get_course(1) + self.feature = self.course.get_features()[0] + self.feature_flag = self.course.get_feature_flag(self.feature) + + # __Str__() + def test__str__(self, m): + string = str(self.feature_flag) + self.assertIsInstance(string, str) From b1b12707907ada05381cc24d09a0893ade1198ad Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Thu, 18 Jul 2019 11:07:24 -0400 Subject: [PATCH 17/65] add get_feature_flag() to course, account and user --- canvasapi/account.py | 25 +++++++++++++++++++++++-- canvasapi/course.py | 24 +++++++++++++++++++++++- canvasapi/user.py | 25 +++++++++++++++++++++++-- tests/fixtures/account.json | 17 ++++++++++++++--- tests/fixtures/course.json | 15 +++++++++++++-- tests/fixtures/user.json | 13 +++++++++++-- tests/test_account.py | 13 ++++++++++++- tests/test_course.py | 31 +++++++++++++++++++++---------- tests/test_user.py | 13 ++++++++++++- 9 files changed, 152 insertions(+), 24 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 5db3fdcd..726aa9d1 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -6,14 +6,14 @@ from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import CanvasException, RequiredFieldMissing -from canvasapi.feature import Feature +from canvasapi.feature import Feature, FeatureFlag from canvasapi.grading_standard import GradingStandard from canvasapi.grading_period import GradingPeriod from canvasapi.outcome_import import OutcomeImport from canvasapi.paginated_list import PaginatedList from canvasapi.rubric import Rubric from canvasapi.sis_import import SisImport -from canvasapi.util import combine_kwargs, file_or_path, obj_or_id +from canvasapi.util import combine_kwargs, file_or_path, obj_or_id, obj_or_str @python_2_unicode_compatible @@ -984,6 +984,27 @@ def get_external_tools(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_feature_flag(self, feature, **kwargs): + """ + Returns the feature flag that applies to the given account. + + :calls: `GET /api/v1/accounts/:account_id/features/flags/:feature \ + `_ + + :param feature: The object to retrieve. + :type feature: :class:`canvasapi.feature.Feature` + + :rtype: :class:`canvasapi.feature.FeatureFlag` + """ + feature_name = obj_or_str(feature, "name", (Feature,)) + + response = self._requester.request( + "GET", + "accounts/{}/features/flags/{}".format(self.id, feature_name), + _kwargs=combine_kwargs(**kwargs), + ) + return FeatureFlag(self._requester, response.json()) + def get_features(self, **kwargs): """ Lists all of the features of an account. diff --git a/canvasapi/course.py b/canvasapi/course.py index 566ce4ab..b0e346f2 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -11,7 +11,7 @@ from canvasapi.grading_standard import GradingStandard from canvasapi.grading_period import GradingPeriod from canvasapi.exceptions import RequiredFieldMissing -from canvasapi.feature import Feature +from canvasapi.feature import Feature, FeatureFlag from canvasapi.folder import Folder from canvasapi.outcome_import import OutcomeImport from canvasapi.page import Page @@ -26,6 +26,7 @@ is_multivalued, file_or_path, obj_or_id, + obj_or_str, normalize_bool, ) from canvasapi.rubric import Rubric @@ -1011,6 +1012,27 @@ def get_external_tools(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_feature_flag(self, feature, **kwargs): + """ + Return the feature flag that applies to given course. + + :calls: `GET /api/v1/courses/:course_id/features/flags/:feature \ + `_ + + :param feature: The object to retrieve. + :type feature: :class:`canvasapi.feature.Feature` + + :rtype: :class:`canvasapi.feature.FeatureFlag` + """ + feature_name = obj_or_str(feature, "name", (Feature,)) + + response = self._requester.request( + "GET", + "courses/{}/features/flags/{}".format(self.id, feature_name), + _kwargs=combine_kwargs(**kwargs), + ) + return FeatureFlag(self._requester, response.json()) + def get_features(self, **kwargs): """ Lists all features of a course. diff --git a/canvasapi/user.py b/canvasapi/user.py index e219df25..1c7c03f4 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -6,11 +6,11 @@ from canvasapi.calendar_event import CalendarEvent from canvasapi.canvas_object import CanvasObject from canvasapi.communication_channel import CommunicationChannel -from canvasapi.feature import Feature +from canvasapi.feature import Feature, FeatureFlag from canvasapi.folder import Folder from canvasapi.paginated_list import PaginatedList from canvasapi.upload import Uploader -from canvasapi.util import combine_kwargs, obj_or_id +from canvasapi.util import combine_kwargs, obj_or_id, obj_or_str @python_2_unicode_compatible @@ -441,6 +441,27 @@ def get_enrollments(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_feature_flag(self, feature, **kwargs): + """ + Returns the feature flag that applies to the given user. + + :calls: `GET /api/v1/users/:user_id/features/flags/:feature \ + `_ + + :param feature: The object to retrieve. + :type feature: :class:`canvasapi.feature.Feature` + + :rtype: :class:`canvasapi.feature.FeatureFlag` + """ + feature_name = obj_or_str(feature, "name", (Feature,)) + + response = self._requester.request( + "GET", + "users/{}/features/flags/{}".format(self.id, feature_name), + _kwargs=combine_kwargs(**kwargs), + ) + return FeatureFlag(self._requester, response.json()) + def get_features(self, **kwargs): """ Lists all of the features for this user. diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index ffc9db9e..dbf77d9b 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -1531,9 +1531,9 @@ "endpoint": "accounts/1/features", "data": [ { - "name": "feature_one", - "display_name": "Feature One", - "applies_to": "Account" + "name": "epub_export", + "display_name": "ePub Exporting", + "applies_to": "Course" }, { "name": "feature_two", @@ -1559,5 +1559,16 @@ } ], "status_code": 200 + }, + "get_feature_flag": { + "method": "GET", + "endpoint": "accounts/1/features/flags/epub_export", + "data": { + "feature": "epub_export", + "context_id": 1, + "context_type": "Account", + "state": "on" + }, + "status_code": 200 } } diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index ed804f9f..4a5be7f4 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1765,8 +1765,8 @@ "endpoint": "courses/1/features", "data": [ { - "name": "feature_test", - "display_name": "Feature Test", + "name": "epub_export", + "display_name": "ePub Exporting", "applies_to": "Course" }, { @@ -1793,5 +1793,16 @@ } ], "status_code": 200 + }, + "get_feature_flag": { + "method": "GET", + "endpoint": "courses/1/features/flags/epub_export", + "data": { + "feature": "epub_export", + "context_id": 1, + "context_type": "Account", + "state": "on" + }, + "status_code": 200 } } diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json index c70e466d..ad939425 100644 --- a/tests/fixtures/user.json +++ b/tests/fixtures/user.json @@ -863,8 +863,8 @@ "endpoint": "users/1/features", "data": [ { - "name": "feature_one", - "display_name": "Feature One", + "name": "high_contrast", + "display_name": "High Contrast UI", "applies_to": "User" }, { @@ -891,5 +891,14 @@ } ], "status_code": 200 + }, + "get_feature_flag": { + "method": "GET", + "endpoint": "users/1/features/flags/high_contrast", + "data": { + "feature": "high_contrast", + "state": "allowed" + }, + "status_code": 200 } } diff --git a/tests/test_account.py b/tests/test_account.py index f09aa5d4..072213ec 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -21,7 +21,7 @@ from canvasapi.enrollment_term import EnrollmentTerm from canvasapi.external_tool import ExternalTool from canvasapi.exceptions import CanvasException, RequiredFieldMissing -from canvasapi.feature import Feature +from canvasapi.feature import Feature, FeatureFlag from canvasapi.grading_period import GradingPeriod from canvasapi.grading_standard import GradingStandard from canvasapi.group import Group, GroupCategory @@ -1195,3 +1195,14 @@ def test_get_enabled_features(self, m): self.assertIsInstance(features, PaginatedList) self.assertIsInstance(features[0], Feature) + + # get_feature_flag() + def test_get_feature_flag(self, m): + register_uris({"account": ["get_features", "get_feature_flag"]}, m) + + feature = self.account.get_features()[0] + + feature_flag = self.account.get_feature_flag(feature) + + self.assertIsInstance(feature_flag, FeatureFlag) + self.assertEqual(feature_flag.feature, "epub_export") diff --git a/tests/test_course.py b/tests/test_course.py index 182425f5..925944e0 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -20,7 +20,7 @@ from canvasapi.exceptions import ResourceDoesNotExist, RequiredFieldMissing from canvasapi.external_feed import ExternalFeed from canvasapi.external_tool import ExternalTool -from canvasapi.feature import Feature +from canvasapi.feature import Feature, FeatureFlag from canvasapi.file import File from canvasapi.folder import Folder from canvasapi.grading_period import GradingPeriod @@ -1699,15 +1699,6 @@ def test_export_content(self, m): self.assertIsInstance(content_export, ContentExport) self.assertTrue(hasattr(content_export, "export_type")) - # get_features() - def test_get_features(self, m): - register_uris({"course": ["get_features"]}, m) - - features = self.course.get_features() - - self.assertIsInstance(features, PaginatedList) - self.assertIsInstance(features[0], Feature) - # get_enabled_features() def test_get__enabled_features(self, m): register_uris({"course": ["get_enabled_features"]}, m) @@ -1717,6 +1708,26 @@ def test_get__enabled_features(self, m): self.assertIsInstance(enabled_features, PaginatedList) self.assertIsInstance(enabled_features[0], Feature) + # get_feature_flag() + def test_get_feature_flag(self, m): + register_uris({"course": ["get_features", "get_feature_flag"]}, m) + + feature = self.course.get_features()[0] + + feature_flag = self.course.get_feature_flag(feature) + + self.assertIsInstance(feature_flag, FeatureFlag) + self.assertEqual(feature_flag.feature, "epub_export") + + # get_features() + def test_get_features(self, m): + register_uris({"course": ["get_features"]}, m) + + features = self.course.get_features() + + self.assertIsInstance(features, PaginatedList) + self.assertIsInstance(features[0], Feature) + @requests_mock.Mocker() class TestCourseNickname(unittest.TestCase): diff --git a/tests/test_user.py b/tests/test_user.py index 950f40a9..cecdaf2f 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -14,7 +14,7 @@ from canvasapi.content_migration import ContentMigration, Migrator from canvasapi.course import Course from canvasapi.enrollment import Enrollment -from canvasapi.feature import Feature +from canvasapi.feature import Feature, FeatureFlag from canvasapi.file import File from canvasapi.folder import Folder from canvasapi.login import Login @@ -550,6 +550,17 @@ def test_get_enabled_features(self, m): self.assertIsInstance(features, PaginatedList) self.assertIsInstance(features[0], Feature) + # get_feature_flag() + def test_get_feature_flag(self, m): + register_uris({"user": ["get_features", "get_feature_flag"]}, m) + + feature = self.user.get_features()[0] + + feature_flag = self.user.get_feature_flag(feature) + + self.assertIsInstance(feature_flag, FeatureFlag) + self.assertEqual(feature_flag.feature, "high_contrast") + @requests_mock.Mocker() class TestUserDisplay(unittest.TestCase): From 4ac9f42502f975f6291907aa692cfb3ebe6d3ea9 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Tue, 23 Jul 2019 12:46:51 -0400 Subject: [PATCH 18/65] Amend get_features() to pass in object id, add _parent_id() and _parent_type(), add set_feature flag() --- canvasapi/account.py | 3 ++ canvasapi/course.py | 31 +++++++++++++ canvasapi/feature.py | 61 ++++++++++++++++++++++++++ canvasapi/user.py | 3 ++ tests/fixtures/account.json | 15 ++++++- tests/fixtures/course.json | 15 ++++++- tests/fixtures/user.json | 9 ++++ tests/test_feature.py | 86 +++++++++++++++++++++++++++++++++---- 8 files changed, 211 insertions(+), 12 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 726aa9d1..1c234607 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -895,6 +895,7 @@ def get_enabled_features(self, **kwargs): self._requester, "GET", "accounts/{}/features/enabled".format(self.id), + {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1003,6 +1004,7 @@ def get_feature_flag(self, feature, **kwargs): "accounts/{}/features/flags/{}".format(self.id, feature_name), _kwargs=combine_kwargs(**kwargs), ) + return FeatureFlag(self._requester, response.json()) def get_features(self, **kwargs): @@ -1020,6 +1022,7 @@ def get_features(self, **kwargs): self._requester, "GET", "accounts/{}/features".format(self.id), + {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) diff --git a/canvasapi/course.py b/canvasapi/course.py index b0e346f2..4e0637b7 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -905,6 +905,7 @@ def get_enabled_features(self, **kwargs): self._requester, "GET", "courses/{}/features/enabled".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -1031,6 +1032,7 @@ def get_feature_flag(self, feature, **kwargs): "courses/{}/features/flags/{}".format(self.id, feature_name), _kwargs=combine_kwargs(**kwargs), ) + return FeatureFlag(self._requester, response.json()) def get_features(self, **kwargs): @@ -1048,6 +1050,7 @@ def get_features(self, **kwargs): self._requester, "GET", "courses/{}/features".format(self.id), + {"course_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -2329,6 +2332,34 @@ def reset(self): ) return Course(self._requester, response.json()) + # def set_feature_flag(self, feature, state, **kwargs): + # """ + # Set a feature flag for a given course. + + # :calls: `PUT /api/v1/courses/:course_id/features/flags/:feature \ + # `_ + + # :param feature: The feature to set + # :type feature: :class:`canvasapi.feature.Feature` + # :param state: The state of the feature. Allowed values: "off", "allowed", "on" + # :type state: string + + # :rtype: :class:`canvasapi.feature.FeatureFlag` + # """ + # feature_flag = self.course.get_feature_flag(feature) + + # # what happens if state isn't a valid string? just make a update_state()? + # feature_flag.state = state + + # feature_name = obj_or_str(feature, "name", (Feature,)) + + # response = self._requester.request( + # "PUT", + # "courses/{}/features/flags/{}".format(self.id, feature_name), + # _kwargs=combine_kwargs(**kwargs), + # ) + # return FeatureFlag(self._requester, response.json()) + def set_quiz_extensions(self, quiz_extensions, **kwargs): """ Set extensions for student all quiz submissions in a course. diff --git a/canvasapi/feature.py b/canvasapi/feature.py index eaa9d66d..7f189b12 100644 --- a/canvasapi/feature.py +++ b/canvasapi/feature.py @@ -3,6 +3,7 @@ from six import python_2_unicode_compatible from canvasapi.canvas_object import CanvasObject +from canvasapi.util import combine_kwargs, obj_or_str @python_2_unicode_compatible @@ -10,6 +11,43 @@ class Feature(CanvasObject): def __str__(self): return "{} {}".format(self.display_name, self.applies_to) + @property + def _parent_id(self): + """ + Return the id of the account, course or user that spawned this feature + + :rtype: int + """ + if hasattr(self, "account_id"): + return self.account_id + elif hasattr(self, "course_id"): + return self.course_id + elif hasattr(self, "user_id"): + return self.user_id + else: + raise ValueError( + "Feature Flag does not have account_id, course_id or user_id" + ) + + @property + def _parent_type(self): + """ + Return whether the feature with the feature was spawned from an account, + a course or a user. + + :rtype: str + """ + if hasattr(self, "account_id"): + return "account" + elif hasattr(self, "course_id"): + return "course" + elif hasattr(self, "user_id"): + return "user" + else: + raise ValueError( + "Feature Flag does not have account_id, course_id or user_id" + ) + @python_2_unicode_compatible class FeatureFlag(CanvasObject): @@ -17,3 +55,26 @@ def __str__(self): return "{} {} {} {}".format( self.context_type, self.context_id, self.feature, self.state ) + + def set_feature_flag(self, feature, **kwargs): + """ + Set a feature flag for a given account, course or user. + + :calls: `PUT /api/v1/courses/:course_id/features/flags/:feature \ + `_ + + :param feature: The feature object to set + :type feature: :class:`canvasapi.feature.Feature` + + :rtype: :class:`canvasapi.feature.FeatureFlag` + """ + feature_name = obj_or_str(feature, "name", (Feature,)) + + response = self._requester.request( + "PUT", + "{}s/{}/features/flags/{}".format( + feature._parent_type, feature._parent_id, feature_name + ), + _kwargs=combine_kwargs(**kwargs), + ) + return FeatureFlag(self._requester, response.json()) diff --git a/canvasapi/user.py b/canvasapi/user.py index 1c7c03f4..45618032 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -418,6 +418,7 @@ def get_enabled_features(self, **kwargs): self._requester, "GET", "users/{}/features/enabled".format(self.id), + {"user_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) @@ -460,6 +461,7 @@ def get_feature_flag(self, feature, **kwargs): "users/{}/features/flags/{}".format(self.id, feature_name), _kwargs=combine_kwargs(**kwargs), ) + return FeatureFlag(self._requester, response.json()) def get_features(self, **kwargs): @@ -477,6 +479,7 @@ def get_features(self, **kwargs): self._requester, "GET", "users/{}/features".format(self.id), + {"user_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index dbf77d9b..3fffa90c 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -1536,8 +1536,8 @@ "applies_to": "Course" }, { - "name": "feature_two", - "display_name": "Feature Two", + "name": "outcome_gradebook", + "display_name": "Learning Mastery Gradebook", "applies_to": "Account" } ], @@ -1570,5 +1570,16 @@ "state": "on" }, "status_code": 200 + }, + "set_feature_flag": { + "method": "PUT", + "endpoint": "accounts/1/features/flags/epub_export", + "data": { + "context_id": 1, + "context_type": "Account", + "feature": "epub_export", + "state": "on" + }, + "status_code": 200 } } diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 4a5be7f4..5990cd67 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1770,8 +1770,8 @@ "applies_to": "Course" }, { - "name": "feature_second", - "display_name": "Feature Second", + "name": "gradebook_list_students_by_sortable_name", + "display_name": "Gradebook - List Students by Sortable Name", "applies_to": "Course" } ], @@ -1804,5 +1804,16 @@ "state": "on" }, "status_code": 200 + }, + "set_feature_flag": { + "method": "PUT", + "endpoint": "courses/1/features/flags/epub_export", + "data": { + "context_id": 1, + "context_type": "Account", + "feature": "epub_export", + "state": "on" + }, + "status_code": 200 } } diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json index ad939425..47ff34b1 100644 --- a/tests/fixtures/user.json +++ b/tests/fixtures/user.json @@ -900,5 +900,14 @@ "state": "allowed" }, "status_code": 200 + }, + "set_feature_flag": { + "method": "PUT", + "endpoint": "users/1/features/flags/high_contrast", + "data": { + "feature": "high_contrast", + "state": "allowed" + }, + "status_code": 200 } } diff --git a/tests/test_feature.py b/tests/test_feature.py index b0be104b..24f8b68c 100644 --- a/tests/test_feature.py +++ b/tests/test_feature.py @@ -4,6 +4,7 @@ import requests_mock from canvasapi import Canvas +from canvasapi.feature import Feature, FeatureFlag from tests import settings from tests.util import register_uris @@ -14,17 +15,55 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = {"course": ["get_by_id", "get_features"]} + requires = { + "account": ["get_by_id", "get_features"], + "course": ["get_by_id", "get_features"], + "user": ["get_by_id", "get_features"], + } register_uris(requires, m) + self.account = self.canvas.get_account(1) self.course = self.canvas.get_course(1) - self.feature = self.course.get_features()[0] + self.user = self.canvas.get_user(1) + self.feature_account = self.account.get_features()[0] + self.feature_course = self.course.get_features()[0] + self.feature_user = self.user.get_features()[0] # __str__() def test__str__(self, m): - string = str(self.feature) + string = str(self.feature_course) self.assertIsInstance(string, str) + # _parent_id() + def test_parent_id_account(self, m): + self.assertEqual(self.feature_account._parent_id, 1) + + def test_parent_id_course(self, m): + self.assertEqual(self.feature_course._parent_id, 1) + + def test_parent_id_user(self, m): + self.assertEqual(self.feature_user._parent_id, 1) + + def test_parent_id_no_id(self, m): + feature = Feature(self.canvas._Canvas__requester, {"id": 1}) + with self.assertRaises(ValueError): + feature._parent_id + + # _parent_type() + def test_parent_type_account(self, m): + self.assertEqual(self.feature_account._parent_type, "account") + + def test_parent_type_course(self, m): + self.assertEqual(self.feature_course._parent_type, "course") + + def test_parent_type_user(self, m): + self.assertEqual(self.feature_user._parent_type, "user") + + def test_parent_type_no_id(self, m): + feature = Feature(self.canvas._Canvas__requester, {"id": 1}) + with self.assertRaises(ValueError): + feature._parent_type + @requests_mock.Mocker() class TestFeatureFlag(unittest.TestCase): @@ -32,14 +71,45 @@ def setUp(self): self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) with requests_mock.Mocker() as m: - requires = {"course": ["get_by_id", "get_features", "get_feature_flag"]} + requires = { + "account": ["get_by_id", "get_features", "get_feature_flag"], + "course": ["get_by_id", "get_features", "get_feature_flag"], + "user": ["get_by_id", "get_features", "get_feature_flag"], + } register_uris(requires, m) + self.account = self.canvas.get_account(1) self.course = self.canvas.get_course(1) - self.feature = self.course.get_features()[0] - self.feature_flag = self.course.get_feature_flag(self.feature) + self.user = self.canvas.get_user(1) + self.feature_account = self.account.get_features()[0] + self.feature_course = self.course.get_features()[0] + self.feature_user = self.user.get_features()[0] + self.feature_flag_account = self.account.get_feature_flag( + self.feature_account + ) + self.feature_flag_course = self.course.get_feature_flag(self.feature_course) + self.feature_flag_user = self.user.get_feature_flag(self.feature_user) - # __Str__() + # __str__() def test__str__(self, m): - string = str(self.feature_flag) + string = str(self.feature_flag_course) self.assertIsInstance(string, str) + + # set_feature_flag() + def test_set_feature_flag_account(self, m): + register_uris({"account": ["set_feature_flag"]}, m) + update_flag = self.feature_flag_account.set_feature_flag(self.feature_account) + + self.assertIsInstance(update_flag, FeatureFlag) + + def test_set_feature_flag_course(self, m): + register_uris({"course": ["set_feature_flag"]}, m) + update_flag = self.feature_flag_course.set_feature_flag(self.feature_course) + + self.assertIsInstance(update_flag, FeatureFlag) + + def test_set_feature_flag_user(self, m): + register_uris({"user": ["set_feature_flag"]}, m) + update_flag = self.feature_flag_user.set_feature_flag(self.feature_user) + + self.assertIsInstance(update_flag, FeatureFlag) From 4fca5bfcf83be7e60e7aba28448b30407667910a Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Tue, 23 Jul 2019 12:53:05 -0400 Subject: [PATCH 19/65] Fix format --- canvasapi/account.py | 1 - canvasapi/course.py | 29 ----------------------------- canvasapi/user.py | 1 - 3 files changed, 31 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 1c234607..9615074a 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1004,7 +1004,6 @@ def get_feature_flag(self, feature, **kwargs): "accounts/{}/features/flags/{}".format(self.id, feature_name), _kwargs=combine_kwargs(**kwargs), ) - return FeatureFlag(self._requester, response.json()) def get_features(self, **kwargs): diff --git a/canvasapi/course.py b/canvasapi/course.py index 4e0637b7..70a05f15 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -1032,7 +1032,6 @@ def get_feature_flag(self, feature, **kwargs): "courses/{}/features/flags/{}".format(self.id, feature_name), _kwargs=combine_kwargs(**kwargs), ) - return FeatureFlag(self._requester, response.json()) def get_features(self, **kwargs): @@ -2332,34 +2331,6 @@ def reset(self): ) return Course(self._requester, response.json()) - # def set_feature_flag(self, feature, state, **kwargs): - # """ - # Set a feature flag for a given course. - - # :calls: `PUT /api/v1/courses/:course_id/features/flags/:feature \ - # `_ - - # :param feature: The feature to set - # :type feature: :class:`canvasapi.feature.Feature` - # :param state: The state of the feature. Allowed values: "off", "allowed", "on" - # :type state: string - - # :rtype: :class:`canvasapi.feature.FeatureFlag` - # """ - # feature_flag = self.course.get_feature_flag(feature) - - # # what happens if state isn't a valid string? just make a update_state()? - # feature_flag.state = state - - # feature_name = obj_or_str(feature, "name", (Feature,)) - - # response = self._requester.request( - # "PUT", - # "courses/{}/features/flags/{}".format(self.id, feature_name), - # _kwargs=combine_kwargs(**kwargs), - # ) - # return FeatureFlag(self._requester, response.json()) - def set_quiz_extensions(self, quiz_extensions, **kwargs): """ Set extensions for student all quiz submissions in a course. diff --git a/canvasapi/user.py b/canvasapi/user.py index 45618032..09cc9ee2 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -461,7 +461,6 @@ def get_feature_flag(self, feature, **kwargs): "users/{}/features/flags/{}".format(self.id, feature_name), _kwargs=combine_kwargs(**kwargs), ) - return FeatureFlag(self._requester, response.json()) def get_features(self, **kwargs): From d8494a692dab4b80ec04f461dc39898840c4fe92 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Wed, 24 Jul 2019 11:02:10 -0400 Subject: [PATCH 20/65] Add delete() to feature. Fix format --- canvasapi/account.py | 2 +- canvasapi/course.py | 2 +- canvasapi/feature.py | 40 ++++++++++++++++++++++++++++++++++++- canvasapi/user.py | 2 +- tests/fixtures/account.json | 11 ++++++++++ tests/fixtures/course.json | 11 ++++++++++ tests/fixtures/user.json | 9 +++++++++ tests/test_feature.py | 19 ++++++++++++++++++ 8 files changed, 92 insertions(+), 4 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 9615074a..1b14310a 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -992,7 +992,7 @@ def get_feature_flag(self, feature, **kwargs): :calls: `GET /api/v1/accounts/:account_id/features/flags/:feature \ `_ - :param feature: The object to retrieve. + :param feature: The feature to retrieve. :type feature: :class:`canvasapi.feature.Feature` :rtype: :class:`canvasapi.feature.FeatureFlag` diff --git a/canvasapi/course.py b/canvasapi/course.py index 70a05f15..1a8e187b 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -1020,7 +1020,7 @@ def get_feature_flag(self, feature, **kwargs): :calls: `GET /api/v1/courses/:course_id/features/flags/:feature \ `_ - :param feature: The object to retrieve. + :param feature: The feature to retrieve. :type feature: :class:`canvasapi.feature.Feature` :rtype: :class:`canvasapi.feature.FeatureFlag` diff --git a/canvasapi/feature.py b/canvasapi/feature.py index 7f189b12..cb520ca0 100644 --- a/canvasapi/feature.py +++ b/canvasapi/feature.py @@ -56,12 +56,50 @@ def __str__(self): self.context_type, self.context_id, self.feature, self.state ) + def delete(self, feature, **kwargs): + """ + Remove a feature flag for a given account, course or user. + + :calls: `DELETE /api/v1/courses/:course_id/features/flags/:feature \ + `_ + + or `DELETE /api/v1/accounts/:account_id/features/flags/:feature \ + `_ + + or `DELETE /api/v1/users/:user_id/features/flags/:feature \ + `_ + + :rtype: :class:`canvasapi.feature.FeatureFlag` + """ + feature_name = obj_or_str(feature, "name", (Feature,)) + + response = self._requester.request( + "DELETE", + "{}s/{}/features/flags/{}".format( + feature._parent_type, feature._parent_id, feature_name + ), + _kwargs=combine_kwargs(**kwargs), + ) + return FeatureFlag(self._requester, response.json()) + def set_feature_flag(self, feature, **kwargs): """ Set a feature flag for a given account, course or user. :calls: `PUT /api/v1/courses/:course_id/features/flags/:feature \ - `_ + `_ + + or ` PUT /api/v1/accounts/:account_id/features/flags/:feature \ + `_ + + or ` PUT /api/v1/users/:user_id/features/flags/:feature \ + `_ :param feature: The feature object to set :type feature: :class:`canvasapi.feature.Feature` diff --git a/canvasapi/user.py b/canvasapi/user.py index 09cc9ee2..ae9844ee 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -449,7 +449,7 @@ def get_feature_flag(self, feature, **kwargs): :calls: `GET /api/v1/users/:user_id/features/flags/:feature \ `_ - :param feature: The object to retrieve. + :param feature: The feature to retrieve. :type feature: :class:`canvasapi.feature.Feature` :rtype: :class:`canvasapi.feature.FeatureFlag` diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 3fffa90c..f2b34415 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -1581,5 +1581,16 @@ "state": "on" }, "status_code": 200 + }, + "delete_feature_flag": { + "method": "DELETE", + "endpoint": "accounts/1/features/flags/epub_export", + "data": { + "context_id": 1, + "context_type": "Account", + "feature": "epub_export", + "state": "on" + }, + "status_code": 200 } } diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 5990cd67..9da7b051 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1815,5 +1815,16 @@ "state": "on" }, "status_code": 200 + }, + "delete_feature_flag": { + "method": "DELETE", + "endpoint": "courses/1/features/flags/epub_export", + "data": { + "context_id": 1, + "context_type": "Account", + "feature": "epub_export", + "state": "on" + }, + "status_code": 200 } } diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json index 47ff34b1..6c4129ac 100644 --- a/tests/fixtures/user.json +++ b/tests/fixtures/user.json @@ -909,5 +909,14 @@ "state": "allowed" }, "status_code": 200 + }, + "delete_feature_flag": { + "method": "DELETE", + "endpoint": "users/1/features/flags/high_contrast", + "data": { + "feature": "high_contrast", + "state": "allowed" + }, + "status_code": 200 } } diff --git a/tests/test_feature.py b/tests/test_feature.py index 24f8b68c..507bdbd5 100644 --- a/tests/test_feature.py +++ b/tests/test_feature.py @@ -95,6 +95,25 @@ def test__str__(self, m): string = str(self.feature_flag_course) self.assertIsInstance(string, str) + # delete() + def test_delete_account(self, m): + register_uris({"account": ["delete_feature_flag"]}, m) + delete_flag = self.feature_flag_account.delete(self.feature_account) + + self.assertIsInstance(delete_flag, FeatureFlag) + + def test_delete_course(self, m): + register_uris({"course": ["delete_feature_flag"]}, m) + delete_flag = self.feature_flag_course.delete(self.feature_course) + + self.assertIsInstance(delete_flag, FeatureFlag) + + def test_delete_user(self, m): + register_uris({"user": ["delete_feature_flag"]}, m) + delete_flag = self.feature_flag_user.delete(self.feature_user) + + self.assertIsInstance(delete_flag, FeatureFlag) + # set_feature_flag() def test_set_feature_flag_account(self, m): register_uris({"account": ["set_feature_flag"]}, m) From e08ba3fc712a5dfc9c45dc36aebbac0cf911733c Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Wed, 24 Jul 2019 12:17:01 -0400 Subject: [PATCH 21/65] add docs file --- docs/feature-ref.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/feature-ref.rst diff --git a/docs/feature-ref.rst b/docs/feature-ref.rst new file mode 100644 index 00000000..36627047 --- /dev/null +++ b/docs/feature-ref.rst @@ -0,0 +1,13 @@ +======= +Feature +======= + +.. autoclass:: canvasapi.feature.Feature + :members: + +=========== +FeatureFlag +=========== + +.. autoclass:: canvasapi.feature.FeatureFlag + :members: From 6128841247cb640ca7b5dcf292ff6fcea36f8f46 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Wed, 24 Jul 2019 12:26:39 -0400 Subject: [PATCH 22/65] Remove svn install of docutils in favor of the (finally) updated version on pypi. --- dev_requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev_requirements.txt b/dev_requirements.txt index 7b4a4e43..60d69848 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -1,6 +1,6 @@ -r tests_requirements.txt +docutils==0.15.1 pre-commit; python_version >= '3.6' Sphinx sphinx-rtd-theme -svn+https://svn.code.sf.net/p/docutils/code/trunk/docutils#egg=docutils From c6f233f513afffb710bbb86953fb97717d24467c Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Wed, 24 Jul 2019 12:46:27 -0400 Subject: [PATCH 23/65] add doc file to class-reference --- docs/class-reference.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/class-reference.rst b/docs/class-reference.rst index e4f6b21f..938a5180 100644 --- a/docs/class-reference.rst +++ b/docs/class-reference.rst @@ -25,6 +25,7 @@ Class Reference enrollment-term-ref external-tool-ref favorite-ref + feature-ref file-ref folder-ref grading-period-ref From 9a722cbcc5dc765b1f458b110ef1677b84055d1e Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Mon, 29 Jul 2019 13:35:06 -0400 Subject: [PATCH 24/65] add RubricAssociation class --- canvasapi/rubric.py | 6 ++++++ tests/test_rubric.py | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/canvasapi/rubric.py b/canvasapi/rubric.py index 4ff44abf..4b58436f 100644 --- a/canvasapi/rubric.py +++ b/canvasapi/rubric.py @@ -9,3 +9,9 @@ class Rubric(CanvasObject): def __str__(self): return "{} ({})".format(self.title, self.id) + + +@python_2_unicode_compatible +class RubricAssociation(CanvasObject): + def __str__(self): + return "{}, {}".format(self.id, self.association_type) diff --git a/tests/test_rubric.py b/tests/test_rubric.py index 285ee7c8..c1e49591 100644 --- a/tests/test_rubric.py +++ b/tests/test_rubric.py @@ -23,3 +23,22 @@ def setUp(self): def test__str__(self, m): string = str(self.rubric) self.assertIsInstance(string, str) + + +@requests_mock.Mocker() +class TestRubricAssociation(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + with requests_mock.Mocker() as m: + register_uris( + {"course": ["get_by_id", "create_rubric_with_association"]}, m + ) + + self.course = self.canvas.get_course(1) + self.rubric = self.course.create_rubric() + + # __str__() + def test__str__(self, m): + string = str(self.rubric["rubric_association"]) + self.assertIsInstance(string, str) From 36e9bc25dd924c439331aa53f9980d5791998a31 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Mon, 29 Jul 2019 13:46:51 -0400 Subject: [PATCH 25/65] add create_rubric() to course --- canvasapi/course.py | 36 ++++++++++++++++++++++++++++++- tests/fixtures/course.json | 44 ++++++++++++++++++++++++++++++++++++++ tests/test_course.py | 23 ++++++++++++++++++++ 3 files changed, 102 insertions(+), 1 deletion(-) diff --git a/canvasapi/course.py b/canvasapi/course.py index fccd6874..03a04010 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -18,6 +18,7 @@ from canvasapi.progress import Progress from canvasapi.quiz import QuizExtension from canvasapi.tab import Tab +from canvasapi.rubric import RubricAssociation, Rubric from canvasapi.submission import GroupedSubmission, Submission from canvasapi.upload import Uploader from canvasapi.util import ( @@ -27,7 +28,6 @@ obj_or_id, normalize_bool, ) -from canvasapi.rubric import Rubric @python_2_unicode_compatible @@ -430,6 +430,40 @@ def create_quiz(self, quiz, **kwargs): return Quiz(self._requester, quiz_json) + def create_rubric(self, **kwargs): + """ + Create a new rubric. + + :calls: `POST /api/v1/courses/:course_id/rubrics \ + `_ + + :returns: Returns a dictionary with rubric and rubric association. + :rtype: `dict` + """ + response = self._requester.request( + "POST", + "courses/{}/rubrics".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + dictionary = response.json() + + rubric_dict = {} + + if "rubric" in dictionary: + r_dict = dictionary["rubric"] + rubric = Rubric(self._requester, r_dict) + + rubric_dict = {"rubric": rubric} + + if "rubric_association" in dictionary: + ra_dict = dictionary["rubric_association"] + rubric_association = RubricAssociation(self._requester, ra_dict) + + rubric_dict.update({"rubric_association": rubric_association}) + + return rubric_dict + def delete(self): """ Permanently delete this course. diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 8b0df0d3..c6595e91 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1759,5 +1759,49 @@ "export_type": "d" }, "status_code": 200 + }, + "create_rubric": { + "method": "POST", + "endpoint": "courses/1/rubrics", + "data": { + "rubric": { + "id": 1, + "title": "Course Rubric 1", + "context_id": 1, + "context_type": "Course", + "points_possible": 10.0, + "reusable": false, + "read_only": true, + "free_form_critereon_comments": true, + "hide_score_total": true + } + }, + "status_code": 200 + }, + "create_rubric_with_association": { + "method": "POST", + "endpoint": "courses/1/rubrics", + "data": { + "rubric": { + "id": 1, + "title": "Course Rubric 1", + "context_id": 1, + "context_type": "Course", + "points_possible": 10.0, + "reusable": false, + "read_only": true, + "free_form_critereon_comments": true, + "hide_score_total": true + }, + "rubric_association": { + "id": 1, + "rubric_id": 1, + "association_id": 1, + "association_type": "Course", + "used_for_grading": true, + "hide_score_total": true + } + }, + "status_code": 200 } } diff --git a/tests/test_course.py b/tests/test_course.py index 9f2480d7..6aefd3ac 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -1700,6 +1700,29 @@ def test_export_content(self, m): self.assertIsInstance(content_export, ContentExport) self.assertTrue(hasattr(content_export, "export_type")) + # create_rubric() + def test_create_rubric_no_association(self, m): + register_uris({"course": ["create_rubric"]}, m) + + rubric = self.course.create_rubric() + + self.assertIsInstance(rubric, dict) + self.assertEqual(rubric["rubric"].title, "Course Rubric 1") + self.assertEqual(rubric["rubric"].id, 1) + + def test_create_rubric_with_association(self, m): + register_uris({"course": ["create_rubric_with_association"]}, m) + + rubric = self.course.create_rubric() + + self.assertIsInstance(rubric, dict) + self.assertEqual(rubric["rubric"].title, "Course Rubric 1") + self.assertEqual(rubric["rubric"].id, 1) + + self.assertEqual(rubric["rubric_association"].id, 1) + self.assertEqual(rubric["rubric_association"].rubric_id, 1) + self.assertEqual(rubric["rubric_association"].association_type, "Course") + @requests_mock.Mocker() class TestCourseNickname(unittest.TestCase): From 20461f3924d2ab55747aedbddcb54729518576b3 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Mon, 29 Jul 2019 13:47:27 -0400 Subject: [PATCH 26/65] add RubricAssociation to docs --- docs/rubric-ref.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/rubric-ref.rst b/docs/rubric-ref.rst index 87533326..b02aaa22 100644 --- a/docs/rubric-ref.rst +++ b/docs/rubric-ref.rst @@ -4,3 +4,10 @@ Rubric .. autoclass:: canvasapi.rubric.Rubric :members: + +================== +Rubric Association +================== + +.. autoclass:: canvasapi.rubric.RubricAssociation + :members: From 60e29a2ee6832d82be866f03e730a64cef246f2e Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 30 Jul 2019 07:31:14 -0400 Subject: [PATCH 27/65] Update docutils version --- dev_requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev_requirements.txt b/dev_requirements.txt index 60d69848..b500ff2b 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -1,6 +1,6 @@ -r tests_requirements.txt -docutils==0.15.1 +docutils==0.15.2 pre-commit; python_version >= '3.6' Sphinx sphinx-rtd-theme From 8580177e7cf23ff91f96d04c0de6981effde17ab Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 10:15:10 -0400 Subject: [PATCH 28/65] Created function for getting list of scopes, create scope object. --- canvasapi/account.py | 19 +++++++++++++++++++ canvasapi/scope.py | 10 ++++++++++ 2 files changed, 29 insertions(+) create mode 100644 canvasapi/scope.py diff --git a/canvasapi/account.py b/canvasapi/account.py index 11ed6015..7e9584c6 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1698,6 +1698,25 @@ def update_role(self, role, **kwargs): ) return Role(self._requester, response.json()) + def get_scopes(self, **kwargs): + """ + Retrieve a list of scopes. + + :calls: `GET /api/v1/accounts/:account_id/scopes \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.scope.Scope` + """ + from canvasapi.scope import Scope + + return PaginatedList( + Scope, + self._requester, + "GET", + "accounts/{}/scopes".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + @python_2_unicode_compatible class AccountNotification(CanvasObject): diff --git a/canvasapi/scope.py b/canvasapi/scope.py new file mode 100644 index 00000000..8d930320 --- /dev/null +++ b/canvasapi/scope.py @@ -0,0 +1,10 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +from six import python_2_unicode_compatible + +from canvasapi.canvas_object import CanvasObject + +@python_2_unicode_compatible +class Scope(CanvasObject): + def __str__(self): + return "{}".format(self.resource) \ No newline at end of file From 4988ec83998740b754d2c3f6482aeee2de4554d0 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 11:24:37 -0400 Subject: [PATCH 29/65] created test function for get_scopes and created fixtures for the test function. --- tests/fixtures/account.json | 25 +++++++++++++++++++++++++ tests/test_account.py | 9 +++++++++ 2 files changed, 34 insertions(+) diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 46fcc327..deaa8174 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -1195,6 +1195,31 @@ }, "status_code": 200 }, + "get_scopes": { + "method": "GET", + "endpoint": "accounts/1/scopes", + "data": [ + { + "controller": "users", + "action": "settings", + "verb": "PUT", + "path": "/api/v1/users/:id/settings", + "scope": "url:PUT|/api/v1/users/:id/settings", + "resource": "users", + "resource_name": "Users" + }, + { + "controller": "course_nicknames", + "action": "show", + "verb": "GET", + "path": "/api/v1/users/self/course_nicknames/:course_id", + "scope": "url:GET|/api/v1/users/self/course_nicknames/:course_id", + "resource": "users", + "resource_name": "Users" + } + ], + "status_code": 200 + }, "create_content_migration": { "method": "POST", "endpoint": "accounts/1/content_migrations", diff --git a/tests/test_account.py b/tests/test_account.py index 646af870..5a160a0d 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -1176,3 +1176,12 @@ def test_delete_grading_periods(self, m): ) self.assertTrue(self.account.delete_grading_period(1)) self.assertTrue(self.account.delete_grading_period(self.grading_period)) + + # get_scopes() + def test_get_scopes(self, m): + register_uris({"account": ["get_scopes"]}, m) + + scopes = self.account.get_scopes() + scope_list = [scope for scope in scopes] + + self.assertEqual(len(list(scopes)), 2) From 17cd98d4be31170d7acd483d514cae16b52fcb56 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 11:57:39 -0400 Subject: [PATCH 30/65] Finished writing the test method for get_scopes --- tests/test_account.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_account.py b/tests/test_account.py index 5a160a0d..e231560e 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -29,6 +29,7 @@ from canvasapi.outcome_import import OutcomeImport from canvasapi.paginated_list import PaginatedList from canvasapi.rubric import Rubric +from canvasapi.scope import Scope from canvasapi.sis_import import SisImport from canvasapi.user import User from canvasapi.content_migration import ContentMigration, Migrator @@ -1185,3 +1186,11 @@ def test_get_scopes(self, m): scope_list = [scope for scope in scopes] self.assertEqual(len(list(scopes)), 2) + self.assertTrue(isinstance(scopes, PaginatedList)) + self.assertTrue(isinstance(scope_list[0], Scope)) + + self.assertEqual(scope_list[0].resource, "users") + self.assertEqual(scope_list[1].resource, "users") + + self.assertEqual(scope_list[0].verb, "PUT") + self.assertEqual(scope_list[1].verb, "GET") From fb0de28d266a42de8b837a44df554b8081ad28ed Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 13:30:04 -0400 Subject: [PATCH 31/65] Created test scope class to test out the to str method of the scope class. Added documentation for scope class. --- canvasapi/account.py | 2 +- canvasapi/scope.py | 3 ++- docs/class-reference.rst | 1 + docs/scope-ref.rst | 6 ++++++ tests/test_scope.py | 24 ++++++++++++++++++++++++ 5 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 docs/scope-ref.rst create mode 100644 tests/test_scope.py diff --git a/canvasapi/account.py b/canvasapi/account.py index 7e9584c6..8726c067 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1700,7 +1700,7 @@ def update_role(self, role, **kwargs): def get_scopes(self, **kwargs): """ - Retrieve a list of scopes. + Retrieve a paginated list of scopes. :calls: `GET /api/v1/accounts/:account_id/scopes \ `_ diff --git a/canvasapi/scope.py b/canvasapi/scope.py index 8d930320..4b410fa5 100644 --- a/canvasapi/scope.py +++ b/canvasapi/scope.py @@ -4,7 +4,8 @@ from canvasapi.canvas_object import CanvasObject + @python_2_unicode_compatible class Scope(CanvasObject): def __str__(self): - return "{}".format(self.resource) \ No newline at end of file + return "{}".format(self.resource) diff --git a/docs/class-reference.rst b/docs/class-reference.rst index e4f6b21f..01215ed3 100644 --- a/docs/class-reference.rst +++ b/docs/class-reference.rst @@ -43,6 +43,7 @@ Class Reference quiz-ref quiz-group-ref rubric-ref + scope-ref section-ref submission-ref tab-ref diff --git a/docs/scope-ref.rst b/docs/scope-ref.rst new file mode 100644 index 00000000..ec8d23bf --- /dev/null +++ b/docs/scope-ref.rst @@ -0,0 +1,6 @@ +===== +Scope +===== + +.. autoclass:: canvasapi.scope.Scope + :members: diff --git a/tests/test_scope.py b/tests/test_scope.py new file mode 100644 index 00000000..c16c2fc3 --- /dev/null +++ b/tests/test_scope.py @@ -0,0 +1,24 @@ +from __future__ import absolute_import, division, print_function, unicode_literals +import unittest + +import requests_mock + +from canvasapi import Canvas +from canvasapi.exceptions import RequiredFieldMissing +from canvasapi.scope import Scope +from tests import settings + + +@requests_mock.Mocker() +class TestGradingPeriod(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + self.scope = Scope( + self.canvas._Canvas__requester, {"resource": "users", "verb": "PUT"} + ) + + def test_str(self, m): + + test_str = str(self.scope) + self.assertIsInstance(test_str, str) From 514c4fe247305197ba269e8622d44b838cdf9001 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 14:06:19 -0400 Subject: [PATCH 32/65] Created function for getting global notifications --- canvasapi/account.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/canvasapi/account.py b/canvasapi/account.py index 8726c067..d08815a0 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -114,6 +114,29 @@ def add_grading_standards(self, title, grading_scheme_entry, **kwargs): return GradingStandard(self._requester, response.json()) + def get_global_notification(self, notification, **kwargs): + """ + Returns a global notification for the current user. + + :calls: `GET /api/v1/accounts/:account_id/account_notifications/:id \ + `_ + + :param notification: The notification object or ID to close. + :type notification: :class:`canvasapi.account.AccountNotification` or int + + :rtype: :class:`canvasapi.account.AccountNotification` + """ + + notif_id = obj_or_id(notification, "notification", (AccountNotification,)) + + response = self._requester.request( + "GET", + "accounts/{}/account_notifications/{}".format( + self.id, notif_id), + ) + + return AccountNotification(self._requester, response_json()) + def close_notification_for_user(self, user, notification): """ If the user no long wants to see a notification, it can be From 280c092f35a04d84cc4b7a03a75e4dad9b0814aa Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 15:55:18 -0400 Subject: [PATCH 33/65] Finished testing get_global_notification method. --- canvasapi/account.py | 10 ++++------ tests/fixtures/account.json | 14 ++++++++++++++ tests/test_account.py | 11 +++++++++++ 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index d08815a0..9a2818a6 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -114,7 +114,7 @@ def add_grading_standards(self, title, grading_scheme_entry, **kwargs): return GradingStandard(self._requester, response.json()) - def get_global_notification(self, notification, **kwargs): + def get_global_notification(self, notification_id, **kwargs): """ Returns a global notification for the current user. @@ -127,15 +127,13 @@ def get_global_notification(self, notification, **kwargs): :rtype: :class:`canvasapi.account.AccountNotification` """ - notif_id = obj_or_id(notification, "notification", (AccountNotification,)) - response = self._requester.request( "GET", - "accounts/{}/account_notifications/{}".format( - self.id, notif_id), + "accounts/{}/account_notifications/{}".format(self.id, notification_id), + _kwargs=combine_kwargs(**kwargs), ) - return AccountNotification(self._requester, response_json()) + return AccountNotification(self._requester, response.json()) def close_notification_for_user(self, user, notification): """ diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index deaa8174..9f713eda 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -321,6 +321,20 @@ }, "status_code": 200 }, + "get_notification": { + "method": "GET", + "endpoint": "accounts/1/account_notifications/1", + "data":{ + "subject": "Attention Students", + "message": "This is a test of the notification system.", + "start_at": "2013-08-28T23:59:00-06:00", + "end_at": "2013-08-29T23:59:00-06:00", + "icon": "information", + "roles": ["StudentEnrollment"], + "role_ids": [1] + }, + "status_code": 200 + }, "get_grading_periods": { "method": "GET", "endpoint": "accounts/1/grading_periods", diff --git a/tests/test_account.py b/tests/test_account.py index e231560e..949a9181 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -55,6 +55,17 @@ def test__str__(self, m): string = str(self.account) self.assertIsInstance(string, str) + # get_global_notification() + def test_get_global_notification(self, m): + register_uris({"account": ["get_notification"]}, m) + + notif_id = 1 + notification = self.account.get_global_notification(notif_id) + + self.assertIsInstance(notification, AccountNotification) + self.assertTrue(hasattr(notification, "subject")) + self.assertEqual(notification.subject, "Attention Students") + # close_notification_for_user() def test_close_notification_for_user_id(self, m): register_uris({"account": ["close_notification"]}, m) From 29386f651d47c55f76135271961f180a725e466d Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 16:04:16 -0400 Subject: [PATCH 34/65] Fixed documentation for getting global notifications. --- canvasapi/account.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 9a2818a6..373b58b2 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -119,10 +119,10 @@ def get_global_notification(self, notification_id, **kwargs): Returns a global notification for the current user. :calls: `GET /api/v1/accounts/:account_id/account_notifications/:id \ - `_ + `_ - :param notification: The notification object or ID to close. - :type notification: :class:`canvasapi.account.AccountNotification` or int + :param notification_id: The notification ID of the desired notification.. + :type: int :rtype: :class:`canvasapi.account.AccountNotification` """ From aaf320462433e91e2b8538c8a0517f84371d47bb Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 8 Aug 2019 16:51:28 -0400 Subject: [PATCH 35/65] wrote update global notification function, test function, and fixture --- canvasapi/account.py | 34 ++++++++++++++++++++++++++++++++++ tests/fixtures/account.json | 11 +++++++++++ tests/test_account.py | 15 +++++++++++++++ 3 files changed, 60 insertions(+) diff --git a/canvasapi/account.py b/canvasapi/account.py index 373b58b2..93843c69 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -135,6 +135,40 @@ def get_global_notification(self, notification_id, **kwargs): return AccountNotification(self._requester, response.json()) + def update_global_notification(self, account_notification, notification_id, **kwargs): + """ + Updates a global notification. + + :calls: `PUT /api/v1/accounts/:account_id/account_notifications/:id \ + `_ + + :param notification_id: The notification ID of the desired notification. + :type: int + + :rtype: :class:`canvasapi.account.AccountNotification` + """ + required_key_list = ["subject", "message", "start_at", "end_at"] + required_keys_present = all( + (x in account_notification for x in required_key_list) + ) + + if isinstance(account_notification, dict) and required_keys_present: + kwargs["account_notification"] = account_notification + else: + raise RequiredFieldMissing( + ( + "account_notification must be a dictionary with keys " + "'subject', 'message', 'start_at', and 'end_at'." + ) + ) + + response = self._requester.request( + "PUT", + "accounts/{}/account_notifications/{}".format(self.id, notification_id), + _kwargs=combine_kwargs(**kwargs), + ) + return AccountNotification(self._requester, response.json()) + def close_notification_for_user(self, user, notification): """ If the user no long wants to see a notification, it can be diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 9f713eda..784b210e 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -665,6 +665,17 @@ "data": {}, "status_code": 200 }, + "update_notification": { + "method": "PUT", + "endpoint": "accounts/1/account_notifications/1", + "data": { + "subject": "subject", + "message": "Message", + "start_at": "2015-04-01T00:00:00Z", + "end_at": "2018-04-01T00:00:00Z" + }, + "status_code": 200 + }, "create_group_category": { "method": "POST", "endpoint": "accounts/1/group_categories", diff --git a/tests/test_account.py b/tests/test_account.py index 949a9181..63bd587f 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -77,6 +77,21 @@ def test_close_notification_for_user_id(self, m): self.assertIsInstance(closed_notif, AccountNotification) self.assertTrue(hasattr(closed_notif, "subject")) + # update_global_notification() + def test_update_global_notification(self, m): + register_uris({"account": ["update_notification"]}, m) + + notif_dict = { + "subject": "subject", + "message": "Message", + "start_at": "2015-04-01T00:00:00Z", + "end_at": "2018-04-01T00:00:00Z", + } + + updated_notif = self.account.update_global_notification(notif_dict, 1) + + self.assertIsInstance(updated_notif, AccountNotification) + def test_close_notification_for_user_obj(self, m): register_uris({"account": ["close_notification"]}, m) From 071ca717c7944e639e94a4358326d89ad90fb5be Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Fri, 9 Aug 2019 14:58:25 -0400 Subject: [PATCH 36/65] refactored update_notifications to work from inside the AccountNotifications class. Still needs to be tested. --- canvasapi/account.py | 76 ++++++++++++++++++++++++++++++++++++++++--- tests/test_account.py | 71 ++++++++++++++++++++++------------------ 2 files changed, 111 insertions(+), 36 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 93843c69..3e024fde 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -133,7 +133,10 @@ def get_global_notification(self, notification_id, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - return AccountNotification(self._requester, response.json()) + response_json = response.json() + response_json.update({"account_id": self.id}) + + return AccountNotification(self._requester, response_json) def update_global_notification(self, account_notification, notification_id, **kwargs): """ @@ -142,7 +145,10 @@ def update_global_notification(self, account_notification, notification_id, **kw :calls: `PUT /api/v1/accounts/:account_id/account_notifications/:id \ `_ - :param notification_id: The notification ID of the desired notification. + :param account_notification: The notification to update with. + :type account_notification: dict + + :param notification_id: The notification ID of the to be replaced notification. :type: int :rtype: :class:`canvasapi.account.AccountNotification` @@ -397,7 +403,11 @@ def create_notification(self, account_notification, **kwargs): "accounts/{}/account_notifications".format(self.id), _kwargs=combine_kwargs(**kwargs), ) - return AccountNotification(self._requester, response.json()) + + response_json = response.json() + response_json.update({"account_id": self.id}) + + return AccountNotification(self._requester, response_json) def create_role(self, label, **kwargs): """ @@ -1776,7 +1786,65 @@ def get_scopes(self, **kwargs): @python_2_unicode_compatible class AccountNotification(CanvasObject): def __str__(self): # pragma: no cover - return "{}".format(self.subject) + return "{} ({})".format(self.subject, self.id) + + def update_global_notification(self, account_notification, **kwargs): + """ + Updates a global notification. + + :calls: `PUT /api/v1/accounts/:account_id/account_notifications/:id \ + `_ + + :param account_notification: The notification to update with. + :type account_notification: dict + + :rtype: :class:`canvasapi.account.AccountNotification` + """ + required_key_list = ["subject", "message", "start_at", "end_at"] + required_keys_present = all( + (x in account_notification for x in required_key_list) + ) + + if isinstance(account_notification, dict) and required_keys_present: + kwargs["account_notification"] = account_notification + else: + raise RequiredFieldMissing( + ( + "account_notification must be a dictionary with keys " + "'subject', 'message', 'start_at', and 'end_at'." + ) + ) + + response = self._requester.request( + "PUT", + "accounts/{}/account_notifications/{}".format(self.account_id, self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + return AccountNotification(self._requester, response.json()) + + def close_notification_for_user(self, user, notification): + """ + If the user no long wants to see a notification, it can be + excused with this call. + + :calls: `DELETE /api/v1/accounts/:account_id/users/:user_id/account_notifications/:id \ + `_ + + :param user: The user object or ID to close the notificaton for. + :type user: :class:`canvasapi.user.User` or int + :param notification: The notification object or ID to close. + :type notification: :class:`canvasapi.account.AccountNotification` or int + + :rtype: :class:`canvasapi.account.AccountNotification` + """ + response = self._requester.request( + "DELETE", + "accounts/{}/account_notifications/{}".format( + self.account_id, self.id + ), + ) + return AccountNotification(self._requester, response.json()) @python_2_unicode_compatible diff --git a/tests/test_account.py b/tests/test_account.py index 63bd587f..49dccada 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -66,38 +66,6 @@ def test_get_global_notification(self, m): self.assertTrue(hasattr(notification, "subject")) self.assertEqual(notification.subject, "Attention Students") - # close_notification_for_user() - def test_close_notification_for_user_id(self, m): - register_uris({"account": ["close_notification"]}, m) - - user_id = self.user.id - notif_id = 1 - closed_notif = self.account.close_notification_for_user(user_id, notif_id) - - self.assertIsInstance(closed_notif, AccountNotification) - self.assertTrue(hasattr(closed_notif, "subject")) - - # update_global_notification() - def test_update_global_notification(self, m): - register_uris({"account": ["update_notification"]}, m) - - notif_dict = { - "subject": "subject", - "message": "Message", - "start_at": "2015-04-01T00:00:00Z", - "end_at": "2018-04-01T00:00:00Z", - } - - updated_notif = self.account.update_global_notification(notif_dict, 1) - - self.assertIsInstance(updated_notif, AccountNotification) - - def test_close_notification_for_user_obj(self, m): - register_uris({"account": ["close_notification"]}, m) - - notif_id = 1 - self.account.close_notification_for_user(self.user, notif_id) - # create_account() def test_create_account(self, m): register_uris({"account": ["create_2"]}, m) @@ -1220,3 +1188,42 @@ def test_get_scopes(self, m): self.assertEqual(scope_list[0].verb, "PUT") self.assertEqual(scope_list[1].verb, "GET") + + # close_notification + #def test_close_notification_for_user_id(self, m): + # register_uris({"account": ["close_notification"]}, m) +# + # user_id = self.user.id + # notif_id = 1 + # closed_notif = self.account.close_notification_for_user(user_id, notif_id) +# + # self.assertIsInstance(closed_notif, AccountNotification) + # self.assertTrue(hasattr(closed_notif, "subject")) + + # update_global_notification() + def test_update_global_notification(self, m): + register_uris({"account": ["update_notification"]}, m) + + self.AccountNotification = AccountNotification(self.canvas._Canvas__requester,{ + "subject": "", + "message": "", + "start_at": "", + "end_at": "", + "id": 1, + "account_id": 1, + }) + + notif = AccountNotification(self.canvas._Canvas__requester,{ + "subject": "subject", + "message": "Message", + "start_at": "2015-04-01T00:00:00Z", + "end_at": "2018-04-01T00:00:00Z", + "id": 1, + "account_id": 1, + }) + + updated_notif = self.AccountNotification.update_global_notification(notif) + + self.assertIsInstance(updated_notif, AccountNotification) + self.assertTrue(hasattr(updated_notif, "subject")) + self.assertEqual(updated_notif.subject, "subject") \ No newline at end of file From 4866c7e1e4135b135bbbf5b42958b3c14c185b40 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 10:53:18 -0400 Subject: [PATCH 37/65] Removed delete function from accountNotification type --- canvasapi/account.py | 27 +++------------------------ tests/test_account.py | 43 +++++++++++++++++++++++-------------------- 2 files changed, 26 insertions(+), 44 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 3e024fde..cb67c5c8 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -138,7 +138,9 @@ def get_global_notification(self, notification_id, **kwargs): return AccountNotification(self._requester, response_json) - def update_global_notification(self, account_notification, notification_id, **kwargs): + def update_global_notification( + self, account_notification, notification_id, **kwargs + ): """ Updates a global notification. @@ -1823,29 +1825,6 @@ def update_global_notification(self, account_notification, **kwargs): return AccountNotification(self._requester, response.json()) - def close_notification_for_user(self, user, notification): - """ - If the user no long wants to see a notification, it can be - excused with this call. - - :calls: `DELETE /api/v1/accounts/:account_id/users/:user_id/account_notifications/:id \ - `_ - - :param user: The user object or ID to close the notificaton for. - :type user: :class:`canvasapi.user.User` or int - :param notification: The notification object or ID to close. - :type notification: :class:`canvasapi.account.AccountNotification` or int - - :rtype: :class:`canvasapi.account.AccountNotification` - """ - response = self._requester.request( - "DELETE", - "accounts/{}/account_notifications/{}".format( - self.account_id, self.id - ), - ) - return AccountNotification(self._requester, response.json()) - @python_2_unicode_compatible class AccountReport(CanvasObject): diff --git a/tests/test_account.py b/tests/test_account.py index 49dccada..b0654805 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -1190,40 +1190,43 @@ def test_get_scopes(self, m): self.assertEqual(scope_list[1].verb, "GET") # close_notification - #def test_close_notification_for_user_id(self, m): - # register_uris({"account": ["close_notification"]}, m) -# - # user_id = self.user.id - # notif_id = 1 - # closed_notif = self.account.close_notification_for_user(user_id, notif_id) -# - # self.assertIsInstance(closed_notif, AccountNotification) - # self.assertTrue(hasattr(closed_notif, "subject")) + def test_close_notification_for_user_id(self, m): + register_uris({"account": ["close_notification"]}, m) + + user_id = self.user.id + notif_id = 1 + closed_notif = self.account.close_notification_for_user(user_id, notif_id) + + self.assertIsInstance(closed_notif, AccountNotification) + self.assertTrue(hasattr(closed_notif, "subject")) # update_global_notification() def test_update_global_notification(self, m): register_uris({"account": ["update_notification"]}, m) - self.AccountNotification = AccountNotification(self.canvas._Canvas__requester,{ - "subject": "", - "message": "", - "start_at": "", - "end_at": "", - "id": 1, - "account_id": 1, - }) + self.AccountNotification = AccountNotification( + self.canvas._Canvas__requester, + { + "subject": "", + "message": "", + "start_at": "", + "end_at": "", + "id": 1, + "account_id": 1, + }, + ) - notif = AccountNotification(self.canvas._Canvas__requester,{ + notif = { "subject": "subject", "message": "Message", "start_at": "2015-04-01T00:00:00Z", "end_at": "2018-04-01T00:00:00Z", "id": 1, "account_id": 1, - }) + } updated_notif = self.AccountNotification.update_global_notification(notif) self.assertIsInstance(updated_notif, AccountNotification) self.assertTrue(hasattr(updated_notif, "subject")) - self.assertEqual(updated_notif.subject, "subject") \ No newline at end of file + self.assertEqual(updated_notif.subject, "subject") From aebe89c451900e175afebc5f108145ab56eb59e2 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 11:22:09 -0400 Subject: [PATCH 38/65] Finished testing update_notification function. Alphabetized account file. --- canvasapi/account.py | 125 +++++++++++++++--------------------------- tests/test_account.py | 21 +++++++ 2 files changed, 64 insertions(+), 82 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index cb67c5c8..bea7fcb7 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -114,69 +114,6 @@ def add_grading_standards(self, title, grading_scheme_entry, **kwargs): return GradingStandard(self._requester, response.json()) - def get_global_notification(self, notification_id, **kwargs): - """ - Returns a global notification for the current user. - - :calls: `GET /api/v1/accounts/:account_id/account_notifications/:id \ - `_ - - :param notification_id: The notification ID of the desired notification.. - :type: int - - :rtype: :class:`canvasapi.account.AccountNotification` - """ - - response = self._requester.request( - "GET", - "accounts/{}/account_notifications/{}".format(self.id, notification_id), - _kwargs=combine_kwargs(**kwargs), - ) - - response_json = response.json() - response_json.update({"account_id": self.id}) - - return AccountNotification(self._requester, response_json) - - def update_global_notification( - self, account_notification, notification_id, **kwargs - ): - """ - Updates a global notification. - - :calls: `PUT /api/v1/accounts/:account_id/account_notifications/:id \ - `_ - - :param account_notification: The notification to update with. - :type account_notification: dict - - :param notification_id: The notification ID of the to be replaced notification. - :type: int - - :rtype: :class:`canvasapi.account.AccountNotification` - """ - required_key_list = ["subject", "message", "start_at", "end_at"] - required_keys_present = all( - (x in account_notification for x in required_key_list) - ) - - if isinstance(account_notification, dict) and required_keys_present: - kwargs["account_notification"] = account_notification - else: - raise RequiredFieldMissing( - ( - "account_notification must be a dictionary with keys " - "'subject', 'message', 'start_at', and 'end_at'." - ) - ) - - response = self._requester.request( - "PUT", - "accounts/{}/account_notifications/{}".format(self.id, notification_id), - _kwargs=combine_kwargs(**kwargs), - ) - return AccountNotification(self._requester, response.json()) - def close_notification_for_user(self, user, notification): """ If the user no long wants to see a notification, it can be @@ -1032,6 +969,30 @@ def get_external_tools(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_global_notification(self, notification_id, **kwargs): + """ + Returns a global notification for the current user. + + :calls: `GET /api/v1/accounts/:account_id/account_notifications/:id \ + `_ + + :param notification_id: The notification ID of the desired notification.. + :type: int + + :rtype: :class:`canvasapi.account.AccountNotification` + """ + + response = self._requester.request( + "GET", + "accounts/{}/account_notifications/{}".format(self.id, notification_id), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({"account_id": self.id}) + + return AccountNotification(self._requester, response_json) + def get_grading_periods(self, **kwargs): """ Return a list of grading periods for the associated account. @@ -1331,6 +1292,25 @@ def get_rubrics(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) + def get_scopes(self, **kwargs): + """ + Retrieve a paginated list of scopes. + + :calls: `GET /api/v1/accounts/:account_id/scopes \ + `_ + + :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.scope.Scope` + """ + from canvasapi.scope import Scope + + return PaginatedList( + Scope, + self._requester, + "GET", + "accounts/{}/scopes".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + def get_single_grading_standard(self, grading_standard_id, **kwargs): """ Get a single grading standard from the account. @@ -1765,25 +1745,6 @@ def update_role(self, role, **kwargs): ) return Role(self._requester, response.json()) - def get_scopes(self, **kwargs): - """ - Retrieve a paginated list of scopes. - - :calls: `GET /api/v1/accounts/:account_id/scopes \ - `_ - - :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.scope.Scope` - """ - from canvasapi.scope import Scope - - return PaginatedList( - Scope, - self._requester, - "GET", - "accounts/{}/scopes".format(self.id), - _kwargs=combine_kwargs(**kwargs), - ) - @python_2_unicode_compatible class AccountNotification(CanvasObject): diff --git a/tests/test_account.py b/tests/test_account.py index b0654805..b698a820 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -1230,3 +1230,24 @@ def test_update_global_notification(self, m): self.assertIsInstance(updated_notif, AccountNotification) self.assertTrue(hasattr(updated_notif, "subject")) self.assertEqual(updated_notif.subject, "subject") + + def test_update_global_notification_missing_field(self, m): + register_uris({"account": ["update_notification"]}, m) + + self.AccountNotification = AccountNotification( + self.canvas._Canvas__requester, + { + "subject": "", + "message": "", + "start_at": "", + "end_at": "", + "id": 1, + "account_id": 1, + }, + ) + + notif = { + } + + with self.assertRaises(RequiredFieldMissing): + updated_notif = self.AccountNotification.update_global_notification(notif) From 54f56d37eb96da801c77407a1ea18996c21a6e1d Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 12:38:38 -0400 Subject: [PATCH 39/65] Wrote start report function and edited other account report functions to include account_ID. --- canvasapi/account.py | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index bea7fcb7..59887be8 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -348,6 +348,28 @@ def create_notification(self, account_notification, **kwargs): return AccountNotification(self._requester, response_json) + def create_report(self, report_type, **kwargs): + """ + Generates a report of a specific type for the account. + + :calls: `POST /api/v1/accounts/:account_id/reports/:report \ + `_ + + :param report_type: The type of report. + :type report_type: str + :rtype: :class:`canvasapi.account.AccountReport` + """ + response = self._requester.request( + "POST", + "accounts/{}/account_notifications/{}".format(self.id, report_type), + _kwargs=combine_kwargs(**kwargs), + ) + + response_json = response.json() + response_json.update({"account_id": self.id}) + + return AccountReport(self._requester, response_json) + def create_role(self, label, **kwargs): """ Create a new course-level or account-level role. @@ -1072,7 +1094,7 @@ def get_groups(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def get_index_of_reports(self, report_type): + def get_index_of_reports(self, report_type): """ Retrieve all reports that have been run for the account of a specific type. @@ -1089,6 +1111,8 @@ def get_index_of_reports(self, report_type): self._requester, "GET", "accounts/{}/reports/{}".format(self.id, report_type), + {"account_id": self.id}, + _root="reports", ) def get_migration_systems(self, **kwargs): @@ -1197,7 +1221,12 @@ def get_reports(self): :class:`canvasapi.account.AccountReport` """ return PaginatedList( - AccountReport, self._requester, "GET", "accounts/{}/reports".format(self.id) + AccountReport, + self._requester, + "GET", + "accounts/{}/reports".format(self.id), + {"account_id": self.id}, + _root="reports", ) def get_role(self, role): From c27da88fc635e59edb46522ce11640aaced4654c Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 13:11:58 -0400 Subject: [PATCH 40/65] Changed old report functions back because they weren't working with kwargs. Wrote fixtures for create report and created initial test report function. --- canvasapi/account.py | 6 +----- tests/fixtures/account.json | 8 ++++++++ tests/test_account.py | 9 +++++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 59887be8..a23f3dfa 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1094,7 +1094,7 @@ def get_groups(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - def get_index_of_reports(self, report_type): + def get_index_of_reports(self, report_type): """ Retrieve all reports that have been run for the account of a specific type. @@ -1111,8 +1111,6 @@ def get_index_of_reports(self, report_type): self._requester, "GET", "accounts/{}/reports/{}".format(self.id, report_type), - {"account_id": self.id}, - _root="reports", ) def get_migration_systems(self, **kwargs): @@ -1225,8 +1223,6 @@ def get_reports(self): self._requester, "GET", "accounts/{}/reports".format(self.id), - {"account_id": self.id}, - _root="reports", ) def get_role(self, role): diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 784b210e..ce843fe3 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -473,6 +473,14 @@ }, "status_code": 200 }, + "create_report":{ + "method": "GET", + "endpoint": "accounts/1/reports/zero_activity_csv", + "data": { + + }, + "status_code": 200 + }, "reports": { "method": "GET", "endpoint": "accounts/1/reports", diff --git a/tests/test_account.py b/tests/test_account.py index b698a820..a1428f94 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -205,6 +205,15 @@ def test_get_external_tools(self, m): self.assertIsInstance(tool_list[0], ExternalTool) self.assertEqual(len(tool_list), 4) + # create_report + def test_create_report(self, m): + required = {"account": ["create_report"]} + register_uris(required, m) + + report = self.account.create_report("zero_activity_csv") + + self.assertIsInstance(report, AccountReport) + # get_index_of_reports() def test_get_index_of_reports(self, m): required = {"account": ["report_index", "report_index_page_2"]} From 0bd07aa5742df5ea4ec1040d1ff6d635188e0920 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 13:48:45 -0400 Subject: [PATCH 41/65] finished create_reports function --- canvasapi/account.py | 7 ++----- tests/fixtures/account.json | 20 ++++++++++++++++++-- tests/test_account.py | 4 +++- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index a23f3dfa..4b6dbe27 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -361,14 +361,11 @@ def create_report(self, report_type, **kwargs): """ response = self._requester.request( "POST", - "accounts/{}/account_notifications/{}".format(self.id, report_type), + "accounts/{}/reports/{}".format(self.id, report_type), _kwargs=combine_kwargs(**kwargs), ) - response_json = response.json() - response_json.update({"account_id": self.id}) - - return AccountReport(self._requester, response_json) + return AccountReport(self._requester, response.json()) def create_role(self, label, **kwargs): """ diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index ce843fe3..b1db5868 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -474,10 +474,26 @@ "status_code": 200 }, "create_report":{ - "method": "GET", + "method": "POST", "endpoint": "accounts/1/reports/zero_activity_csv", "data": { - + "title": "Zero Activity", + "parameters": { + "enrollment_term_id": { + "required": false, + "description": "The canvas id of the term to get grades from" + }, + "start_at": { + "required": false, + "description": "The first date in the date range, the second date is the time the report is run." + }, + "course_id": { + "required": false, + "description": "The course to report on" + } + }, + "report": "zero_activity_csv", + "last_run": null }, "status_code": 200 }, diff --git a/tests/test_account.py b/tests/test_account.py index a1428f94..f75ec72b 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -213,6 +213,8 @@ def test_create_report(self, m): report = self.account.create_report("zero_activity_csv") self.assertIsInstance(report, AccountReport) + self.assertTrue(hasattr(report, "title")) + self.assertEqual(report.title, "Zero Activity") # get_index_of_reports() def test_get_index_of_reports(self, m): @@ -1259,4 +1261,4 @@ def test_update_global_notification_missing_field(self, m): } with self.assertRaises(RequiredFieldMissing): - updated_notif = self.AccountNotification.update_global_notification(notif) + self.AccountNotification.update_global_notification(notif) From 3d3fe388b2e6139c04457ddaa1e60eda2b5d082a Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 14:36:55 -0400 Subject: [PATCH 42/65] Added report parameter for creating reports --- canvasapi/account.py | 5 ++++- tests/test_account.py | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 4b6dbe27..ca734ba2 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -348,7 +348,7 @@ def create_notification(self, account_notification, **kwargs): return AccountNotification(self._requester, response_json) - def create_report(self, report_type, **kwargs): + def create_report(self, report, report_type, **kwargs): """ Generates a report of a specific type for the account. @@ -359,6 +359,9 @@ def create_report(self, report_type, **kwargs): :type report_type: str :rtype: :class:`canvasapi.account.AccountReport` """ + + kwargs["report"] = report + response = self._requester.request( "POST", "accounts/{}/reports/{}".format(self.id, report_type), diff --git a/tests/test_account.py b/tests/test_account.py index f75ec72b..7332bb45 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -210,7 +210,27 @@ def test_create_report(self, m): required = {"account": ["create_report"]} register_uris(required, m) - report = self.account.create_report("zero_activity_csv") + report_template = { + "title": "Zero Activity", + "parameters": { + "enrollment_term_id": { + "required": False, + "description": "The canvas id of the term to get grades from" + }, + "start_at": { + "required": False, + "description": "The first date in the date range, the second date is the time the report is run." + }, + "course_id": { + "required": False, + "description": "The course to report on" + } + }, + "report": "zero_activity_csv", + "last_run": "null" + } + + report = self.account.create_report(report_template, "zero_activity_csv") self.assertIsInstance(report, AccountReport) self.assertTrue(hasattr(report, "title")) From de676e9eb821830a6e953f3869d37b940f983a37 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 15:09:03 -0400 Subject: [PATCH 43/65] Finished testing get_report function. Tidyied up some minor errors due to line lengths in test_scope --- canvasapi/account.py | 28 ++++++++++++++++++++++++---- tests/fixtures/account.json | 24 ++++++++++++++++++++++++ tests/test_account.py | 24 +++++++++++++++++------- tests/test_scope.py | 1 - 4 files changed, 65 insertions(+), 12 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index ca734ba2..745a8c50 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1208,6 +1208,29 @@ def get_outcome_import_status(self, outcome_import, **kwargs): return OutcomeImport(self._requester, response_json) + def get_report(self, report_type, report_id, **kwargs): + """ + Return a list of reports for the current context. + + :calls: `GET /api/v1/accounts/:account_id/reports/:report/:id \ + `_ + + :param report_type: The type of the report which is being looked up. + :type report_type: :string: + + :param report_id: The id for the report which is being looked up. + :type report_id: :int: + + :rtype: :class:`canvasapi.account.AccountReport` + """ + response = self._requester.request( + "GET", + "accounts/{}/reports/{}/{}".format(self.id, report_type, report_id), + _kwargs=combine_kwargs(**kwargs), + ) + + return AccountReport(self._requester, response.json()) + def get_reports(self): """ Return a list of reports for the current context. @@ -1219,10 +1242,7 @@ def get_reports(self): :class:`canvasapi.account.AccountReport` """ return PaginatedList( - AccountReport, - self._requester, - "GET", - "accounts/{}/reports".format(self.id), + AccountReport, self._requester, "GET", "accounts/{}/reports".format(self.id) ) def get_role(self, role): diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index b1db5868..74a5b672 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -497,6 +497,30 @@ }, "status_code": 200 }, + "get_report":{ + "method": "GET", + "endpoint": "accounts/1/reports/zero_activity_csv/1", + "data":{ + "title": "Zero Activity", + "parameters": { + "enrollment_term_id": { + "required": false, + "description": "The canvas id of the term to get grades from" + }, + "start_at": { + "required": false, + "description": "The first date in the date range, the second date is the time the report is run." + }, + "course_id": { + "required": false, + "description": "The course to report on" + } + }, + "report": "zero_activity_csv", + "last_run": null + }, + "status_code": 200 + }, "reports": { "method": "GET", "endpoint": "accounts/1/reports", diff --git a/tests/test_account.py b/tests/test_account.py index 7332bb45..c76e50d4 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -215,19 +215,19 @@ def test_create_report(self, m): "parameters": { "enrollment_term_id": { "required": False, - "description": "The canvas id of the term to get grades from" + "description": "The canvas id of the term to get grades from", }, "start_at": { "required": False, - "description": "The first date in the date range, the second date is the time the report is run." + "description": "The first date in the date range", }, "course_id": { "required": False, - "description": "The course to report on" - } + "description": "The course to report on", + }, }, "report": "zero_activity_csv", - "last_run": "null" + "last_run": "null", } report = self.account.create_report(report_template, "zero_activity_csv") @@ -236,6 +236,17 @@ def test_create_report(self, m): self.assertTrue(hasattr(report, "title")) self.assertEqual(report.title, "Zero Activity") + # get_report + def test_get_report(self, m): + required = {"account": ["get_report"]} + register_uris(required, m) + + report = self.account.get_report("zero_activity_csv", 1) + + self.assertIsInstance(report, AccountReport) + self.assertTrue(hasattr(report, "title")) + self.assertEqual(report.title, "Zero Activity") + # get_index_of_reports() def test_get_index_of_reports(self, m): required = {"account": ["report_index", "report_index_page_2"]} @@ -1277,8 +1288,7 @@ def test_update_global_notification_missing_field(self, m): }, ) - notif = { - } + notif = {} with self.assertRaises(RequiredFieldMissing): self.AccountNotification.update_global_notification(notif) diff --git a/tests/test_scope.py b/tests/test_scope.py index c16c2fc3..83fd798b 100644 --- a/tests/test_scope.py +++ b/tests/test_scope.py @@ -4,7 +4,6 @@ import requests_mock from canvasapi import Canvas -from canvasapi.exceptions import RequiredFieldMissing from canvasapi.scope import Scope from tests import settings From 2ab0856c2c22ed530528b34e9b05b3cb015bc598 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 15:27:30 -0400 Subject: [PATCH 44/65] Added account ID to dictionary in order to use delete function more conveniently --- canvasapi/account.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 745a8c50..83102fbb 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -368,7 +368,10 @@ def create_report(self, report, report_type, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - return AccountReport(self._requester, response.json()) + response_json = response.json() + response_json.update({"account_id": self.id}) + + return AccountReport(self._requester, response_json) def create_role(self, label, **kwargs): """ @@ -1111,6 +1114,7 @@ def get_index_of_reports(self, report_type): self._requester, "GET", "accounts/{}/reports/{}".format(self.id, report_type), + {"account_id": self.id}, ) def get_migration_systems(self, **kwargs): @@ -1229,7 +1233,10 @@ def get_report(self, report_type, report_id, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - return AccountReport(self._requester, response.json()) + response_json = response.json() + response_json.update({"account_id": self.id}) + + return AccountReport(self._requester, response_json) def get_reports(self): """ @@ -1242,7 +1249,11 @@ def get_reports(self): :class:`canvasapi.account.AccountReport` """ return PaginatedList( - AccountReport, self._requester, "GET", "accounts/{}/reports".format(self.id) + AccountReport, + self._requester, + "GET", + "accounts/{}/reports".format(self.id), + {"account_id": self.id}, ) def get_role(self, role): From 41ac19ca7da2a56fd66d15f77d16dd1481adcc91 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 16:12:40 -0400 Subject: [PATCH 45/65] Wrote delete function and initial test function as well as fixtures. --- canvasapi/account.py | 17 +++++++++++++++ tests/fixtures/account.json | 42 +++++++++++++++++++++++++++++++++++++ tests/test_account.py | 25 ++++++++++++++++++++++ 3 files changed, 84 insertions(+) diff --git a/canvasapi/account.py b/canvasapi/account.py index 83102fbb..7a11a69b 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1848,6 +1848,23 @@ class AccountReport(CanvasObject): def __str__(self): # pragma: no cover return "{} ({})".format(self.report, self.id) + def delete_report(self, **kwargs): + """ + Delete this report. + + :calls: `DELETE /api/v1/accounts/:account_id/reports/:report/:id \ + `_ + + :rtype: :class:`canvasapi.account.AccountReport` + """ + response = self._requester.request( + "DELETE", + "accounts/{}/reports/{}/{}".format(self.account_id, self.report, self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + return AccountNotification(self._requester, response.json()) + @python_2_unicode_compatible class Role(CanvasObject): diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 74a5b672..2a0dfeee 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -497,6 +497,48 @@ }, "status_code": 200 }, + "delete_report":{ + "method": "DELETE", + "endpoint": "accounts/1/reports/zero_activity_csv/1", + "data": { + "id": 1, + "progress": 100, + "parameters": { + "extra_text": "Term: All Terms;" + }, + "current_line": 1, + "status": "deleted", + "report": "zero_activity_csv", + "created_at": "2019-08-13T15:23:15-04:00", + "started_at": "2019-08-13T15:23:17-04:00", + "ended_at": "2019-08-13T15:23:17-04:00", + "file_url": "https://canvas.dev.cdl.ucf.edu/accounts/1/files/1432/download", + "attachment": { + "id": 1432, + "uuid": "CCVh71fQEPsDqc4VOoGBr5llCbzAeLEpBcWcAe88", + "folder_id": 53, + "display_name": "zero_activity_csv_13_Aug_2019_420190813-16-ecpli.csv", + "filename": "zero_activity_csv_13_Aug_2019_120190813-16-8jbpun.csv", + "workflow_state": "processed", + "upload_status": "success", + "content-type": "text/csv", + "url": "https://canvas.dev.cdl.ucf.edu/files/1432/download?download_frd=1&verifier=CCVh71fQEPsDqc4VOoGBr5llCbzAeLEpBcWcAe88", + "size": 100, + "created_at": "2019-08-13T19:23:17Z", + "updated_at": "2019-08-13T19:23:17Z", + "unlock_at": null, + "locked": false, + "hidden": false, + "lock_at": null, + "hidden_for_user": false, + "thumbnail_url": null, + "modified_at": "2019-08-13T19:23:17Z", + "mime_class": "file", + "media_entry_id": null, + "locked_for_user": false + } + } + }, "get_report":{ "method": "GET", "endpoint": "accounts/1/reports/zero_activity_csv/1", diff --git a/tests/test_account.py b/tests/test_account.py index c76e50d4..c4449099 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -236,6 +236,31 @@ def test_create_report(self, m): self.assertTrue(hasattr(report, "title")) self.assertEqual(report.title, "Zero Activity") + # delete_report + def test_delete_report(self, m): + required = {"account": ["delete_report"]} + register_uris(required, m) + + self.account_report = AccountReport( + self.canvas._Canvas__requester, + {"title": "Zero Activity","parameters": { + "enrollment_term_id": { + "required": False, + "description": "The canvas id of the term to get grades from", + }, + "start_at": { + "required": False, + "description": "The first date in the date range", + }, + "course_id": { + "required": False, + "description": "The course to report on", + }, + },"report": "zero_activity_csv","last_run": "null","account_id": 1, "id": 1, }, + ) + + self.account_report.delete_report() + # get_report def test_get_report(self, m): required = {"account": ["get_report"]} From 3544b123c4fa03ad7f836f0523ab894c13c2ecdc Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 16:36:40 -0400 Subject: [PATCH 46/65] Fixed error where delete function was returning the wrong object. --- canvasapi/account.py | 2 +- tests/test_account.py | 39 +++++++++++++++++++++++++-------------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 7a11a69b..dfc6d7b9 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1863,7 +1863,7 @@ def delete_report(self, **kwargs): _kwargs=combine_kwargs(**kwargs), ) - return AccountNotification(self._requester, response.json()) + return AccountReport(self._requester, response.json()) @python_2_unicode_compatible diff --git a/tests/test_account.py b/tests/test_account.py index c4449099..8bf3c190 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -243,23 +243,34 @@ def test_delete_report(self, m): self.account_report = AccountReport( self.canvas._Canvas__requester, - {"title": "Zero Activity","parameters": { - "enrollment_term_id": { - "required": False, - "description": "The canvas id of the term to get grades from", - }, - "start_at": { - "required": False, - "description": "The first date in the date range", - }, - "course_id": { - "required": False, - "description": "The course to report on", + { + "title": "Zero Activity", + "parameters": { + "enrollment_term_id": { + "required": False, + "description": "The canvas id of the term to get grades from", + }, + "start_at": { + "required": False, + "description": "The first date in the date range", + }, + "course_id": { + "required": False, + "description": "The course to report on", + }, }, - },"report": "zero_activity_csv","last_run": "null","account_id": 1, "id": 1, }, + "report": "zero_activity_csv", + "last_run": "null", + "account_id": 1, + "id": 1, + }, ) - self.account_report.delete_report() + report = self.account_report.delete_report() + + self.assertIsInstance(report, AccountReport) + self.assertTrue(hasattr(report, "status")) + self.assertEqual(report.status, "deleted") # get_report def test_get_report(self, m): From 5b1a97bc1c77c0cd723cc5d3848c69100d90ea11 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Tue, 13 Aug 2019 17:07:27 -0400 Subject: [PATCH 47/65] Fixed some issues in the documentation for various endpoints --- canvasapi/account.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index dfc6d7b9..e315e540 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -355,6 +355,9 @@ def create_report(self, report, report_type, **kwargs): :calls: `POST /api/v1/accounts/:account_id/reports/:report \ `_ + :param report: The dictionary with which to build the report object. + :type report: dict + :param report_type: The type of report. :type report_type: str :rtype: :class:`canvasapi.account.AccountReport` @@ -1001,8 +1004,8 @@ def get_global_notification(self, notification_id, **kwargs): :calls: `GET /api/v1/accounts/:account_id/account_notifications/:id \ `_ - :param notification_id: The notification ID of the desired notification.. - :type: int + :param notification_id: The notification ID of the desired notification. + :type notification_id: `int` :rtype: :class:`canvasapi.account.AccountNotification` """ @@ -1214,16 +1217,16 @@ def get_outcome_import_status(self, outcome_import, **kwargs): def get_report(self, report_type, report_id, **kwargs): """ - Return a list of reports for the current context. + Return a report which corresponds to the given report type and ID. :calls: `GET /api/v1/accounts/:account_id/reports/:report/:id \ `_ :param report_type: The type of the report which is being looked up. - :type report_type: :string: + :type report_type: `string` :param report_id: The id for the report which is being looked up. - :type report_id: :int: + :type report_id: `int` :rtype: :class:`canvasapi.account.AccountReport` """ From 64714b844941b983cea364e9d99c14158f71b591 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 15 Aug 2019 12:54:32 -0400 Subject: [PATCH 48/65] Added collab class and method --- canvasapi/collaboration.py | 13 +++++++++++++ canvasapi/course.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 canvasapi/collaboration.py diff --git a/canvasapi/collaboration.py b/canvasapi/collaboration.py new file mode 100644 index 00000000..59fc2a71 --- /dev/null +++ b/canvasapi/collaboration.py @@ -0,0 +1,13 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +from six import python_2_unicode_compatible + +from canvasapi.canvas_object import CanvasObject +from canvasapi.exceptions import RequiredFieldMissing +from canvasapi.util import combine_kwargs + + +@python_2_unicode_compatible +class Collaboration(CanvasObject): + def __str__(self): + return "{} ({})".format(self.collaboration_type, self.id) diff --git a/canvasapi/course.py b/canvasapi/course.py index fccd6874..8e2e012c 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -6,6 +6,7 @@ from canvasapi.blueprint import BlueprintSubscription from canvasapi.canvas_object import CanvasObject +from canvasapi.collaboration import Collaboration from canvasapi.course_epub_export import CourseEpubExport from canvasapi.discussion_topic import DiscussionTopic from canvasapi.grading_standard import GradingStandard @@ -697,6 +698,23 @@ def get_blueprint(self, template="default", **kwargs): ) return BlueprintTemplate(self._requester, response.json()) + def get_gollaborations(self, **kwargs): + """ + Return a list of collaborations for a given course ID. + + :calls: `GET /api/v1/courses/:course_id/collaborations \ + `_ + + :rtype: :class:`canvasapi.collaboration.Collaboration` + """ + return PaginatedList( + Collaboration, + self._requester, + "GET", + "courses/{}/collaborations".format(self.id), + kwargs=combine_kwargs(**kwargs), + ) + def get_content_export(self, content_export, **kwargs): """ Return information about a single content export. From 1caafafce45836451f477e45db4bfea09df7d66f Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 15 Aug 2019 13:25:07 -0400 Subject: [PATCH 49/65] Removed report parameter from create_report and reworked function to pass parameters through kwargs. modified test_create_report to work accordingly. --- canvasapi/account.py | 8 ++------ tests/test_account.py | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index e315e540..6b74867d 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -348,23 +348,19 @@ def create_notification(self, account_notification, **kwargs): return AccountNotification(self._requester, response_json) - def create_report(self, report, report_type, **kwargs): + def create_report(self, report_type, **kwargs): """ Generates a report of a specific type for the account. :calls: `POST /api/v1/accounts/:account_id/reports/:report \ `_ - :param report: The dictionary with which to build the report object. - :type report: dict - :param report_type: The type of report. :type report_type: str + :rtype: :class:`canvasapi.account.AccountReport` """ - kwargs["report"] = report - response = self._requester.request( "POST", "accounts/{}/reports/{}".format(self.id, report_type), diff --git a/tests/test_account.py b/tests/test_account.py index 8bf3c190..68085e33 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -230,7 +230,7 @@ def test_create_report(self, m): "last_run": "null", } - report = self.account.create_report(report_template, "zero_activity_csv") + report = self.account.create_report("zero_activity_csv", parameters=report_template) self.assertIsInstance(report, AccountReport) self.assertTrue(hasattr(report, "title")) From 194617892fbe29abf2957bbdc02762bf70b7aa81 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 15 Aug 2019 13:38:17 -0400 Subject: [PATCH 50/65] Black formatted test_account create report function --- tests/test_account.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_account.py b/tests/test_account.py index 68085e33..8ecf7574 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -230,7 +230,9 @@ def test_create_report(self, m): "last_run": "null", } - report = self.account.create_report("zero_activity_csv", parameters=report_template) + report = self.account.create_report( + "zero_activity_csv", parameters=report_template + ) self.assertIsInstance(report, AccountReport) self.assertTrue(hasattr(report, "title")) From b18170b972f63fac37ea4fc0d818c3aa067478b8 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 15 Aug 2019 16:43:51 -0400 Subject: [PATCH 51/65] Covered list collaborations endpoint for course --- canvasapi/collaboration.py | 2 +- canvasapi/course.py | 7 ++++--- tests/fixtures/course.json | 41 ++++++++++++++++++++++++++++++++++++++ tests/test_course.py | 16 +++++++++++++++ 4 files changed, 62 insertions(+), 4 deletions(-) diff --git a/canvasapi/collaboration.py b/canvasapi/collaboration.py index 59fc2a71..0a0c913a 100644 --- a/canvasapi/collaboration.py +++ b/canvasapi/collaboration.py @@ -10,4 +10,4 @@ @python_2_unicode_compatible class Collaboration(CanvasObject): def __str__(self): - return "{} ({})".format(self.collaboration_type, self.id) + return "{} ({})".format(self.document_id, self.id) diff --git a/canvasapi/course.py b/canvasapi/course.py index 8e2e012c..462b304f 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -698,12 +698,12 @@ def get_blueprint(self, template="default", **kwargs): ) return BlueprintTemplate(self._requester, response.json()) - def get_gollaborations(self, **kwargs): + def get_collaborations(self, **kwargs): """ Return a list of collaborations for a given course ID. :calls: `GET /api/v1/courses/:course_id/collaborations \ - `_ + `_ :rtype: :class:`canvasapi.collaboration.Collaboration` """ @@ -712,8 +712,9 @@ def get_gollaborations(self, **kwargs): self._requester, "GET", "courses/{}/collaborations".format(self.id), + _root="collaborations", kwargs=combine_kwargs(**kwargs), - ) + ) def get_content_export(self, content_export, **kwargs): """ diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 8b0df0d3..be4c96d2 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1215,6 +1215,47 @@ }, "status_code": 200 }, + "get_collaborations": { + "method": "GET", + "endpoint": "courses/1/collaborations", + "data": { + "collaborations": [ + { + "id": 1, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89fef", + "user_id": 92, + "context_id": 77, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + }, + { + "id": 2, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89zzz", + "user_id": 93, + "context_id": 78, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + } + ] + }, + "status_code": 200 + }, "get_course_level_participation_data": { "method": "GET", "endpoint": "courses/1/analytics/activity", diff --git a/tests/test_course.py b/tests/test_course.py index 9f2480d7..a717f753 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -777,6 +777,22 @@ def test_create_external_tool(self, m): self.assertTrue(hasattr(response, "id")) self.assertEqual(response.id, 20) + # get_collaborations + def test_get_collaborations(self, m): + register_uris({"course": ["get_collaborations"]}, m) + + from canvasapi.collaboration import Collaboration + + collab_list = self.course.get_collaborations() + + self.assertIsInstance(collab_list, PaginatedList) + self.assertIsInstance(collab_list[0], Collaboration) + self.assertIsInstance(collab_list[1], Collaboration) + self.assertEqual(collab_list[0].id, 1) + self.assertEqual(collab_list[1].id, 2) + self.assertEqual(collab_list[0].document_id, "oinwoenfe8w8ef_onweufe89fef") + self.assertEqual(collab_list[1].document_id, "oinwoenfe8w8ef_onweufe89zzz") + # get_course_level_participation_data() def test_get_course_level_participation_data(self, m): register_uris({"course": ["get_course_level_participation_data"]}, m) From 7c4372eb31712c12bab3447b24ae154d83641e23 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Thu, 15 Aug 2019 17:04:27 -0400 Subject: [PATCH 52/65] Added get collaborations to the group endppoint --- canvasapi/group.py | 19 +++++++++++++++++ tests/fixtures/group.json | 41 +++++++++++++++++++++++++++++++++++++ tests/test_collaboration.py | 38 ++++++++++++++++++++++++++++++++++ tests/test_group.py | 17 +++++++++++++++ 4 files changed, 115 insertions(+) create mode 100644 tests/test_collaboration.py diff --git a/canvasapi/group.py b/canvasapi/group.py index aadf81a9..18045092 100644 --- a/canvasapi/group.py +++ b/canvasapi/group.py @@ -5,6 +5,7 @@ import warnings from canvasapi.canvas_object import CanvasObject +from canvasapi.collaboration import Collaboration from canvasapi.discussion_topic import DiscussionTopic from canvasapi.folder import Folder from canvasapi.exceptions import RequiredFieldMissing @@ -292,6 +293,24 @@ def get_assignment_override(self, assignment, **kwargs): return AssignmentOverride(self._requester, response_json) + def get_collaborations(self, **kwargs): + """ + Return a list of collaborations for a given course ID. + + :calls: `GET /api/v1/groups/:group_id/collaborations \ + `_ + + :rtype: :class:`canvasapi.collaboration.Collaboration` + """ + return PaginatedList( + Collaboration, + self._requester, + "GET", + "groups/{}/collaborations".format(self.id), + _root="collaborations", + kwargs=combine_kwargs(**kwargs), + ) + def get_content_export(self, content_export, **kwargs): """ Return information about a single content export. diff --git a/tests/fixtures/group.json b/tests/fixtures/group.json index 841602b3..73c5f1fc 100644 --- a/tests/fixtures/group.json +++ b/tests/fixtures/group.json @@ -814,6 +814,47 @@ ], "status_code": 200 }, + "get_collaborations": { + "method": "GET", + "endpoint": "groups/1/collaborations", + "data": { + "collaborations": [ + { + "id": 1, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89fef", + "user_id": 92, + "context_id": 77, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + }, + { + "id": 2, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89zzz", + "user_id": 93, + "context_id": 78, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + } + ] + }, + "status_code": 200 + }, "create_content_migration": { "method": "POST", "endpoint": "groups/1/content_migrations", diff --git a/tests/test_collaboration.py b/tests/test_collaboration.py new file mode 100644 index 00000000..27456abc --- /dev/null +++ b/tests/test_collaboration.py @@ -0,0 +1,38 @@ +from __future__ import absolute_import, division, print_function, unicode_literals +import unittest + +import requests_mock + +from canvasapi import Canvas +from canvasapi.collaboration import Collaboration +from tests import settings + + +@requests_mock.Mocker() +class TestCollaboration(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + self.collaboration = Collaboration( + self.canvas._Canvas__requester, + { + "id": 1, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89fef", + "user_id": 92, + "context_id": 77, + "context_type": "Course", + "url": "null", + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": "null", + "title": "null", + "type": "ExternalToolCollaboration", + "update_url": "null", + "user_name": "John Danger", + }, + ) + + def test_str(self, m): + test_str = str(self.collaboration) + self.assertIsInstance(test_str, str) diff --git a/tests/test_group.py b/tests/test_group.py index 10f66173..48c1ad35 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -16,6 +16,7 @@ from canvasapi.external_feed import ExternalFeed from canvasapi.file import File from canvasapi.folder import Folder +from canvasapi.paginated_list import PaginatedList from canvasapi.tab import Tab from canvasapi.content_migration import ContentMigration, Migrator from canvasapi.content_export import ContentExport @@ -523,6 +524,22 @@ def test_create_content_migration_bad_migration_type(self, m): with self.assertRaises(TypeError): self.group.create_content_migration(1) + # get_collaborations + def test_get_collaborations(self, m): + register_uris({"group": ["get_collaborations"]}, m) + + from canvasapi.collaboration import Collaboration + + collab_list = self.group.get_collaborations() + + self.assertIsInstance(collab_list, PaginatedList) + self.assertIsInstance(collab_list[0], Collaboration) + self.assertIsInstance(collab_list[1], Collaboration) + self.assertEqual(collab_list[0].id, 1) + self.assertEqual(collab_list[1].id, 2) + self.assertEqual(collab_list[0].document_id, "oinwoenfe8w8ef_onweufe89fef") + self.assertEqual(collab_list[1].document_id, "oinwoenfe8w8ef_onweufe89zzz") + # get_content_migration def test_get_content_migration(self, m): register_uris({"group": ["get_content_migration_single"]}, m) From 8206a7c7ddb64cf7efb9df26181545dda367f731 Mon Sep 17 00:00:00 2001 From: Catherine Abbruzzese Date: Fri, 16 Aug 2019 10:58:54 -0400 Subject: [PATCH 53/65] docstring fixes --- canvasapi/account.py | 4 ++-- canvasapi/course.py | 4 ++-- canvasapi/feature.py | 4 ++-- canvasapi/user.py | 4 ++-- canvasapi/util.py | 9 ++++++--- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 1b14310a..2f91d6b0 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -992,8 +992,8 @@ def get_feature_flag(self, feature, **kwargs): :calls: `GET /api/v1/accounts/:account_id/features/flags/:feature \ `_ - :param feature: The feature to retrieve. - :type feature: :class:`canvasapi.feature.Feature` + :param feature: The feature object or name of the feature to retrieve. + :type feature: :class:`canvasapi.feature.Feature` or str :rtype: :class:`canvasapi.feature.FeatureFlag` """ diff --git a/canvasapi/course.py b/canvasapi/course.py index bb631213..33f021a7 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -1017,8 +1017,8 @@ def get_feature_flag(self, feature, **kwargs): :calls: `GET /api/v1/courses/:course_id/features/flags/:feature \ `_ - :param feature: The feature to retrieve. - :type feature: :class:`canvasapi.feature.Feature` + :param feature: The feature object or name of the feature to retrieve. + :type feature: :class:`canvasapi.feature.Feature` or str :rtype: :class:`canvasapi.feature.FeatureFlag` """ diff --git a/canvasapi/feature.py b/canvasapi/feature.py index cb520ca0..f9d53b8b 100644 --- a/canvasapi/feature.py +++ b/canvasapi/feature.py @@ -93,11 +93,11 @@ def set_feature_flag(self, feature, **kwargs): `_ - or ` PUT /api/v1/accounts/:account_id/features/flags/:feature \ + or `PUT /api/v1/accounts/:account_id/features/flags/:feature \ `_ - or ` PUT /api/v1/users/:user_id/features/flags/:feature \ + or `PUT /api/v1/users/:user_id/features/flags/:feature \ `_ diff --git a/canvasapi/user.py b/canvasapi/user.py index ae9844ee..d560c724 100644 --- a/canvasapi/user.py +++ b/canvasapi/user.py @@ -449,8 +449,8 @@ def get_feature_flag(self, feature, **kwargs): :calls: `GET /api/v1/users/:user_id/features/flags/:feature \ `_ - :param feature: The feature to retrieve. - :type feature: :class:`canvasapi.feature.Feature` + :param feature: The feature object or name of the feature to retrieve. + :type feature: :class:`canvasapi.feature.Feature` or str :rtype: :class:`canvasapi.feature.FeatureFlag` """ diff --git a/canvasapi/util.py b/canvasapi/util.py index 30fd1b2d..976ecddc 100644 --- a/canvasapi/util.py +++ b/canvasapi/util.py @@ -139,9 +139,12 @@ def obj_or_str(obj, attr, object_types): Accepts an object. If the object has the attribute, return the corresponding string. Otherwise, throw an exception. - :param obj: object - :param attr: str - :param object_types: tuple + :param obj: object from which to retrieve attribute + :type obj: object + :param attr: name of the attribute to retrieve + :type attr: str + :param object_types: tuple containing the types of the object being passed in + :type object_types: tuple :rtype: str """ try: From e4fb86acccd7bc233f47ccff01d147079416d10b Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Fri, 16 Aug 2019 11:37:09 -0400 Subject: [PATCH 54/65] Added function for getting collaborators, added tests and fixtures --- canvasapi/collaboration.py | 26 ++++++++++++++++++++++++++ tests/fixtures/collaboration.json | 16 ++++++++++++++++ tests/test_collaboration.py | 29 ++++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 tests/fixtures/collaboration.json diff --git a/canvasapi/collaboration.py b/canvasapi/collaboration.py index 0a0c913a..6ae04dd1 100644 --- a/canvasapi/collaboration.py +++ b/canvasapi/collaboration.py @@ -3,11 +3,37 @@ from six import python_2_unicode_compatible from canvasapi.canvas_object import CanvasObject +from canvasapi.paginated_list import PaginatedList from canvasapi.exceptions import RequiredFieldMissing from canvasapi.util import combine_kwargs +from tests import settings @python_2_unicode_compatible class Collaboration(CanvasObject): def __str__(self): return "{} ({})".format(self.document_id, self.id) + + def get_collaborators(self, **kwargs): + """ + Return a list of collaborators for this collaboration. + + :calls: `GET /api/v1/collaborations/:id/members \ + `_ + + :rtype: :class:`canvasapi.collaboration.Collaborator` + """ + return PaginatedList( + Collaborator, + self._requester, + "GET", + "collaborations/{}/members".format(self.id), + _root="collaborators", + kwargs=combine_kwargs(**kwargs), + ) + + +@python_2_unicode_compatible +class Collaborator(CanvasObject): + def __str__(self): + return "{} ({})".format(self.name, self.id) diff --git a/tests/fixtures/collaboration.json b/tests/fixtures/collaboration.json new file mode 100644 index 00000000..bc2d1896 --- /dev/null +++ b/tests/fixtures/collaboration.json @@ -0,0 +1,16 @@ +{ + "get_collaborators": { + "method": "GET", + "endpoint": "collaborations/1/members", + "data": { + "collaborators": [ + { + "id": 12345, + "type": "user", + "name": "Don Draper" + } + ] +}, +"status_code": 200 +} +} \ No newline at end of file diff --git a/tests/test_collaboration.py b/tests/test_collaboration.py index 27456abc..c16d574e 100644 --- a/tests/test_collaboration.py +++ b/tests/test_collaboration.py @@ -4,8 +4,10 @@ import requests_mock from canvasapi import Canvas -from canvasapi.collaboration import Collaboration +from canvasapi.collaboration import Collaboration, Collaborator +from canvasapi.paginated_list import PaginatedList from tests import settings +from tests.util import cleanup_file, register_uris @requests_mock.Mocker() @@ -36,3 +38,28 @@ def setUp(self): def test_str(self, m): test_str = str(self.collaboration) self.assertIsInstance(test_str, str) + + def test_get_collaborators(self, m): + register_uris({"collaboration": ["get_collaborators"]}, m) + + collaborator_list = self.collaboration.get_collaborators() + + self.assertIsInstance(collaborator_list, PaginatedList) + + +@requests_mock.Mocker() +class TestCollaborator(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + self.collaborator = Collaborator( + self.canvas._Canvas__requester, + { + "id": 12345, + "type": "user", + "name": "Don Draper" + }) + + def test_str(self, m): + test_str = str(self.collaborator) + self.assertIsInstance(test_str, str) From d625df32b1a7305f6f524965813f82318bc4260b Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Fri, 16 Aug 2019 12:13:05 -0400 Subject: [PATCH 55/65] added more tests for get collaborators. --- tests/test_collaboration.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_collaboration.py b/tests/test_collaboration.py index c16d574e..e75885b5 100644 --- a/tests/test_collaboration.py +++ b/tests/test_collaboration.py @@ -45,6 +45,9 @@ def test_get_collaborators(self, m): collaborator_list = self.collaboration.get_collaborators() self.assertIsInstance(collaborator_list, PaginatedList) + self.assertIsInstance(collaborator_list[0], Collaborator) + self.assertEqual(collaborator_list[0].id, 12345) + self.assertEqual(collaborator_list[0].name, "Don Draper") @requests_mock.Mocker() From c35344da4eed66933aaf9ffc6d05d06057cd4cf9 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Fri, 16 Aug 2019 12:58:11 -0400 Subject: [PATCH 56/65] Addressed changes requested by thetwam --- canvasapi/account.py | 6 ++-- tests/fixtures/account.json | 12 ++++---- tests/test_account.py | 57 +++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/canvasapi/account.py b/canvasapi/account.py index 6b74867d..1e1b2e5f 100644 --- a/canvasapi/account.py +++ b/canvasapi/account.py @@ -1803,7 +1803,7 @@ def update_role(self, role, **kwargs): @python_2_unicode_compatible class AccountNotification(CanvasObject): - def __str__(self): # pragma: no cover + def __str__(self): return "{} ({})".format(self.subject, self.id) def update_global_notification(self, account_notification, **kwargs): @@ -1820,7 +1820,7 @@ def update_global_notification(self, account_notification, **kwargs): """ required_key_list = ["subject", "message", "start_at", "end_at"] required_keys_present = all( - (x in account_notification for x in required_key_list) + x in account_notification for x in required_key_list ) if isinstance(account_notification, dict) and required_keys_present: @@ -1844,7 +1844,7 @@ def update_global_notification(self, account_notification, **kwargs): @python_2_unicode_compatible class AccountReport(CanvasObject): - def __str__(self): # pragma: no cover + def __str__(self): return "{} ({})".format(self.report, self.id) def delete_report(self, **kwargs): diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index 2a0dfeee..27a5bcfe 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -512,17 +512,17 @@ "created_at": "2019-08-13T15:23:15-04:00", "started_at": "2019-08-13T15:23:17-04:00", "ended_at": "2019-08-13T15:23:17-04:00", - "file_url": "https://canvas.dev.cdl.ucf.edu/accounts/1/files/1432/download", + "file_url": "xxxxxxxxxxxxxxxxxxxxxxx", "attachment": { - "id": 1432, + "id": 1, "uuid": "CCVh71fQEPsDqc4VOoGBr5llCbzAeLEpBcWcAe88", - "folder_id": 53, - "display_name": "zero_activity_csv_13_Aug_2019_420190813-16-ecpli.csv", - "filename": "zero_activity_csv_13_Aug_2019_120190813-16-8jbpun.csv", + "folder_id": 1, + "display_name": "zero_activity_csv_xxxxxxxxxxxxxxxxxxxxxxx.csv", + "filename": "zero_activity_csv_xxxxxxxxxxxxxxxxxxxxxxx.csv", "workflow_state": "processed", "upload_status": "success", "content-type": "text/csv", - "url": "https://canvas.dev.cdl.ucf.edu/files/1432/download?download_frd=1&verifier=CCVh71fQEPsDqc4VOoGBr5llCbzAeLEpBcWcAe88", + "url": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "size": 100, "created_at": "2019-08-13T19:23:17Z", "updated_at": "2019-08-13T19:23:17Z", diff --git a/tests/test_account.py b/tests/test_account.py index 8ecf7574..0b10f705 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -1330,3 +1330,60 @@ def test_update_global_notification_missing_field(self, m): with self.assertRaises(RequiredFieldMissing): self.AccountNotification.update_global_notification(notif) + + +@requests_mock.Mocker() +class TestAccountNotification(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + self.AccountNotification = AccountNotification( + self.canvas._Canvas__requester, + { + "subject": "subject", + "message": "Message", + "start_at": "2015-04-01T00:00:00Z", + "end_at": "2018-04-01T00:00:00Z", + "id": 1, + "account_id": 1, + }, + ) + + # __str__() + def test__str__(self, m): + string = str(self.AccountNotification) + self.assertIsInstance(string, str) + + +@requests_mock.Mocker() +class TestAccountReport(unittest.TestCase): + def setUp(self): + self.canvas = Canvas(settings.BASE_URL, settings.API_KEY) + + self.AccountReport = AccountReport( + self.canvas._Canvas__requester, + { + "title": "Zero Activity", + "parameters": { + "enrollment_term_id": { + "required": False, + "description": "The canvas id of the term to get grades from", + }, + "start_at": { + "required": False, + "description": "The first date in the date range", + }, + "course_id": { + "required": False, + "description": "The course to report on", + }, + }, + "report": "zero_activity_csv", + "last_run": "null", + }, + ) + + # __str__() + def test__str__(self, m): + string = str(self.AccountReport) + self.assertIsInstance(string, str) From fcdea03a9c036380f62bde1bc193891ce2328065 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Fri, 16 Aug 2019 13:06:53 -0400 Subject: [PATCH 57/65] Added docs for collaborations and collaborators. --- docs/collaboration-ref.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/collaboration-ref.rst diff --git a/docs/collaboration-ref.rst b/docs/collaboration-ref.rst new file mode 100644 index 00000000..c6055957 --- /dev/null +++ b/docs/collaboration-ref.rst @@ -0,0 +1,14 @@ +============= +Collaboration +============= + +.. autoclass:: canvasapi.collaboration.Collaboration + :members: + + +============= +Collaborators +============= + +.. autoclass:: canvasapi.collaboration.Collaborators + :members: \ No newline at end of file From dfc25fb9b6c2d17506f8bd5b5b6af944f1d10064 Mon Sep 17 00:00:00 2001 From: Jose Silveti Date: Fri, 16 Aug 2019 13:14:20 -0400 Subject: [PATCH 58/65] Fixed unused imports and errors with the doctree --- canvasapi/collaboration.py | 2 -- docs/class-reference.rst | 1 + docs/collaboration-ref.rst | 8 ++++---- tests/test_collaboration.py | 9 +++------ 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/canvasapi/collaboration.py b/canvasapi/collaboration.py index 6ae04dd1..182c4ecd 100644 --- a/canvasapi/collaboration.py +++ b/canvasapi/collaboration.py @@ -4,9 +4,7 @@ from canvasapi.canvas_object import CanvasObject from canvasapi.paginated_list import PaginatedList -from canvasapi.exceptions import RequiredFieldMissing from canvasapi.util import combine_kwargs -from tests import settings @python_2_unicode_compatible diff --git a/docs/class-reference.rst b/docs/class-reference.rst index e4f6b21f..02009644 100644 --- a/docs/class-reference.rst +++ b/docs/class-reference.rst @@ -12,6 +12,7 @@ Class Reference blueprint-ref bookmark-ref calendar-event-ref + collaboration-ref communication-channel-ref content-export-ref content-migration-ref diff --git a/docs/collaboration-ref.rst b/docs/collaboration-ref.rst index c6055957..6402382f 100644 --- a/docs/collaboration-ref.rst +++ b/docs/collaboration-ref.rst @@ -6,9 +6,9 @@ Collaboration :members: -============= -Collaborators -============= +============ +Collaborator +============ -.. autoclass:: canvasapi.collaboration.Collaborators +.. autoclass:: canvasapi.collaboration.Collaborator :members: \ No newline at end of file diff --git a/tests/test_collaboration.py b/tests/test_collaboration.py index e75885b5..8b9ffaf0 100644 --- a/tests/test_collaboration.py +++ b/tests/test_collaboration.py @@ -7,7 +7,7 @@ from canvasapi.collaboration import Collaboration, Collaborator from canvasapi.paginated_list import PaginatedList from tests import settings -from tests.util import cleanup_file, register_uris +from tests.util import register_uris @requests_mock.Mocker() @@ -57,11 +57,8 @@ def setUp(self): self.collaborator = Collaborator( self.canvas._Canvas__requester, - { - "id": 12345, - "type": "user", - "name": "Don Draper" - }) + {"id": 12345, "type": "user", "name": "Don Draper"}, + ) def test_str(self, m): test_str = str(self.collaborator) From 9d7c3cc7912c77ecffad2c610ced9d6d3111b261 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 19 Aug 2019 10:50:09 -0400 Subject: [PATCH 59/65] Fix formatting issues --- tests/fixtures/collaboration.json | 6 +- tests/fixtures/course.json | 64 +++++----- tests/fixtures/group.json | 198 +++++++++++++++--------------- 3 files changed, 134 insertions(+), 134 deletions(-) diff --git a/tests/fixtures/collaboration.json b/tests/fixtures/collaboration.json index bc2d1896..4b63f9b4 100644 --- a/tests/fixtures/collaboration.json +++ b/tests/fixtures/collaboration.json @@ -10,7 +10,7 @@ "name": "Don Draper" } ] -}, -"status_code": 200 + }, + "status_code": 200 + } } -} \ No newline at end of file diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index ca97ad18..53b5e702 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1221,38 +1221,38 @@ "data": { "collaborations": [ { - "id": 1, - "collaboration_type": "Microsoft Office", - "document_id": "oinwoenfe8w8ef_onweufe89fef", - "user_id": 92, - "context_id": 77, - "context_type": "Course", - "url": null, - "created_at": "2012-06-01T00:00:00-06:00", - "updated_at": "2012-06-01T00:00:00-06:00", - "description": null, - "title": null, - "type": "ExternalToolCollaboration", - "update_url": null, - "user_name": "John Danger" - }, - { - "id": 2, - "collaboration_type": "Microsoft Office", - "document_id": "oinwoenfe8w8ef_onweufe89zzz", - "user_id": 93, - "context_id": 78, - "context_type": "Course", - "url": null, - "created_at": "2012-06-01T00:00:00-06:00", - "updated_at": "2012-06-01T00:00:00-06:00", - "description": null, - "title": null, - "type": "ExternalToolCollaboration", - "update_url": null, - "user_name": "John Danger" - } - ] + "id": 1, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89fef", + "user_id": 92, + "context_id": 77, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + }, + { + "id": 2, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89zzz", + "user_id": 93, + "context_id": 78, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + } + ] }, "status_code": 200 }, diff --git a/tests/fixtures/group.json b/tests/fixtures/group.json index 73c5f1fc..f34d68fd 100644 --- a/tests/fixtures/group.json +++ b/tests/fixtures/group.json @@ -44,16 +44,16 @@ "status_code": 200 }, "create_folder": { - "method": "POST", - "endpoint": "groups/1/folders", - "data": { - "id": 2, - "name": "Test String", - "locked": false, - "hidden": false - }, - "status_code": 200 - }, + "method": "POST", + "endpoint": "groups/1/folders", + "data": { + "id": 2, + "name": "Test String", + "locked": false, + "hidden": false + }, + "status_code": 200 + }, "create_page": { "method": "POST", "endpoint": "groups/1/pages", @@ -215,8 +215,8 @@ "data": { "upload_url": "https://example.com/api/v1/files/upload_response_upload_url", "upload_params": { - "some_param": "param123", - "a_different_param": "param456" + "some_param": "param123", + "a_different_param": "param456" } } }, @@ -601,17 +601,17 @@ "method": "POST", "endpoint": "group_categories/1/assign_unassigned_members", "data": { - "completion": 0, - "context_id": 20, - "context_type": "GroupCategory", - "created_at": "2013-07-05T10:57:48-06:00", - "id": 2, - "message": null, - "tag": "assign_unassigned_members", - "updated_at": "2013-07-05T10:57:48-06:00", - "user_id": null, - "workflow_state": "running", - "url": "http://localhost:3000/api/v1/progress/2" + "completion": 0, + "context_id": 20, + "context_type": "GroupCategory", + "created_at": "2013-07-05T10:57:48-06:00", + "id": 2, + "message": null, + "tag": "assign_unassigned_members", + "updated_at": "2013-07-05T10:57:48-06:00", + "user_id": null, + "workflow_state": "running", + "url": "http://localhost:3000/api/v1/progress/2" }, "status_code": 200 }, @@ -709,7 +709,7 @@ "url": "https://example.com/myblog2.rss" } ], - "status_code": 200 + "status_code": 200 }, "create_external_feed": { "method": "POST", @@ -759,57 +759,57 @@ "status_code": 200 }, "get_folder": { - "method": "GET", - "endpoint": "groups/1/folders/1", - "data": { - "id": 1, - "files_count": 10, - "folders_count": 2, - "name": "Folder 1", - "full_name": "Folder 1" - }, - "status_code": 200 + "method": "GET", + "endpoint": "groups/1/folders/1", + "data": { + "id": 1, + "files_count": 10, + "folders_count": 2, + "name": "Folder 1", + "full_name": "Folder 1" + }, + "status_code": 200 }, "list_folders": { - "method": "GET", - "endpoint": "groups/1/folders", - "data": [ - { - "id": 2, - "files_count": 0, - "folders_count": 0, - "name": "Folder 2", - "full_name": "group_files/Folder 2" - }, - { - "id": 3, - "files_count": 0, - "folders_count": 0, - "name": "Folder 3", - "full_name": "group_files/Folder 3" - } - ], - "status_code": 200 + "method": "GET", + "endpoint": "groups/1/folders", + "data": [ + { + "id": 2, + "files_count": 0, + "folders_count": 0, + "name": "Folder 2", + "full_name": "group_files/Folder 2" + }, + { + "id": 3, + "files_count": 0, + "folders_count": 0, + "name": "Folder 3", + "full_name": "group_files/Folder 3" + } + ], + "status_code": 200 }, "list_tabs": { "method": "GET", "endpoint": "groups/1/tabs", "data": [ { - "id": "home", - "html_url": "/groups/1", - "position": 1, - "visibility": "public", - "label": "Home", - "type": "internal" - }, - { - "id": "pages", - "html_url": "/groups/1/wiki", - "position": 2, - "visibility": "public", - "label": "Pages", - "type": "internal" + "id": "home", + "html_url": "/groups/1", + "position": 1, + "visibility": "public", + "label": "Home", + "type": "internal" + }, + { + "id": "pages", + "html_url": "/groups/1/wiki", + "position": 2, + "visibility": "public", + "label": "Pages", + "type": "internal" } ], "status_code": 200 @@ -820,38 +820,38 @@ "data": { "collaborations": [ { - "id": 1, - "collaboration_type": "Microsoft Office", - "document_id": "oinwoenfe8w8ef_onweufe89fef", - "user_id": 92, - "context_id": 77, - "context_type": "Course", - "url": null, - "created_at": "2012-06-01T00:00:00-06:00", - "updated_at": "2012-06-01T00:00:00-06:00", - "description": null, - "title": null, - "type": "ExternalToolCollaboration", - "update_url": null, - "user_name": "John Danger" - }, - { - "id": 2, - "collaboration_type": "Microsoft Office", - "document_id": "oinwoenfe8w8ef_onweufe89zzz", - "user_id": 93, - "context_id": 78, - "context_type": "Course", - "url": null, - "created_at": "2012-06-01T00:00:00-06:00", - "updated_at": "2012-06-01T00:00:00-06:00", - "description": null, - "title": null, - "type": "ExternalToolCollaboration", - "update_url": null, - "user_name": "John Danger" - } - ] + "id": 1, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89fef", + "user_id": 92, + "context_id": 77, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + }, + { + "id": 2, + "collaboration_type": "Microsoft Office", + "document_id": "oinwoenfe8w8ef_onweufe89zzz", + "user_id": 93, + "context_id": 78, + "context_type": "Course", + "url": null, + "created_at": "2012-06-01T00:00:00-06:00", + "updated_at": "2012-06-01T00:00:00-06:00", + "description": null, + "title": null, + "type": "ExternalToolCollaboration", + "update_url": null, + "user_name": "John Danger" + } + ] }, "status_code": 200 }, From 2cbaefbeda082cad8271eb30d5f068606a8a9fce Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 19 Aug 2019 11:17:37 -0400 Subject: [PATCH 60/65] Update changelog. Add Cat to authors.md --- AUTHORS.md | 1 + CHANGELOG.md | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/AUTHORS.md b/AUTHORS.md index 5708dbb5..6584013e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -17,6 +17,7 @@ Patches and Suggestions - Ben Liblit [@liblit](https://github.com/liblit) - Bill Wrbican [@wjw27](https://github.com/wjw27) - Bradford Lynch [@bradfordlynch](https://github.com/bradfordlynch) +- Catherine Abbruzzese [@cat0698](https://github.com/cat0698)) - Daniel Brinkman [@DanBrink91](https://github.com/DanBrink91) - Daniel Grobani [@dgrobani](https://github.com/dgrobani) - David Warden [@dfwarden](https://github.com/dfwarden) diff --git a/CHANGELOG.md b/CHANGELOG.md index acba9542..c2c0d987 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ ## Unreleased +### New Endpoint Coverage + +- API Token scopes (Thanks, [@jrsilveti](https://github.com/jrsilveti)) + - List scopes +- Account Notifications (Thanks, [@jrsilveti](https://github.com/jrsilveti)) + - Show a global notification + - Update a global notification +- Account Reports (Thanks, [@jrsilveti](https://github.com/jrsilveti)) + - Start a report + - Status of a report + - Delete a report +- Collaborations (Thanks, [@jrsilveti](https://github.com/jrsilveti)) + - List collaborations + - List members of a collaboration +- Feature Flags (Thanks, [@cat0698](https://github.com/cat0698)) + - List features + - List enabled features + - Get feature flag + - Set feature flag + - Remove feature flag +- Rubric (Thanks, [@cat0698](https://github.com/cat0698)) + - Create a single rubric + ### General - Removed overzealous global enabling of `DeprecationWarning`. (Thanks, [@Screeeech](https://github.com/Screeeech)) From df0b4cf798a7715729c9e9f2c4918f3bbce03583 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Mon, 19 Aug 2019 11:32:51 -0400 Subject: [PATCH 61/65] Fix build docs warnings. Add internal class references to docs. --- docs/canvas-object-ref.rst | 2 +- docs/class-reference.rst | 1 + docs/conf.py | 2 +- docs/content-migration-ref.rst | 8 ++++++++ docs/index.rst | 1 + docs/internal-classes.rst | 11 +++++++++++ docs/paginated-list-ref.rst | 6 ++++++ 7 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 docs/internal-classes.rst create mode 100644 docs/paginated-list-ref.rst diff --git a/docs/canvas-object-ref.rst b/docs/canvas-object-ref.rst index af45bcda..2ba511cf 100644 --- a/docs/canvas-object-ref.rst +++ b/docs/canvas-object-ref.rst @@ -3,4 +3,4 @@ Canvas Object ============= .. autoclass:: canvasapi.canvas_object.CanvasObject - :members: \ No newline at end of file + :members: diff --git a/docs/class-reference.rst b/docs/class-reference.rst index 4a48ff48..6ef89662 100644 --- a/docs/class-reference.rst +++ b/docs/class-reference.rst @@ -47,6 +47,7 @@ Class Reference rubric-ref scope-ref section-ref + sis-import-ref submission-ref tab-ref upload-ref diff --git a/docs/conf.py b/docs/conf.py index cda23caa..66f4dbc5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -143,7 +143,7 @@ # 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'] +html_static_path = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied diff --git a/docs/content-migration-ref.rst b/docs/content-migration-ref.rst index ce926377..12c47c0f 100644 --- a/docs/content-migration-ref.rst +++ b/docs/content-migration-ref.rst @@ -5,8 +5,16 @@ ContentMigration .. autoclass:: canvasapi.content_migration.ContentMigration :members: +============== +MigrationIssue +============== + .. autoclass:: canvasapi.content_migration.MigrationIssue :members: +======== +Migrator +======== + .. autoclass:: canvasapi.content_migration.Migrator :members: diff --git a/docs/index.rst b/docs/index.rst index ff456172..ee8667dc 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -17,3 +17,4 @@ Contents: exceptions debugging class-reference + internal-classes diff --git a/docs/internal-classes.rst b/docs/internal-classes.rst new file mode 100644 index 00000000..829a6770 --- /dev/null +++ b/docs/internal-classes.rst @@ -0,0 +1,11 @@ +Internal Classes +================ + +The following classes are internal to CanvasAPI and are described here for reference only. They are not intended for use by consumers of the library. + +.. toctree:: + + canvas-object-ref + paginated-list-ref + requester-ref + util-ref diff --git a/docs/paginated-list-ref.rst b/docs/paginated-list-ref.rst new file mode 100644 index 00000000..01ae7ab2 --- /dev/null +++ b/docs/paginated-list-ref.rst @@ -0,0 +1,6 @@ +============= +PaginatedList +============= + +.. autoclass:: canvasapi.paginated_list.PaginatedList + :members: From 74922ac045bb911369427d2786852d65fcccd597 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 20 Aug 2019 10:59:17 -0400 Subject: [PATCH 62/65] Bump version to 0.14.0 --- CHANGELOG.md | 2 +- canvasapi/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2c0d987..8888bd76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Change Log -## Unreleased +## [0.14.0] - 2019-08-20 ### New Endpoint Coverage diff --git a/canvasapi/__init__.py b/canvasapi/__init__.py index 599821b1..ce7ccf6c 100644 --- a/canvasapi/__init__.py +++ b/canvasapi/__init__.py @@ -6,4 +6,4 @@ __all__ = ["Canvas"] -__version__ = "0.13.0" +__version__ = "0.14.0" From 0c0c53318b9748919729dc5f90038e0ce521aa1f Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 20 Aug 2019 11:41:38 -0400 Subject: [PATCH 63/65] Add code style: black badge --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e05bd0c6..b8719a95 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@ [![Build Status](https://travis-ci.org/ucfopen/canvasapi.svg?branch=master)](https://travis-ci.org/ucfopen/canvasapi) [![Coverage Status](https://coveralls.io/repos/github/ucfopen/canvasapi/badge.svg?branch=master)](https://coveralls.io/github/ucfopen/canvasapi?branch=master) [![Join UCF Open Slack Discussions](https://ucf-open-slackin.herokuapp.com/badge.svg)](https://ucf-open-slackin.herokuapp.com/) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) + # CanvasAPI From d450aa76fd62ace372765de9d750320d261de7a3 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 20 Aug 2019 11:44:13 -0400 Subject: [PATCH 64/65] Remove extra line --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index b8719a95..19f2bddf 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,6 @@ [![Join UCF Open Slack Discussions](https://ucf-open-slackin.herokuapp.com/badge.svg)](https://ucf-open-slackin.herokuapp.com/) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) - # CanvasAPI CanvasAPI is a Python library for accessing Instructure’s [Canvas LMS API](https://canvas.instructure.com/doc/api/index.html). The library enables developers to programmatically manage Canvas courses, users, gradebooks, and more. From 4d80c2e15df1845d96f882964490d3caee013513 Mon Sep 17 00:00:00 2001 From: Matthew Emond Date: Tue, 20 Aug 2019 11:50:55 -0400 Subject: [PATCH 65/65] Update changelog links --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8888bd76..0ce69fcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -368,7 +368,7 @@ Huge thanks to [@liblit](https://github.com/liblit) for lots of issues, suggesti - Fixed some incorrectly defined parameters - Fixed an issue where tests would fail due to an improperly configured requires block -[Unreleased]: https://github.com/ucfopen/canvasapi/compare/v0.13.0...develop +[0.14.0]: https://github.com/ucfopen/canvasapi/compare/v0.13.0...v0.14.0 [0.13.0]: https://github.com/ucfopen/canvasapi/compare/v0.12.0...v0.13.0 [0.12.0]: https://github.com/ucfopen/canvasapi/compare/v0.11.0...v0.12.0 [0.11.0]: https://github.com/ucfopen/canvasapi/compare/v0.10.0...v0.11.0