BOM-2477: pylint warnings lint-amnesty (#27585)

This commit is contained in:
Usama Sadiq
2021-05-11 17:22:40 +05:00
committed by GitHub
parent 156a1a80ee
commit 4f4be6538a
52 changed files with 67 additions and 69 deletions

View File

@@ -47,7 +47,7 @@ class Command(BaseCommand):
course_dir = data_root / subdir course_dir = data_root / subdir
# Extract library archive # Extract library archive
tar_file = tarfile.open(archive_path) tar_file = tarfile.open(archive_path) # lint-amnesty, pylint: disable=consider-using-with
try: try:
safetar_extractall(tar_file, course_dir.encode('utf-8')) safetar_extractall(tar_file, course_dir.encode('utf-8'))
except SuspiciousOperation as exc: except SuspiciousOperation as exc:

View File

@@ -336,7 +336,7 @@ def create_export_tarball(course_module, course_key, context, status=None):
Updates the context with any error information if applicable. Updates the context with any error information if applicable.
""" """
name = course_module.url_name name = course_module.url_name
export_file = NamedTemporaryFile(prefix=name + '.', suffix=".tar.gz") export_file = NamedTemporaryFile(prefix=name + '.', suffix=".tar.gz") # lint-amnesty, pylint: disable=consider-using-with
root_dir = path(mkdtemp()) root_dir = path(mkdtemp())
try: try:
@@ -595,7 +595,7 @@ def import_olx(self, user_id, course_key_string, archive_path, archive_name, lan
# try-finally block for proper clean up after receiving file. # try-finally block for proper clean up after receiving file.
try: try:
tar_file = tarfile.open(temp_filepath) tar_file = tarfile.open(temp_filepath) # lint-amnesty, pylint: disable=consider-using-with
try: try:
safetar_extractall(tar_file, (course_dir + '/')) safetar_extractall(tar_file, (course_dir + '/'))
except SuspiciousOperation as exc: except SuspiciousOperation as exc:

View File

@@ -812,7 +812,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
""" """
Create srt file. Create srt file.
""" """
srt_file = tempfile.NamedTemporaryFile(suffix=".srt") srt_file = tempfile.NamedTemporaryFile(suffix=".srt") # lint-amnesty, pylint: disable=consider-using-with
srt_file.content_type = transcripts_utils.Transcript.SRT srt_file.content_type = transcripts_utils.Transcript.SRT
srt_file.write(content) srt_file.write(content)
srt_file.seek(0) srt_file.seek(0)

View File

@@ -720,7 +720,7 @@ class ExportTestCase(CourseTestCase):
resp_content += item resp_content += item
buff = BytesIO(resp_content) buff = BytesIO(resp_content)
return tarfile.open(fileobj=buff) return tarfile.open(fileobj=buff) # lint-amnesty, pylint: disable=consider-using-with
def _verify_export_succeeded(self, resp): def _verify_export_succeeded(self, resp):
""" Export success helper method. """ """ Export success helper method. """

View File

@@ -183,7 +183,7 @@ class TestUploadTranscripts(BaseTranscripts):
""" """
Setup a transcript file with suffix and content. Setup a transcript file with suffix and content.
""" """
transcript_file = tempfile.NamedTemporaryFile(suffix=suffix) transcript_file = tempfile.NamedTemporaryFile(suffix=suffix) # lint-amnesty, pylint: disable=consider-using-with
wrapped_content = textwrap.dedent(content) wrapped_content = textwrap.dedent(content)
if include_bom: if include_bom:
wrapped_content = wrapped_content.encode('utf-8-sig') wrapped_content = wrapped_content.encode('utf-8-sig')

View File

@@ -15,7 +15,6 @@
import logging import logging
import six
from django.conf import settings from django.conf import settings
from django.http import HttpResponse # lint-amnesty, pylint: disable=unused-import from django.http import HttpResponse # lint-amnesty, pylint: disable=unused-import
from django.template import engines from django.template import engines

View File

@@ -68,7 +68,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
group_objects = {} group_objects = {}
f = open(options['log_name'], "a+") f = open(options['log_name'], "a+") # lint-amnesty, pylint: disable=consider-using-with
# Create groups # Create groups
for group in dict(groups): for group in dict(groups):

View File

@@ -3218,8 +3218,7 @@ class UserCelebration(TimeStampedModel):
if last_day_of_streak != self.last_day_of_streak: if last_day_of_streak != self.last_day_of_streak:
self.last_day_of_streak = last_day_of_streak self.last_day_of_streak = last_day_of_streak
self.streak_length = streak_length self.streak_length = streak_length
if self.longest_ever_streak < streak_length: self.longest_ever_streak = max(self.longest_ever_streak, streak_length)
self.longest_ever_streak = streak_length
self.save() self.save()

View File

@@ -74,7 +74,7 @@ class StubLtiServiceTest(unittest.TestCase):
grade_uri = self.uri + 'grade' grade_uri = self.uri + 'grade'
with patch('common.djangoapps.terrain.stubs.lti.requests.post') as mocked_post: with patch('common.djangoapps.terrain.stubs.lti.requests.post') as mocked_post:
mocked_post.return_value = Mock(content='Test response', status_code=200) mocked_post.return_value = Mock(content='Test response', status_code=200)
response = urlopen(grade_uri, data=b'') response = urlopen(grade_uri, data=b'') # lint-amnesty, pylint: disable=consider-using-with
assert b'Test response' in response.read() assert b'Test response' in response.read()
@patch('common.djangoapps.terrain.stubs.lti.signature.verify_hmac_sha1', return_value=True) @patch('common.djangoapps.terrain.stubs.lti.signature.verify_hmac_sha1', return_value=True)
@@ -84,7 +84,7 @@ class StubLtiServiceTest(unittest.TestCase):
grade_uri = self.uri + 'lti2_outcome' grade_uri = self.uri + 'lti2_outcome'
with patch('common.djangoapps.terrain.stubs.lti.requests.put') as mocked_put: with patch('common.djangoapps.terrain.stubs.lti.requests.put') as mocked_put:
mocked_put.return_value = Mock(status_code=200) mocked_put.return_value = Mock(status_code=200)
response = urlopen(grade_uri, data=b'') response = urlopen(grade_uri, data=b'') # lint-amnesty, pylint: disable=consider-using-with
assert b'LTI consumer (edX) responded with HTTP 200' in response.read() assert b'LTI consumer (edX) responded with HTTP 200' in response.read()
@patch('common.djangoapps.terrain.stubs.lti.signature.verify_hmac_sha1', return_value=True) @patch('common.djangoapps.terrain.stubs.lti.signature.verify_hmac_sha1', return_value=True)
@@ -94,5 +94,5 @@ class StubLtiServiceTest(unittest.TestCase):
grade_uri = self.uri + 'lti2_delete' grade_uri = self.uri + 'lti2_delete'
with patch('common.djangoapps.terrain.stubs.lti.requests.put') as mocked_put: with patch('common.djangoapps.terrain.stubs.lti.requests.put') as mocked_put:
mocked_put.return_value = Mock(status_code=200) mocked_put.return_value = Mock(status_code=200)
response = urlopen(grade_uri, data=b'') response = urlopen(grade_uri, data=b'') # lint-amnesty, pylint: disable=consider-using-with
assert b'LTI consumer (edX) responded with HTTP 200' in response.read() assert b'LTI consumer (edX) responded with HTTP 200' in response.read()

View File

@@ -5,7 +5,7 @@ import logging
from opaque_keys import InvalidKeyError from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey, LearningContextKey from opaque_keys.edx.keys import CourseKey, LearningContextKey
from six import text_type from six import text_type # lint-amnesty, pylint: disable=unused-import
from openedx.core.lib.request_utils import COURSE_REGEX from openedx.core.lib.request_utils import COURSE_REGEX

View File

@@ -12,7 +12,7 @@ import logging
import re import re
import sys import sys
import six import six # lint-amnesty, pylint: disable=unused-import
from django.conf import settings from django.conf import settings
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
from eventtracking import tracker from eventtracking import tracker

View File

@@ -24,7 +24,7 @@ import inspect
import warnings import warnings
from importlib import import_module from importlib import import_module
import six import six # lint-amnesty, pylint: disable=unused-import
from django.conf import settings from django.conf import settings
from common.djangoapps.track.backends import BaseBackend from common.djangoapps.track.backends import BaseBackend

View File

@@ -9,7 +9,7 @@ apply them to the appropriate events.
import json import json
import logging import logging
import six import six # lint-amnesty, pylint: disable=unused-import
from opaque_keys import InvalidKeyError from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import UsageKey from opaque_keys.edx.keys import UsageKey

View File

@@ -2777,7 +2777,7 @@ class CodeResponse(LoncapaResponse):
# matches # matches
if oldcmap.is_right_queuekey(self.answer_id, queuekey): if oldcmap.is_right_queuekey(self.answer_id, queuekey):
# Sanity check on returned points # Sanity check on returned points
if points < 0: if points < 0: # lint-amnesty, pylint: disable=consider-using-max-builtin
points = 0 points = 0
# Queuestate is consumed # Queuestate is consumed
oldcmap.set( oldcmap.set(

View File

@@ -2304,7 +2304,7 @@ class CustomResponseTest(ResponseTest): # pylint: disable=missing-class-docstri
# Make a zipfile with one module in it with one function. # Make a zipfile with one module in it with one function.
zipstring = io.BytesIO() zipstring = io.BytesIO()
zipf = zipfile.ZipFile(zipstring, "w") zipf = zipfile.ZipFile(zipstring, "w") # lint-amnesty, pylint: disable=consider-using-with
zipf.writestr("my_helper.py", textwrap.dedent("""\ zipf.writestr("my_helper.py", textwrap.dedent("""\
def seventeen(): def seventeen():
return 17 return 17

View File

@@ -21,7 +21,7 @@ import unicodedata
from copy import deepcopy from copy import deepcopy
from functools import reduce from functools import reduce
import six import six # lint-amnesty, pylint: disable=unused-import
import sympy import sympy
from lxml import etree from lxml import etree
from sympy import latex, sympify from sympy import latex, sympify

View File

@@ -6,7 +6,7 @@ from logging import getLogger
from lms.djangoapps.courseware.access import has_access from lms.djangoapps.courseware.access import has_access
from lms.djangoapps.courseware.masquerade import MASQUERADE_SETTINGS_KEY from lms.djangoapps.courseware.masquerade import MASQUERADE_SETTINGS_KEY
from common.djangoapps.student.roles import GlobalStaff from common.djangoapps.student.roles import GlobalStaff # lint-amnesty, pylint: disable=unused-import
from .exceptions import ItemNotFoundError, NoPathToItem from .exceptions import ItemNotFoundError, NoPathToItem
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)

View File

@@ -324,7 +324,7 @@ class ItemFactory(XModuleFactory):
return parent.location return parent.location
@classmethod @classmethod
def _create(cls, target_class, **kwargs): # lint-amnesty, pylint: disable=arguments-differ, unused-argument def _create(cls, target_class, **kwargs): # lint-amnesty, pylint: disable=arguments-differ, too-many-statements, unused-argument
""" """
Uses ``**kwargs``: Uses ``**kwargs``:

View File

@@ -31,10 +31,10 @@ class Progress: # pylint: disable=eq-without-hash
isinstance(b, numbers.Number)): isinstance(b, numbers.Number)):
raise TypeError(f'a and b must be numbers. Passed {a}/{b}') raise TypeError(f'a and b must be numbers. Passed {a}/{b}')
if a > b: if a > b: # lint-amnesty, pylint: disable=consider-using-min-builtin
a = b a = b
if a < 0: if a < 0: # lint-amnesty, pylint: disable=consider-using-max-builtin
a = 0 a = 0
if b <= 0: if b <= 0:

View File

@@ -396,7 +396,7 @@ class CourseFixture(XBlockContainerFixture):
for asset_name in self._assets: for asset_name in self._assets:
asset_file_path = test_dir + '/data/uploads/' + asset_name asset_file_path = test_dir + '/data/uploads/' + asset_name
asset_file = open(asset_file_path, mode='rb') # lint-amnesty, pylint: disable=bad-option-value, open-builtin asset_file = open(asset_file_path, mode='rb') # lint-amnesty, pylint: disable=consider-using-with
files = {'file': (asset_name, asset_file, mimetypes.guess_type(asset_file_path)[0])} files = {'file': (asset_name, asset_file, mimetypes.guess_type(asset_file_path)[0])}
headers = { headers = {

View File

@@ -17,7 +17,7 @@ from django.urls import reverse, reverse_lazy
from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.course_modes.tests.factories import CourseModeFactory from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from common.djangoapps.student.models import CourseEnrollment from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.tests.tests import EnrollmentEventTestMixin from common.djangoapps.student.tests.tests import EnrollmentEventTestMixin # lint-amnesty, pylint: disable=unused-import
from openedx.core.djangoapps.embargo.test_utils import restrict_course from openedx.core.djangoapps.embargo.test_utils import restrict_course
from openedx.core.djangoapps.enrollments.api import get_enrollment from openedx.core.djangoapps.enrollments.api import get_enrollment
from openedx.core.lib.django_test_client_utils import get_absolute_url from openedx.core.lib.django_test_client_utils import get_absolute_url

View File

@@ -150,7 +150,7 @@ class BasketsView(APIView):
) )
log.info(msg) log.info(msg)
self._enroll(course_key, user, default_enrollment_mode.slug) self._enroll(course_key, user, default_enrollment_mode.slug)
mode = CourseMode.AUDIT if audit_mode else CourseMode.HONOR mode = CourseMode.AUDIT if audit_mode else CourseMode.HONOR # lint-amnesty, pylint: disable=unused-variable
self._handle_marketing_opt_in(request, course_key, user) self._handle_marketing_opt_in(request, course_key, user)
return DetailResponse(msg) return DetailResponse(msg)
else: else:

View File

@@ -14,7 +14,7 @@ from openedx.core.lib.api.authentication import BearerAuthenticationAllowInactiv
from openedx.core.djangoapps.courseware_api.utils import get_celebrations_dict from openedx.core.djangoapps.courseware_api.utils import get_celebrations_dict
from openedx.core.djangoapps.courseware_api.views import CoursewareMeta from openedx.core.djangoapps.courseware_api.views import CoursewareMeta
from common.djangoapps.student.models import CourseEnrollment, UserCelebration from common.djangoapps.student.models import CourseEnrollment, UserCelebration # lint-amnesty, pylint: disable=unused-import
from lms.djangoapps.course_api.api import course_detail from lms.djangoapps.course_api.api import course_detail
from lms.djangoapps.course_home_api.course_metadata.v1.serializers import CourseHomeMetadataSerializer from lms.djangoapps.course_home_api.course_metadata.v1.serializers import CourseHomeMetadataSerializer
from lms.djangoapps.courseware.access import has_access from lms.djangoapps.courseware.access import has_access

View File

@@ -49,7 +49,7 @@ def _create_srt_file(content=None):
""" """
content = content or SRT_content content = content or SRT_content
srt_file = tempfile.NamedTemporaryFile(suffix=".srt") srt_file = tempfile.NamedTemporaryFile(suffix=".srt") # lint-amnesty, pylint: disable=consider-using-with
srt_file.content_type = 'application/x-subrip; charset=utf-8' srt_file.content_type = 'application/x-subrip; charset=utf-8'
srt_file.write(content.encode('utf-8')) srt_file.write(content.encode('utf-8'))
srt_file.seek(0) srt_file.seek(0)
@@ -93,7 +93,7 @@ def _create_file(content=''):
""" """
Create temporary subs_somevalue.srt.sjson file. Create temporary subs_somevalue.srt.sjson file.
""" """
sjson_file = tempfile.NamedTemporaryFile(prefix="subs_", suffix=".srt.sjson") sjson_file = tempfile.NamedTemporaryFile(prefix="subs_", suffix=".srt.sjson") # lint-amnesty, pylint: disable=consider-using-with
sjson_file.content_type = 'application/json' sjson_file.content_type = 'application/json'
sjson_file.write(textwrap.dedent(content).encode('utf-8')) sjson_file.write(textwrap.dedent(content).encode('utf-8'))
sjson_file.seek(0) sjson_file.seek(0)

View File

@@ -16,7 +16,7 @@ from rest_framework.response import Response
from rest_framework.views import APIView from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet from rest_framework.viewsets import ViewSet
from lms.djangoapps.discussion.django_comment_client.utils import available_division_schemes from lms.djangoapps.discussion.django_comment_client.utils import available_division_schemes # lint-amnesty, pylint: disable=unused-import
from lms.djangoapps.discussion.rest_api.api import ( from lms.djangoapps.discussion.rest_api.api import (
create_comment, create_comment,
create_thread, create_thread,
@@ -43,7 +43,7 @@ from lms.djangoapps.discussion.rest_api.serializers import (
DiscussionRolesSerializer, DiscussionRolesSerializer,
DiscussionSettingsSerializer DiscussionSettingsSerializer
) )
from lms.djangoapps.discussion.views import get_divided_discussions from lms.djangoapps.discussion.views import get_divided_discussions # lint-amnesty, pylint: disable=unused-import
from lms.djangoapps.instructor.access import update_forum_role from lms.djangoapps.instructor.access import update_forum_role
from openedx.core.djangoapps.django_comment_common import comment_client from openedx.core.djangoapps.django_comment_common import comment_client
from openedx.core.djangoapps.django_comment_common.models import Role from openedx.core.djangoapps.django_comment_common.models import Role

View File

@@ -1043,7 +1043,7 @@ class GradebookViewTest(GradebookViewTestBase):
assert status.HTTP_200_OK == resp.status_code assert status.HTTP_200_OK == resp.status_code
actual_data = dict(resp.data) actual_data = dict(resp.data)
expected_page_size = page_size or CourseEnrollmentPagination.page_size expected_page_size = page_size or CourseEnrollmentPagination.page_size
if expected_page_size > user_size: if expected_page_size > user_size: # lint-amnesty, pylint: disable=consider-using-min-builtin
expected_page_size = user_size expected_page_size = user_size
assert len(actual_data['results']) == expected_page_size assert len(actual_data['results']) == expected_page_size

View File

@@ -1423,7 +1423,7 @@ class MockDefaultStorage:
def open(self, file_name): def open(self, file_name):
"""Mock out DefaultStorage.open with standard python open""" """Mock out DefaultStorage.open with standard python open"""
return open(file_name) # lint-amnesty, pylint: disable=bad-option-value, open-builtin return open(file_name) # lint-amnesty, pylint: disable=bad-option-value, open-builtin # lint-amnesty, pylint: disable=consider-using-with
@patch('lms.djangoapps.instructor_task.tasks_helper.misc.DefaultStorage', new=MockDefaultStorage) @patch('lms.djangoapps.instructor_task.tasks_helper.misc.DefaultStorage', new=MockDefaultStorage)

View File

@@ -2,7 +2,7 @@
Course API Views Course API Views
""" """
import json import json # lint-amnesty, pylint: disable=unused-import
from completion.exceptions import UnavailableCompletionData from completion.exceptions import UnavailableCompletionData
from completion.utilities import get_key_to_last_completed_block from completion.utilities import get_key_to_last_completed_block

View File

@@ -13,7 +13,7 @@ signals.)
import logging import logging
import shlex import shlex
import sys import sys # lint-amnesty, pylint: disable=unused-import
from datetime import datetime, timedelta from datetime import datetime, timedelta
import dateutil.parser import dateutil.parser

View File

@@ -8,7 +8,7 @@ from unittest import mock
from django.core.management import call_command from django.core.management import call_command
from django.core.management.base import CommandError from django.core.management.base import CommandError
from django.test import TestCase, override_settings from django.test import TestCase, override_settings # lint-amnesty, pylint: disable=unused-import
from freezegun import freeze_time from freezegun import freeze_time
from openedx.core.djangoapps.catalog.tests.factories import ProgramFactory, CourseFactory, CourseRunFactory from openedx.core.djangoapps.catalog.tests.factories import ProgramFactory, CourseFactory, CourseRunFactory

View File

@@ -3,8 +3,8 @@
from unittest import mock from unittest import mock
from django.conf import settings from django.conf import settings # lint-amnesty, pylint: disable=unused-import
from django.test import TestCase, override_settings from django.test import TestCase, override_settings # lint-amnesty, pylint: disable=unused-import
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
from lms.djangoapps.grades.course_grade_factory import CourseGradeFactory from lms.djangoapps.grades.course_grade_factory import CourseGradeFactory

View File

@@ -126,7 +126,7 @@ class LegacySettingsSerializer(serializers.BaseSerializer):
raise serializers.ValidationError('Wrong type for discussion_topics') raise serializers.ValidationError('Wrong type for discussion_topics')
payload = { payload = {
key: value key: value
for key, value in data.items() for key, value in data.items() # lint-amnesty, pylint: disable=unnecessary-comprehension
} }
return payload return payload

View File

@@ -28,7 +28,7 @@ def make_image_file(dimensions=(320, 240), prefix='tmp', extension='.jpeg', forc
""" """
image = Image.new('RGB', dimensions, "green") image = Image.new('RGB', dimensions, "green")
image_file = NamedTemporaryFile(prefix=prefix, suffix=extension) image_file = NamedTemporaryFile(prefix=prefix, suffix=extension) # lint-amnesty, pylint: disable=consider-using-with
try: try:
if orientation and orientation in range(1, 9): if orientation and orientation in range(1, 9):
exif_bytes = piexif.dump({'0th': {piexif.ImageIFD.Orientation: orientation}}) exif_bytes = piexif.dump({'0th': {piexif.ImageIFD.Orientation: orientation}})

View File

@@ -475,7 +475,7 @@ class TestProgramProgressMeter(ModuleStoreTestCase):
programs = data[:3] programs = data[:3]
assert meter.engaged_programs == programs assert meter.engaged_programs == programs
def test_simulate_progress(self, mock_get_programs): def test_simulate_progress(self, mock_get_programs): # lint-amnesty, pylint: disable=too-many-statements
"""Simulate the entirety of a user's progress through a program.""" """Simulate the entirety of a user's progress through a program."""
today = datetime.datetime.now(utc) today = datetime.datetime.now(utc)
two_days_ago = today - datetime.timedelta(days=2) two_days_ago = today - datetime.timedelta(days=2)

View File

@@ -274,7 +274,7 @@ class EmailOptInListTest(ModuleStoreTestCase):
call_command('email_opt_in_list', *args) call_command('email_opt_in_list', *args)
def test_file_already_exists(self): def test_file_already_exists(self):
temp_file = tempfile.NamedTemporaryFile(delete=True) temp_file = tempfile.NamedTemporaryFile(delete=True) # lint-amnesty, pylint: disable=consider-using-with
def _cleanup(): def _cleanup():
temp_file.close() temp_file.close()

View File

@@ -5,7 +5,7 @@ Utility functions used during user authentication.
import random import random
import string import string
from urllib.parse import urlparse # pylint: disable=import-error from urllib.parse import urlparse # pylint: disable=import-error
from uuid import uuid4 from uuid import uuid4 # lint-amnesty, pylint: disable=unused-import
from django.conf import settings from django.conf import settings
from django.utils import http from django.utils import http

View File

@@ -44,7 +44,7 @@ from openedx.core.djangoapps.user_authn.views.utils import (
from openedx.core.djangoapps.user_authn.toggles import is_require_third_party_auth_enabled from openedx.core.djangoapps.user_authn.toggles import is_require_third_party_auth_enabled
from openedx.core.djangoapps.user_authn.config.waffle import ENABLE_LOGIN_USING_THIRDPARTY_AUTH_ONLY from openedx.core.djangoapps.user_authn.config.waffle import ENABLE_LOGIN_USING_THIRDPARTY_AUTH_ONLY
from openedx.core.djangolib.markup import HTML, Text from openedx.core.djangolib.markup import HTML, Text
from openedx.core.lib.api.view_utils import require_post_params from openedx.core.lib.api.view_utils import require_post_params # lint-amnesty, pylint: disable=unused-import
from openedx.features.enterprise_support.api import activate_learner_enterprise, get_enterprise_learner_data_from_api from openedx.features.enterprise_support.api import activate_learner_enterprise, get_enterprise_learner_data_from_api
from common.djangoapps.student.helpers import get_next_url_for_login_page, get_redirect_url_with_host from common.djangoapps.student.helpers import get_next_url_for_login_page, get_redirect_url_with_host
from common.djangoapps.student.models import LoginFailures, AllowedAuthUser, UserProfile from common.djangoapps.student.models import LoginFailures, AllowedAuthUser, UserProfile

View File

@@ -12,7 +12,7 @@ def html_to_text(html_message):
Currently uses lynx in a subprocess; should be refactored to Currently uses lynx in a subprocess; should be refactored to
use something more pythonic. use something more pythonic.
""" """
process = Popen( process = Popen( # lint-amnesty, pylint: disable=consider-using-with
['lynx', '-stdin', '-display_charset=UTF-8', '-assume_charset=UTF-8', '-dump'], ['lynx', '-stdin', '-display_charset=UTF-8', '-assume_charset=UTF-8', '-dump'],
stdin=PIPE, stdin=PIPE,
stdout=PIPE stdout=PIPE

View File

@@ -4,7 +4,7 @@ Script to process pytest warnings output by pytest-json-report plugin and output
""" """
import argparse import argparse
import io import io # lint-amnesty, pylint: disable=unused-import
import itertools import itertools
import json import json
import os import os

View File

@@ -2,7 +2,7 @@
Module to put all pytest hooks that modify pytest behaviour Module to put all pytest hooks that modify pytest behaviour
""" """
import os import os
import io import io # lint-amnesty, pylint: disable=unused-import
import json import json

View File

@@ -2,7 +2,7 @@
Class used to write pytest warning data into html format Class used to write pytest warning data into html format
""" """
import textwrap import textwrap
import six import six # lint-amnesty, pylint: disable=unused-import
class HtmlOutlineWriter: class HtmlOutlineWriter:

View File

@@ -5,7 +5,7 @@ Tests for course dates fragment.
from datetime import datetime, timedelta from datetime import datetime, timedelta
import six import six # lint-amnesty, pylint: disable=unused-import
from django.urls import reverse from django.urls import reverse
from common.djangoapps.student.tests.factories import UserFactory from common.djangoapps.student.tests.factories import UserFactory

View File

@@ -7,7 +7,7 @@ because the Studio course outline may need these utilities.
from enum import Enum from enum import Enum
from typing import Optional from typing import Optional
import six import six # lint-amnesty, pylint: disable=unused-import
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.http import HttpRequest from django.http import HttpRequest

View File

@@ -3,7 +3,7 @@ Views for the course home page.
""" """
import six import six # lint-amnesty, pylint: disable=unused-import
from django.conf import settings from django.conf import settings
from django.template.context_processors import csrf from django.template.context_processors import csrf
from django.template.loader import render_to_string from django.template.loader import render_to_string

View File

@@ -2,7 +2,7 @@
Views that handle course updates. Views that handle course updates.
""" """
import six import six # lint-amnesty, pylint: disable=unused-import
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.template.context_processors import csrf from django.template.context_processors import csrf
from django.template.loader import render_to_string from django.template.loader import render_to_string

View File

@@ -3,7 +3,7 @@ View logic for handling course welcome messages.
""" """
import six import six # lint-amnesty, pylint: disable=unused-import
from django.http import HttpResponse from django.http import HttpResponse
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.urls import reverse from django.urls import reverse

View File

@@ -9,7 +9,7 @@ from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.db.models.signals import post_save, pre_save from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver from django.dispatch import receiver
from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser # lint-amnesty, pylint: disable=unused-import
from integrated_channels.integrated_channel.tasks import ( from integrated_channels.integrated_channel.tasks import (
transmit_single_learner_data, transmit_single_learner_data,
transmit_single_subsection_learner_data transmit_single_subsection_learner_data

View File

@@ -28,7 +28,7 @@ class TestPaverQualityViolations(unittest.TestCase):
""" """
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.f = tempfile.NamedTemporaryFile(delete=False) self.f = tempfile.NamedTemporaryFile(delete=False) # lint-amnesty, pylint: disable=consider-using-with
self.f.close() self.f.close()
self.addCleanup(os.remove, self.f.name) self.addCleanup(os.remove, self.f.name)
@@ -102,7 +102,7 @@ class TestPaverReportViolationsCounts(unittest.TestCase):
super().setUp() super().setUp()
# Temporary file infrastructure # Temporary file infrastructure
self.f = tempfile.NamedTemporaryFile(delete=False) self.f = tempfile.NamedTemporaryFile(delete=False) # lint-amnesty, pylint: disable=consider-using-with
self.f.close() self.f.close()
# Cleanup various mocks and tempfiles # Cleanup various mocks and tempfiles
@@ -241,7 +241,7 @@ class TestPrepareReportDir(unittest.TestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.test_dir = tempfile.mkdtemp() self.test_dir = tempfile.mkdtemp()
self.test_file = tempfile.NamedTemporaryFile(delete=False, dir=self.test_dir) self.test_file = tempfile.NamedTemporaryFile(delete=False, dir=self.test_dir) # lint-amnesty, pylint: disable=consider-using-with
self.addCleanup(os.removedirs, self.test_dir) self.addCleanup(os.removedirs, self.test_dir)
def test_report_dir_with_files(self): def test_report_dir_with_files(self):

View File

@@ -135,20 +135,20 @@ def node_prereqs_installation():
npm_log_file_path = f'{Env.GEN_LOG_DIR}/npm-install.{shard_str}.log' npm_log_file_path = f'{Env.GEN_LOG_DIR}/npm-install.{shard_str}.log'
else: else:
npm_log_file_path = f'{Env.GEN_LOG_DIR}/npm-install.log' npm_log_file_path = f'{Env.GEN_LOG_DIR}/npm-install.log'
npm_log_file = open(npm_log_file_path, 'wb') npm_log_file = open(npm_log_file_path, 'wb') # lint-amnesty, pylint: disable=consider-using-with
npm_command = 'npm install --verbose'.split() npm_command = 'npm install --verbose'.split()
# The implementation of Paver's `sh` function returns before the forked # The implementation of Paver's `sh` function returns before the forked
# actually returns. Using a Popen object so that we can ensure that # actually returns. Using a Popen object so that we can ensure that
# the forked process has returned # the forked process has returned
proc = subprocess.Popen(npm_command, stderr=npm_log_file) proc = subprocess.Popen(npm_command, stderr=npm_log_file) # lint-amnesty, pylint: disable=consider-using-with
retcode = proc.wait() retcode = proc.wait()
if retcode == 1: if retcode == 1:
# Error handling around a race condition that produces "cb() never called" error. This # Error handling around a race condition that produces "cb() never called" error. This
# evinces itself as `cb_error_text` and it ought to disappear when we upgrade # evinces itself as `cb_error_text` and it ought to disappear when we upgrade
# npm to 3 or higher. TODO: clean this up when we do that. # npm to 3 or higher. TODO: clean this up when we do that.
print("npm install error detected. Retrying...") print("npm install error detected. Retrying...")
proc = subprocess.Popen(npm_command, stderr=npm_log_file) proc = subprocess.Popen(npm_command, stderr=npm_log_file) # lint-amnesty, pylint: disable=consider-using-with
retcode = proc.wait() retcode = proc.wait()
if retcode == 1: if retcode == 1:
raise Exception(f"npm install failed: See {npm_log_file_path}") raise Exception(f"npm install failed: See {npm_log_file_path}")

View File

@@ -36,11 +36,11 @@ def run_multi_processes(cmd_list, out_log=None, err_log=None):
pids = [] pids = []
if out_log: if out_log:
out_log_file = open(out_log, 'w') out_log_file = open(out_log, 'w') # lint-amnesty, pylint: disable=consider-using-with
kwargs['stdout'] = out_log_file kwargs['stdout'] = out_log_file
if err_log: if err_log:
err_log_file = open(err_log, 'w') err_log_file = open(err_log, 'w') # lint-amnesty, pylint: disable=consider-using-with
kwargs['stderr'] = err_log_file kwargs['stderr'] = err_log_file
# If the user is performing a dry run of a task, then just log # If the user is performing a dry run of a task, then just log
@@ -93,14 +93,14 @@ def run_background_process(cmd, out_log=None, err_log=None, cwd=None):
kwargs = {'shell': True, 'cwd': cwd} kwargs = {'shell': True, 'cwd': cwd}
if out_log: if out_log:
out_log_file = open(out_log, 'w') out_log_file = open(out_log, 'w') # lint-amnesty, pylint: disable=consider-using-with
kwargs['stdout'] = out_log_file kwargs['stdout'] = out_log_file
if err_log: if err_log:
err_log_file = open(err_log, 'w') err_log_file = open(err_log, 'w') # lint-amnesty, pylint: disable=consider-using-with
kwargs['stderr'] = err_log_file kwargs['stderr'] = err_log_file
proc = subprocess.Popen(cmd, **kwargs) proc = subprocess.Popen(cmd, **kwargs) # lint-amnesty, pylint: disable=consider-using-with
def exit_handler(): def exit_handler():
""" """

View File

@@ -99,7 +99,7 @@ class TestSuite:
process = None process = None
try: try:
process = subprocess.Popen(cmd, **kwargs) process = subprocess.Popen(cmd, **kwargs) # lint-amnesty, pylint: disable=consider-using-with
return self.is_success(process.wait()) return self.is_success(process.wait())
except KeyboardInterrupt: except KeyboardInterrupt:
kill_process(process) kill_process(process)

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -e set -e
export LOWER_PYLINT_THRESHOLD=200 export LOWER_PYLINT_THRESHOLD=0
export UPPER_PYLINT_THRESHOLD=200 export UPPER_PYLINT_THRESHOLD=1
export ESLINT_THRESHOLD=5300 export ESLINT_THRESHOLD=5300
export STYLELINT_THRESHOLD=880 export STYLELINT_THRESHOLD=880