Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix #13162: Add schema and introduce new approach for saving multiple images in suggestion handler. #14063

Merged
merged 186 commits into from Dec 15, 2021
Merged
Show file tree
Hide file tree
Changes from 161 commits
Commits
Show all changes
186 commits
Select commit Hold shift + click to select a range
601bb98
Add schema validation for suggestion handler
Oct 14, 2021
e662578
Add cmd constants of diffetent domain types
Oct 14, 2021
be889c1
Add validate_change method
Oct 14, 2021
2e07409
Remove suggestion handler name
Oct 14, 2021
f7ea2f5
Add skill_difficulty attribute
Oct 14, 2021
0d898ce
Add changes after Linter checks
Oct 14, 2021
09e2a69
Add changes after Linter checks
Oct 14, 2021
96bc10e
Remove Trailing whitespace
Oct 14, 2021
6ff7c73
Remove quotes from a string
Oct 14, 2021
eb9a4f1
Remove skill_difficulty attribute
Oct 15, 2021
901a1ae
Add QuestionSuggestionChange class in validate_change method
Oct 15, 2021
d8584bc
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 15, 2021
092e575
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 16, 2021
a18acf4
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 17, 2021
532ac78
Add schema for handling images
Oct 17, 2021
de69b61
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Oct 17, 2021
80a86f9
Add whitespace after colon
Oct 17, 2021
ed862b3
Add space before curly braces
Oct 17, 2021
10a9cc5
Change validate_change method name as suggested
Oct 17, 2021
1abcc4b
Rename argument for validation method in suggestion handler
Oct 17, 2021
47529f7
Remove exception handling in suggestion handler
Oct 17, 2021
a154c5f
Line too long lint check
Oct 17, 2021
60be8a4
Add method in next line
Oct 17, 2021
d59e7f3
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 19, 2021
683947f
Create a list of allowed commands in Question and Exp domain
Oct 19, 2021
5ad7307
Add a blank line
Oct 19, 2021
ba02f47
Add comments in a domain validator function
Oct 19, 2021
5ce77c1
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 21, 2021
6d20006
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 22, 2021
5e2c269
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 22, 2021
90e5cf1
Change key to access image blob
Oct 23, 2021
cd178d4
Replace fieldname args in upload_files method from file_name to image
Oct 23, 2021
5f0a97e
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 23, 2021
8e0587d
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Oct 23, 2021
72a94d1
Add whitespace
Oct 23, 2021
74dd86e
Write two statements equivalent to pass a test case
Oct 24, 2021
873b06b
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 24, 2021
bd2dc22
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 26, 2021
1557b61
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 27, 2021
5a53d36
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 28, 2021
911119d
Write validation_method for suggestion images
Oct 28, 2021
3c4e98e
Write schema for suggestion images
Oct 28, 2021
f30d150
Write scripts to fetch upload_suggestion_images
Oct 28, 2021
4eb3d84
Replace file content from upload_files to an object
Oct 28, 2021
597b1b3
Convert image blob from bytes to str
Oct 28, 2021
72353ac
Make changes after link checks
Oct 28, 2021
80de151
Make changes after link checks
Oct 28, 2021
e27d217
Make changes after link checks
Oct 28, 2021
6991138
Replace upload_files param with files object
Oct 29, 2021
ad08df4
Introduce a condition to handle images
Oct 29, 2021
6173625
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Oct 29, 2021
d3df22f
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Oct 29, 2021
97a7585
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 2, 2021
b089ba8
Pass payload object to save images
Nov 2, 2021
78c14f5
Revert "Pass payload object to save images"
Nov 2, 2021
dcb7d78
Pass payload object in upload_suggestion() to obtain images
Nov 2, 2021
4f5c44b
Perform encoding for all images
Nov 2, 2021
01431c3
Add condition for images that are string type
Nov 2, 2021
7b223ce
Add encoding for images
Nov 2, 2021
85b4904
Add condition for images that are of type string or bytes
Nov 2, 2021
38f13ee
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Nov 2, 2021
d4ff698
Decode images of type bytes
Nov 2, 2021
0d95113
Add whitespace
Nov 2, 2021
e011b81
Fix Line too long lint check
Nov 2, 2021
12b7029
Add annotations future import
Nov 2, 2021
7f4616b
Correctly sort imports
Nov 2, 2021
682201a
Write unit tests for ExplorationOrQuestion Change
Nov 2, 2021
861e6ee
Fix Lint check errors
Nov 2, 2021
2b2b2a6
Remove some arguments from domain_dict
Nov 2, 2021
4c797df
Add condition to validate missing cmd key
Nov 2, 2021
bb9de26
Add 'is' for reference equality to fix lint error
Nov 2, 2021
134f298
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 2, 2021
c02c589
Fix bugs - ExplorationOrQuestionsTests Class
Nov 3, 2021
f7074a1
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 3, 2021
0009585
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Nov 3, 2021
ca8ded1
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 3, 2021
97574ac
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 5, 2021
f2b20b3
Create lists to check domain allowed commands
Nov 5, 2021
ff76f69
Shift block of code left
Nov 5, 2021
5e10c46
Pass files dict to save images
Nov 5, 2021
365463f
Encode image data to write on disks
Nov 5, 2021
277cc17
Indent blocks of code and pass images through files dict
Nov 5, 2021
3f45b7f
Encode image data
Nov 5, 2021
f010dd4
Remove allowed commands list
Nov 5, 2021
33491f1
Remove allowed commands list
Nov 5, 2021
8e60118
Encode raw_image to bytes to validate
Nov 5, 2021
2397250
Decode images
Nov 5, 2021
f00513b
Write functions to encode and decode image
Nov 5, 2021
66dee09
Add intendation
Nov 5, 2021
c3c856e
Images are encoded/decoded from utils module
Nov 5, 2021
e8e103d
Make changes after lint checks
Nov 5, 2021
54e3219
Make changes after lint checks
Nov 5, 2021
0c6affd
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 6, 2021
cb0ebaf
Revert "Make changes after lint checks"
Nov 6, 2021
90c12db
Make changes after lint check
Nov 6, 2021
89785b6
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 8, 2021
37e0837
Add function to check image data
Nov 8, 2021
bb073e9
Add conditions to handle image data in suggestion handler
Nov 8, 2021
537b182
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Nov 8, 2021
98600c7
Make corrections after lint checks
Nov 8, 2021
0871c54
Make changes after lint checks
Nov 8, 2021
7c3f1f7
Break line after paranthesis
Nov 8, 2021
7ae03f6
Add 4 space indentation
Nov 8, 2021
bbbbeb9
Fix lint check errors
Nov 8, 2021
0b9d0d4
Fix lint check errors
Nov 8, 2021
150311b
Fix lint check error
Nov 8, 2021
67be327
Fix lint check error
Nov 8, 2021
c24a813
Add 4 space indentation to fix lint check error
Nov 8, 2021
77137c2
Make changes after code review
Nov 8, 2021
d400971
Add test for is_base64_encoded method
Nov 8, 2021
5261ec7
Add an issue reference to handle images in suggestion controller
Nov 8, 2021
adab06a
Fix lint check errors
Nov 8, 2021
98be9db
Fix error in a test case
Nov 8, 2021
d0a4eb4
Fix call to untyped function error
Nov 8, 2021
541eda6
Add no-untyped-call comment
Nov 8, 2021
354efab
Add test for ValidSuggestionImages
Nov 9, 2021
029d9ef
FIx lint check errors
Nov 9, 2021
5b33a80
Put comment in a new line
Nov 9, 2021
6220cb7
Fix errors to pass lint check
Nov 9, 2021
3087e1c
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 9, 2021
64ef728
Add a test case to fix coverage failure
Nov 9, 2021
bf057ad
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Nov 9, 2021
6baa95f
Remove trailing whitespace
Nov 9, 2021
c029d82
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 10, 2021
809a1ed
Make changes after final review
Nov 10, 2021
d86de72
Add encoding args in test
Nov 10, 2021
45c7fa6
Make some changes after code review
Nov 12, 2021
b65f746
Encode image blobs from frontend for suggestion handler
Nov 17, 2021
f93c06e
Declare files as undefined
Nov 17, 2021
e44ce72
Fix typescript check fail
Nov 17, 2021
c3f05ad
Fix lint check issues
Nov 17, 2021
aec86ed
Refactor code to send multiple images to suggestion handler
Nov 19, 2021
d122e30
Fix typescript lint checkts
Nov 19, 2021
da42af6
Merge branch 'develop' into add-schema-suggestion-handler
chiragbaid7 Nov 19, 2021
a24b480
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Nov 19, 2021
ba2fa3f
Remove suggestionhandler from schema handler class list
Nov 22, 2021
9e87910
Make changes to add files as a key in postData
Nov 22, 2021
4164c36
Fix Lint check errors
Nov 22, 2021
0a0fb76
Remove ImagesDict function
Nov 23, 2021
9cb304d
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 24, 2021
275c628
Update translate-text.service.ts
chiragbaid7 Nov 25, 2021
b6c64d5
Update translation-modal.component.ts
chiragbaid7 Nov 25, 2021
00c01a3
Merge branch 'develop' into add-schema-suggestion-handler
chiragbaid7 Nov 27, 2021
6e74707
Add description in suggestion tests
chiragbaid7 Nov 27, 2021
2322936
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 29, 2021
7ec2c60
Make changes after code review
Nov 30, 2021
d6a6415
Add flushMicrotasks() and make some changes in Frontend tests
Nov 30, 2021
f05a205
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Nov 30, 2021
34c605f
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Nov 30, 2021
37188a5
Make changes to fix coverage test issue
Dec 1, 2021
9c5ba71
Write comments in blobtobase64() method
Dec 1, 2021
cc55c92
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Dec 1, 2021
dcfc3b5
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 1, 2021
a1d6ce7
Add interface for posData to support optional key
Dec 2, 2021
cca58d6
Make changes to fix front-end failures
Dec 2, 2021
3f03300
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Dec 2, 2021
980abe0
Fix lint check errors
Dec 2, 2021
449e63f
Make changes to pass coverage tests
Dec 3, 2021
2a6c417
Merge branch 'develop' into add-schema-suggestion-handler
chiragbaid7 Dec 3, 2021
19d7530
Fix lint errors
Dec 3, 2021
7396e74
Merge branch 'develop' into add-schema-suggestion-handler
chiragbaid7 Dec 3, 2021
a7319de
Make changes after review
Dec 5, 2021
880a1b7
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Dec 5, 2021
96a4e3a
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 5, 2021
f8d430e
Make changes in frontend after code review
Dec 8, 2021
ba209d3
Make changes in backend after code review
Dec 8, 2021
29f2137
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Dec 8, 2021
2f49274
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 8, 2021
9f5e58d
Fix lint check issues
Dec 8, 2021
f85bf72
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Dec 8, 2021
8ca1c3c
Fix lint check issues
Dec 8, 2021
6d4f2bb
Return objects after validation
Dec 8, 2021
e24082d
Fix lint check issues
Dec 8, 2021
dbf42be
Fix lint check issues
Dec 8, 2021
12da771
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 8, 2021
e2c2f85
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 8, 2021
61d67bd
Fix errors
Dec 9, 2021
53cbd6b
Fix backend test issues
Dec 9, 2021
a02e7fd
Add whitespace
Dec 9, 2021
d536a4c
Fix backend test failure
Dec 10, 2021
15da453
Add validation and test case for prefix in data url
Dec 10, 2021
118ab53
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 10, 2021
06630ee
Address review comments
Dec 10, 2021
c13841a
Merge branch 'add-schema-suggestion-handler' of https://github.com/ch…
Dec 10, 2021
9a95622
Update image_validation_services_test.py
chiragbaid7 Dec 10, 2021
31ee29f
Merge branch 'oppia:develop' into add-schema-suggestion-handler
chiragbaid7 Dec 13, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions core/controllers/domain_objects_validator.py
Expand Up @@ -26,11 +26,40 @@
from core.domain import collection_domain
from core.domain import config_domain
from core.domain import exp_domain
from core.domain import image_validation_services
from core.domain import question_domain
from core.domain import state_domain

from typing import Dict, Optional, Union


def validate_exploration_or_question_change(obj):
"""Validates Exploration or Question change.

Args:
obj: dict. Data that needs to be validated.
vojtechjelinek marked this conversation as resolved.
Show resolved Hide resolved
"""
# No explicit call to validate_dict is required, because
# ExplorationChange or QuestionSuggestionChange calls
# validate method while initialization.
if obj.get('cmd') is None:
raise base.BaseHandler.InvalidInputException(
'Missing cmd key in change dict')
else:
exp_change_commands = [command['name'] for command in
exp_domain.ExplorationChange.ALLOWED_COMMANDS]
question_change_commands = [command['name'] for command in
question_domain.QuestionChange.ALLOWED_COMMANDS]

if obj['cmd'] in exp_change_commands:
exp_domain.ExplorationChange(obj)
elif obj['cmd'] in question_change_commands:
question_domain.QuestionSuggestionChange(obj)
else:
raise base.BaseHandler.InvalidInputException(
'%s cmd is not allowed.' % obj['cmd'])


def validate_exploration_change(obj):
"""Validates exploration change.

Expand Down Expand Up @@ -180,6 +209,17 @@ def validate_aggregated_stats(aggregated_stats):
'stats dict.' % (state_stats_property, state_name))


def validate_suggestion_images(files):
"""Validates the files dict.

Args:
files: dict. Data that needs to be validated.
"""
for filename, raw_image in files.items():
image_validation_services.validate_image_and_filename(
raw_image, filename)
Copy link
Member

Choose a reason for hiding this comment

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

Not sure how this is a domain object validator?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Schema type dict requires all key names to be present in the payload object but image filenames are unknown so only way to validate image data is by passing it through domain object validator.



def validate_params_dict(params):
"""validates params data type

Expand Down
72 changes: 72 additions & 0 deletions core/controllers/domain_objects_validator_test.py
Expand Up @@ -16,6 +16,10 @@

from __future__ import annotations

import os

from core import feconf
from core import python_utils
from core import utils
from core.controllers import domain_objects_validator
from core.tests import test_utils
Expand Down Expand Up @@ -46,6 +50,53 @@ def test_correct_object_do_not_raises_exception(self) -> None:
correct_change_dict)


class ValidateExplorationOrQuestionChangeTests(test_utils.GenericTestBase):
"""Tests to validate domain objects coming from frontend."""

def test_incorrect_exp_domain_object_raises_exception(self) -> None:
incorrect_change_dict = {
'state_name': 'State 3',
'content_id': 'content',
'language_code': 'hi',
'content_html': '<p>old content html</p>',
'translation_html': '<p>In Hindi</p>',
'data_format': 'html'
}
with self.assertRaisesRegexp( # type: ignore[no-untyped-call]
Exception, 'Missing cmd key in change dict'
):
domain_objects_validator.validate_exploration_or_question_change(
incorrect_change_dict)

incorrect_change_dict = {
'cmd': 'add_subtopic',
'state_name': 'State 3',
'content_id': 'content',
'language_code': 'hi',
'content_html': '<p>old content html</p>',
'translation_html': '<p>In Hindi</p>',
'data_format': 'html'
}
with self.assertRaisesRegexp( # type: ignore[no-untyped-call]
Exception, '%s cmd is not allowed.' % incorrect_change_dict['cmd']
):
domain_objects_validator.validate_exploration_or_question_change(
incorrect_change_dict)

def test_correct_exp_domain_object_do_not_raises_exception(self) -> None:
correct_change_dict = {
'cmd': 'add_written_translation',
'state_name': 'State 3',
'content_id': 'content',
'language_code': 'hi',
'content_html': '<p>old content html</p>',
'translation_html': '<p>In Hindi</p>',
'data_format': 'html'
}
domain_objects_validator.validate_exploration_or_question_change(
correct_change_dict)


class ValidateCollectionChangeTests(test_utils.GenericTestBase):
"""Tests to validate domain objects coming from API."""

Expand Down Expand Up @@ -225,6 +276,27 @@ def test_invalid_object_raises_exception(self) -> None:
domain_objects_validator.validate_state_dict(invalid_state_dict)


class ValidateSuggestionImagesTests(test_utils.GenericTestBase):
"""Tests to validate suggestion images coming from frontend."""

def test_invalid_images_raises_exception(self) -> None:
files = {'file.svg': None}
with self.assertRaisesRegexp( # type: ignore[no-untyped-call]
Exception, 'No image supplied'
):
domain_objects_validator.validate_suggestion_images(files)

def test_valid_images_do_not_raises_exception(self) -> None:
files = {'img.png': None, 'test2_svg.svg': None}
for filename in files:
with python_utils.open_file(
os.path.join(feconf.TESTS_DATA_DIR, filename), 'rb',
encoding=None
) as f:
files[filename] = f.read()
domain_objects_validator.validate_suggestion_images(files)


class ValidateParamsDict(test_utils.GenericTestBase):
"""Tests to validate the data type of params"""

Expand Down
96 changes: 76 additions & 20 deletions core/controllers/suggestion.py
Expand Up @@ -18,13 +18,15 @@

from __future__ import annotations

import base64
import logging

from core import feconf
from core import utils
from core.constants import constants
from core.controllers import acl_decorators
from core.controllers import base
from core.controllers import domain_objects_validator
from core.domain import exp_fetchers
from core.domain import fs_services
from core.domain import html_cleaner
Expand All @@ -38,23 +40,77 @@
class SuggestionHandler(base.BaseHandler):
""""Handles operations relating to suggestions."""

URL_PATH_ARGS_SCHEMAS = {}
HANDLER_ARGS_SCHEMAS = {
'POST': {
'suggestion_type': {
'schema': {
'type': 'basestring',
'choices': feconf.SUGGESTION_TYPE_CHOICES
}
},
'target_type': {
'schema': {
'type': 'basestring',
'choices': feconf.SUGGESTION_TARGET_TYPE_CHOICES
}
},
'target_id': {
'schema': {
'type': 'basestring'
}
},
'target_version_at_submission': {
'schema': {
'type': 'int',
'validators': [{
'id': 'is_at_least',
'min_value': 1
}]
}
},
'change': {
'schema': {
'type': 'object_dict',
'validation_method': (
domain_objects_validator.
validate_exploration_or_question_change
Copy link
Member

Choose a reason for hiding this comment

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

Is it possible to have validate_suggestion_change?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done.

)
}
},
'description': {
'schema': {
'type': 'basestring'
}
},
'files': {
'schema': {
'type': 'object_dict',
'validation_method': (
domain_objects_validator.validate_suggestion_images
)
},
'default_value': None
}
}
}

@acl_decorators.can_suggest_changes
def post(self):
"""Handles POST requests."""
if (self.payload.get('suggestion_type') ==
if (self.normalized_payload.get('suggestion_type') ==
feconf.SUGGESTION_TYPE_EDIT_STATE_CONTENT):
raise self.InvalidInputException(
'Content suggestion submissions are no longer supported.')
vojtechjelinek marked this conversation as resolved.
Show resolved Hide resolved

try:
suggestion = suggestion_services.create_suggestion(
self.payload.get('suggestion_type'),
self.payload.get('target_type'), self.payload.get('target_id'),
self.payload.get('target_version_at_submission'),
self.user_id, self.payload.get('change'),
self.payload.get('description'))
except utils.ValidationError as e:
raise self.InvalidInputException(e)
suggestion = suggestion_services.create_suggestion(
self.normalized_payload.get('suggestion_type'),
self.normalized_payload.get('target_type'),
self.normalized_payload.get('target_id'),
self.normalized_payload.get('target_version_at_submission'),
self.user_id,
self.normalized_payload.get('change'),
self.normalized_payload.get('description'))

suggestion_change = suggestion.change
if (
Expand All @@ -80,7 +136,7 @@ def post(self):
if self.payload.get(
'suggestion_type') != (feconf.SUGGESTION_TYPE_ADD_QUESTION):
_upload_suggestion_images(
self.request,
self.normalized_payload.get('files'),
suggestion,
suggestion.get_new_image_filenames_added_in_suggestion())

Expand Down Expand Up @@ -509,11 +565,11 @@ def _construct_exploration_suggestions(suggestions):
return suggestion_dicts


def _upload_suggestion_images(request, suggestion, filenames):
def _upload_suggestion_images(files, suggestion, filenames):
"""Saves a suggestion's images to storage.

Args:
request: webapp2.Request. Request object containing a mapping of image
files: dict. Files containing a mapping of image
filename to image blob.
suggestion: BaseSuggestion. The suggestion for which images are being
uploaded.
Expand All @@ -523,7 +579,7 @@ def _upload_suggestion_images(request, suggestion, filenames):
# TODO(#10513): Find a way to save the images before the suggestion is
# created.
for filename in filenames:
image = request.get(filename)
image = files.get(filename) if files else None
Copy link
Member

Choose a reason for hiding this comment

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

As per the docstring we are expecting files to be a dict, right? in that case why do we need the if files check?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. I have removed this extra check and some unnecessary validation error part in this function because we are already performing validation of images in the schema.

if not image:
logging.exception(
'Image not provided for file with name %s when the '
Expand All @@ -532,12 +588,12 @@ def _upload_suggestion_images(request, suggestion, filenames):
raise base.BaseHandler.InvalidInputException(
'No image data provided for file with name %s.'
% (filename))
try:
file_format = (
image_validation_services.validate_image_and_filename(
image, filename))
except utils.ValidationError as e:
raise base.BaseHandler.InvalidInputException('%s' % (e))
# TODO(#14204): Refactor this to use the normalized_payload files.
Copy link
Member

Choose a reason for hiding this comment

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

Do we still need this TODO?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. I have removed this.

if utils.is_base64_encoded(image):
image = base64.decodebytes(image.encode('utf-8'))
file_format = (
image_validation_services.validate_image_and_filename(
image, filename))
image_is_compressible = (
file_format in feconf.COMPRESSIBLE_IMAGE_FORMATS)
fs_services.save_original_and_compressed_versions_of_image(
Expand Down
38 changes: 24 additions & 14 deletions core/controllers/suggestion_test.py
Expand Up @@ -18,6 +18,7 @@

from __future__ import annotations

import base64
import os

from core import feconf
Expand Down Expand Up @@ -741,10 +742,14 @@ def test_translation_suggestion_creation_with_new_images(self):
'</oppia-noninteractive-image>'),
'data_format': 'html'
},
}, csrf_token=csrf_token,
upload_files=(
('translation_image.png', 'translation_image.png', raw_image), )
)
'description': 'test',
'files': {
'translation_image.png': (
base64.b64encode(raw_image).decode('utf-8'))
},
},
csrf_token=csrf_token
)

fs = fs_domain.AbstractFileSystem(
fs_domain.GcsFileSystem(
Expand Down Expand Up @@ -981,7 +986,8 @@ def test_update_suggestion_updates_question_suggestion_content(self):
suggestion.suggestion_id), {
'question_state_data': question_state_data,
'skill_difficulty': 0.6
}, csrf_token=csrf_token, upload_files=(
},
csrf_token=csrf_token, upload_files=(
('img.png', 'img.png', raw_image),))

updated_suggestion = suggestion_services.get_suggestion_by_id(
Expand Down Expand Up @@ -1330,6 +1336,7 @@ def test_suggestion_creation_when_images_are_not_provided(self):
'translation_html': valid_html,
'data_format': 'html'
},
'description': 'test'
}, csrf_token=csrf_token, expected_status_int=400)

self.assertIn(
Expand Down Expand Up @@ -1405,10 +1412,10 @@ def test_suggestion_creation_when_images_are_not_valid(self):
'translation_html': valid_html,
'data_format': 'html'
},
}, csrf_token=csrf_token,
upload_files=(
('file.svg', 'file.svg', large_image),),
expected_status_int=400)
'description': 'test',
'files': {'file.svg': large_image},
}, csrf_token=csrf_token, expected_status_int=400,
)

self.assertIn(
'Image exceeds file size limit of 100 KB.',
Expand Down Expand Up @@ -1742,8 +1749,8 @@ def test_create_suggestion_invalid_target_version_input(self):

self.assertEqual(
response['error'],
'Expected target_version_at_submission to be an int, '
'received <class \'str\'>'
'Schema validation for \'target_version_at_submission\' failed: '
'Could not convert str to int: invalid_target_version'
)
self.assertEqual(len(suggestions), 1)
self.logout()
Expand Down Expand Up @@ -1793,9 +1800,12 @@ def test_suggestion_creation_with_valid_images(self):
'skill_id': self.SKILL_ID,
'skill_difficulty': 0.3
},
'description': 'Add new question to skill'
}, csrf_token=csrf_token, upload_files=(
('file.svg', 'file.svg', raw_image), ))
'description': 'Add new question to skill',
'files': {
'file.svg': (
base64.b64encode(raw_image).decode('utf-8'))
}
}, csrf_token=csrf_token,)
self.logout()


Expand Down