prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>factories.py<|end_file_name|><|fim▁begin|>import factory from .models import User USER_PASSWORD = "2fast2furious" class UserFactory(factory.DjangoModelFactory): name = "John Doe" email = factory.Sequence(lambda n: "john{}@example.com".format(n)) password = factory.PostGenerationMethodCall('set_password', USER_PASSWORD) gender = "male" class Meta: <|fim_middle|> <|fim▁end|>
model = User
<|file_name|>test_universe_create.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ This pretty much just tests creating a user, a universe, a planet, a building type name, a building type, and a building. """ import os import sys import sqlalchemy sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import legendary_waffle # Database setup db_engine = sqlalchemy.create_engine("sqlite://") legendary_waffle.models.MODELBASE.metadata.create_all(db_engine) legendary_waffle.models.MODELBASE.metadata.bind = db_engine db_session = sqlalchemy.orm.sessionmaker(bind=db_engine) db = db_session() # Create the user legendary_waffle.model_create(db, legendary_waffle.models.User, name='sk4ly') print "Users: {}".format(legendary_waffle.model_read(db, legendary_waffle.models.User)) # Create the universe universe_config = { "name": 'poopiverse', "map_size": 1000,<|fim▁hole|> "max_planets": 1000, "max_players": 10 } legendary_waffle.model_create(db, legendary_waffle.models.Universe, **universe_config) print "Universe: {}".format(legendary_waffle.model_read(db, legendary_waffle.models.Universe)) # Create the planet planet_config = { "universe": 1, # The pkid of the universe 'poopiverse' "coordinate_x": 1, "coordinate_y": 1, "name": 'bloth', "habitable": True, "player_control": 1, # The pkid of user 'sk4ly' "default_condition": 1000, "default_resources": 1000, "current_condition": 1000, "current_resources": 1000 } legendary_waffle.model_create(db, legendary_waffle.models.Planet, **planet_config) print "Planet: {}".format(legendary_waffle.model_read(db, legendary_waffle.models.Planet)) # Create building type name legendary_waffle.model_create(db, legendary_waffle.models.BuildingTypeName, name="Control Center") print "Building Type Name: {}".format(legendary_waffle.model_read(db, legendary_waffle.models.BuildingTypeName)) # Create building type building_type_config = { "typename": 1, # The pkid of the building type name 'Control Center' "description": "This is the control center", "default_condition": 100, "default_firepower": 0, "default_storage": 100, "rhr_passive": 0, "rhr_active": 0, "rhr_destructive": 0, "build_resource_reqs": 500, } legendary_waffle.model_create(db, legendary_waffle.models.BuildingType, **building_type_config) print "Building Type: {}".format(legendary_waffle.model_read(db, legendary_waffle.models.BuildingType)) # Now create our new building building_config = { "building_type": 1, # The pkid of the building type with the name 'Control Center' "universe": 1, # The pkid of the universe 'poopiverse' "planet": 1, # The pkid of the planet 'bloth' "player_control": 1, # The pkid of the user 'sk4ly' } legendary_waffle.model_create(db, legendary_waffle.models.Building, **building_config) print "Building: {}".format(legendary_waffle.model_read(db, legendary_waffle.models.Building))<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""generated file, don't modify or your data will be lost""" try: __import__('pkg_resources').declare_namespace(__name__) except ImportError:<|fim▁hole|><|fim▁end|>
pass
<|file_name|>ptime.py<|end_file_name|><|fim▁begin|>import sys import time <|fim▁hole|>sleep = time.sleep if sys.platform == 'win32': time = time.clock else: time = time.time<|fim▁end|>
<|file_name|>ptime.py<|end_file_name|><|fim▁begin|>import sys import time sleep = time.sleep if sys.platform == 'win32': <|fim_middle|> else: time = time.time <|fim▁end|>
time = time.clock
<|file_name|>ptime.py<|end_file_name|><|fim▁begin|>import sys import time sleep = time.sleep if sys.platform == 'win32': time = time.clock else: <|fim_middle|> <|fim▁end|>
time = time.time
<|file_name|>aliases.py<|end_file_name|><|fim▁begin|>""" Encoding Aliases Support This module is used by the encodings package search function to map encodings names to module names. Note that the search function converts the encoding names to lower case and replaces hyphens with underscores *before* performing the lookup. """ aliases = { # Latin-1 'latin': 'latin_1', 'latin1': 'latin_1', # UTF-7 'utf7': 'utf_7', 'u7': 'utf_7', # UTF-8 'utf': 'utf_8', 'utf8': 'utf_8', 'u8': 'utf_8', 'utf8@ucs2': 'utf_8', 'utf8@ucs4': 'utf_8', # UTF-16 'utf16': 'utf_16', 'u16': 'utf_16', 'utf_16be': 'utf_16_be', 'utf_16le': 'utf_16_le', 'unicodebigunmarked': 'utf_16_be', 'unicodelittleunmarked': 'utf_16_le', # ASCII 'us_ascii': 'ascii', 'ansi_x3.4_1968': 'ascii', # used on Linux 'ansi_x3_4_1968': 'ascii', # used on BSD? '646': 'ascii', # used on Solaris # EBCDIC 'ebcdic_cp_us': 'cp037', 'ibm039': 'cp037', 'ibm1140': 'cp1140', # ISO '8859': 'latin_1', 'iso8859': 'latin_1', 'iso8859_1': 'latin_1', 'iso_8859_1': 'latin_1', 'iso_8859_10': 'iso8859_10', 'iso_8859_13': 'iso8859_13', 'iso_8859_14': 'iso8859_14', 'iso_8859_15': 'iso8859_15', 'iso_8859_2': 'iso8859_2', 'iso_8859_3': 'iso8859_3', 'iso_8859_4': 'iso8859_4', 'iso_8859_5': 'iso8859_5', 'iso_8859_6': 'iso8859_6', 'iso_8859_7': 'iso8859_7', 'iso_8859_8': 'iso8859_8', 'iso_8859_9': 'iso8859_9', # Mac 'maclatin2': 'mac_latin2', 'maccentraleurope': 'mac_latin2', 'maccyrillic': 'mac_cyrillic', 'macgreek': 'mac_greek', 'maciceland': 'mac_iceland', 'macroman': 'mac_roman', 'macturkish': 'mac_turkish', # Windows 'windows_1251': 'cp1251', 'windows_1252': 'cp1252', 'windows_1254': 'cp1254', 'windows_1255': 'cp1255', 'windows_1256': 'cp1256', 'windows_1257': 'cp1257', 'windows_1258': 'cp1258', # MBCS 'dbcs': 'mbcs', # Code pages '437': 'cp437', # CJK # # The codecs for these encodings are not distributed with the # Python core, but are included here for reference, since the # locale module relies on having these aliases available. # 'jis_7': 'jis_7', 'iso_2022_jp': 'jis_7', 'ujis': 'euc_jp', 'ajec': 'euc_jp', 'eucjp': 'euc_jp', 'tis260': 'tactis', 'sjis': 'shift_jis', # Content transfer/compression encodings 'rot13': 'rot_13', 'base64': 'base64_codec', 'base_64': 'base64_codec', 'zlib': 'zlib_codec', 'zip': 'zlib_codec', 'hex': 'hex_codec', 'uu': 'uu_codec', 'quopri': 'quopri_codec', 'quotedprintable': 'quopri_codec', 'quoted_printable': 'quopri_codec', <|fim▁hole|><|fim▁end|>
}
<|file_name|>faux-editor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # ansible-vault is a script that encrypts/decrypts YAML files. See # https://docs.ansible.com/playbooks_vault.html for more details. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import time<|fim▁hole|>import os def main(args): path = os.path.abspath(args[1]) fo = open(path, 'r+') content = fo.readlines() content.append('faux editor added at %s\n' % time.time()) fo.seek(0) fo.write(''.join(content)) fo.close() return 0 if __name__ == '__main__': sys.exit(main(sys.argv[:]))<|fim▁end|>
<|file_name|>faux-editor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # ansible-vault is a script that encrypts/decrypts YAML files. See # https://docs.ansible.com/playbooks_vault.html for more details. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import time import os def main(args): <|fim_middle|> if __name__ == '__main__': sys.exit(main(sys.argv[:])) <|fim▁end|>
path = os.path.abspath(args[1]) fo = open(path, 'r+') content = fo.readlines() content.append('faux editor added at %s\n' % time.time()) fo.seek(0) fo.write(''.join(content)) fo.close() return 0
<|file_name|>faux-editor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # ansible-vault is a script that encrypts/decrypts YAML files. See # https://docs.ansible.com/playbooks_vault.html for more details. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import time import os def main(args): path = os.path.abspath(args[1]) fo = open(path, 'r+') content = fo.readlines() content.append('faux editor added at %s\n' % time.time()) fo.seek(0) fo.write(''.join(content)) fo.close() return 0 if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
sys.exit(main(sys.argv[:]))
<|file_name|>faux-editor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # ansible-vault is a script that encrypts/decrypts YAML files. See # https://docs.ansible.com/playbooks_vault.html for more details. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import time import os def <|fim_middle|>(args): path = os.path.abspath(args[1]) fo = open(path, 'r+') content = fo.readlines() content.append('faux editor added at %s\n' % time.time()) fo.seek(0) fo.write(''.join(content)) fo.close() return 0 if __name__ == '__main__': sys.exit(main(sys.argv[:])) <|fim▁end|>
main
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self):<|fim▁hole|> return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver)<|fim▁end|>
""" :rtype: bool """
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): <|fim_middle|> "Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
"""Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): ""
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме"<|fim_middle|> _INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
"" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(dr<|fim_middle|> = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
iver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators<|fim_middle|> """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self):
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOC<|fim_middle|> _INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
ATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITL<|fim_middle|> lf).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
E_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, se
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav<|fim_middle|> Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
= NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') a<|fim_middle|> ригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
lso_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'о
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMovie<|fim_middle|> s_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
PageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._i
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_L<|fim_middle|> TTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
OCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BU
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') <|fim_middle|> Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self):<|fim_middle|> ge return HomePage(self._driver) <|fim▁end|>
""" :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePa
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim_middle|> <|fim▁end|>
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim_middle|> <|fim▁end|>
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver<|fim_middle|> self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
)
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ se<|fim_middle|>oviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
lf._click(BrowseM
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(Browse<|fim_middle|>EMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
MoviePageLocators.R
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_L<|fim_middle|>'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
OCATOR,
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return <|fim_middle|>present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
self._is_element_
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_<|fim_middle|>AR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
present(AddMoviePageLocators.YE
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCAT<|fim_middle|>tle="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim▁end|>
OR = (By.CSS_SELECTOR, 'img[ti
<|file_name|>movie.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) <|fim_middle|><|fim▁end|>
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id),<|fim▁hole|> lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def get_bug_info_uncached(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id)<|fim▁end|>
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): <|fim_middle|> <|fim▁end|>
"""An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def get_bug_info_uncached(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id)
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): <|fim_middle|> def get_bug_info_uncached(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id) <|fim▁end|>
"""Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60)
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def get_bug_info_uncached(self, repository, bug_id): <|fim_middle|> def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id) <|fim▁end|>
"""Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', }
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def get_bug_info_uncached(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def make_bug_cache_key(self, repository, bug_id): <|fim_middle|> <|fim▁end|>
"""Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id)
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def <|fim_middle|>(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def get_bug_info_uncached(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id) <|fim▁end|>
get_bug_info
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def <|fim_middle|>(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id) <|fim▁end|>
get_bug_info_uncached
<|file_name|>bugtracker.py<|end_file_name|><|fim▁begin|>from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. This should return a dictionary with 'summary', 'description', and 'status' keys. This is cached for 60 seconds to reduce the number of queries to the bug trackers and make things seem fast after the first infobox load, but is still a short enough time to give relatively fresh data. """ return cache_memoize(self.make_bug_cache_key(repository, bug_id), lambda: self.get_bug_info_uncached(repository, bug_id), expiration=60) def get_bug_info_uncached(self, repository, bug_id): """Get the information for the specified bug (implementation). This should be implemented by subclasses, and should return a dictionary with 'summary', 'description', and 'status' keys. If any of those are unsupported by the given bug tracker, the unknown values should be given as an empty string. """ return { 'summary': '', 'description': '', 'status': '', } def <|fim_middle|>(self, repository, bug_id): """Returns a key to use when caching fetched bug information.""" return 'repository-%s-bug-%s' % (repository.pk, bug_id) <|fim▁end|>
make_bug_cache_key
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|> __author__ = "Massimiliano Pippi & Federico Frenguelli" VERSION = __version__ # synonym<|fim▁end|>
__version__ = '0.8.1'
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) <|fim▁hole|>def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception<|fim▁end|>
@function_trace('safe_exec')
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): <|fim_middle|> @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
""" Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj)))
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): <|fim_middle|> <|fim▁end|>
""" Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): <|fim_middle|> with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
lazymod_py_file = lazymod_py_file[:-1]
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): <|fim_middle|> elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
for e in obj: update_hash(hasher, e)
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): <|fim_middle|> else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k])
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: <|fim_middle|> @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
hasher.update(six.b(repr(obj)))
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: <|fim_middle|> # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. <|fim_middle|> # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: <|fim_middle|> return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
raise SafeExecException(emsg)
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): <|fim_middle|> else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data)
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. <|fim_middle|> # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: <|fim_middle|> else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
exec_fn = codejail_not_safe_exec
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: <|fim_middle|> # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
exec_fn = codejail_safe_exec
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: <|fim_middle|> # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
emsg = None
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: <|fim_middle|> # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results))
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: <|fim_middle|> <|fim▁end|>
raise exception
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def <|fim_middle|>(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
update_hash
<|file_name|>safe_exec.py<|end_file_name|><|fim▁begin|>"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def <|fim_middle|>( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception <|fim▁end|>
safe_exec
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle<|fim▁hole|> "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.")<|fim▁end|>
distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): "<|fim_middle|> <|fim▁end|>
""Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.")
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): "<|fim_middle|> def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
""Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus."
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Mét<|fim_middle|> <|fim▁end|>
hode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.")
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personna <|fim_middle|> navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
ge << "|err|Vous n'êtes pas sur un navire.|ff|" return
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnag <|fim_middle|> personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
e << "|err|Vous n'êtes pas sur un navire.|ff|" return
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, <|fim_middle|> if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = <|fim_middle|> if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
t_salle distance = t_distance
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage <|fim_middle|> onnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
<< "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return pers
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.env <|fim_middle|> <|fim▁end|>
oyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.")
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def _<|fim_middle|>self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
_init__(
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant la commande 'débarquer'.""" from math import sqrt from primaires.interpreteur.commande.commande import Commande from secondaires.navigation.constantes import * class CmdDebarquer(Commande): """Commande 'debarquer'""" def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark") self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interp<|fim_middle|> personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return personnage.agir("bouger") # On va chercher la salle la plus proche etendue = navire.etendue # On cherche la salle de nagvire la plus proche d_salle = None # la salle de destination distance = 2 x, y, z = salle.coords.tuple() for t_salle in etendue.cotes.values(): if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance = t_distance if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage) d_salle.envoyer("{{}} arrive en sautant depuis {}.".format( navire.nom), personnage) salle.envoyer("{{}} saute sur {}.".format( d_salle.titre.lower()), personnage) importeur.hook["personnage:deplacer"].executer( personnage, d_salle, None, 0) if not hasattr(d_salle, "navire") or d_salle.navire is None: personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \ "avec %amarre% %amarre:attacher%.") <|fim▁end|>
reter(self,
<|file_name|>test.py<|end_file_name|><|fim▁begin|><|fim▁hole|>zhangyu<|fim▁end|>
<|file_name|>TestSyncGConfFolder.py<|end_file_name|><|fim▁begin|>#common sets up the conduit environment from common import * #setup test test = SimpleSyncTest() #Setup the key to sync gconf = test.get_dataprovider("GConfTwoWay") gconf.module.whitelist = ['/apps/metacity/general/num_workspaces'] folder = test.get_dataprovider("TestFolderTwoWay") test.prepare(gconf, folder) test.set_two_way_policy({"conflict":"ask","deleted":"ask"}) test.set_two_way_sync(True) a = test.get_source_count() b = test.get_sink_count() ok("Got items to sync (%s,%s)" % (a,b), a == 1 and b == 0) for i in (1,2,3,4): if i > 1: #Now modify the file<|fim▁hole|> ) f._set_file_mtime(datetime.datetime(2008,1,i)) a,b = test.sync() aborted,errored,conflicted = test.get_sync_result() ok("Sync #%s: Completed without conflicts" % i, aborted == False and errored == False and conflicted == False) ok("Sync #%s: All items (%s,%s)" % (i,a,b), a == b and a == 1) finished()<|fim▁end|>
f = folder.module.get( folder.module.get_all()[0]
<|file_name|>TestSyncGConfFolder.py<|end_file_name|><|fim▁begin|>#common sets up the conduit environment from common import * #setup test test = SimpleSyncTest() #Setup the key to sync gconf = test.get_dataprovider("GConfTwoWay") gconf.module.whitelist = ['/apps/metacity/general/num_workspaces'] folder = test.get_dataprovider("TestFolderTwoWay") test.prepare(gconf, folder) test.set_two_way_policy({"conflict":"ask","deleted":"ask"}) test.set_two_way_sync(True) a = test.get_source_count() b = test.get_sink_count() ok("Got items to sync (%s,%s)" % (a,b), a == 1 and b == 0) for i in (1,2,3,4): if i > 1: #Now modify the file <|fim_middle|> a,b = test.sync() aborted,errored,conflicted = test.get_sync_result() ok("Sync #%s: Completed without conflicts" % i, aborted == False and errored == False and conflicted == False) ok("Sync #%s: All items (%s,%s)" % (i,a,b), a == b and a == 1) finished() <|fim▁end|>
f = folder.module.get( folder.module.get_all()[0] ) f._set_file_mtime(datetime.datetime(2008,1,i))
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None:<|fim▁hole|> def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False<|fim▁end|>
self.description = "APSync {0} process".format(self.name) else: self.description = description
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): <|fim_middle|> class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
'''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): <|fim_middle|> def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): <|fim_middle|> def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config)
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): <|fim_middle|> def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.out_queue.put_nowait(ping(self.name, self.pid))
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): <|fim_middle|> def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.unload()
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): <|fim_middle|> def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
print self.name, 'called unload' self.unload_callback() self.needs_unloading.set()
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): <|fim_middle|> def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
''' overload to perform any module specific cleanup''' pass
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): <|fim_middle|> def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished'
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): <|fim_middle|> def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
pass
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): <|fim_middle|> def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished'
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): <|fim_middle|> def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
pass
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET <|fim_middle|> def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging'))
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): <|fim_middle|> class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): <|fim_middle|> <|fim▁end|>
def __init__(self, name): self.ack = False
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): <|fim_middle|> <|fim▁end|>
self.ack = False
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: <|fim_middle|> else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.description = "APSync {0} process".format(self.name)
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: <|fim_middle|> def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.description = description
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): <|fim_middle|> for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.config_list = config_list
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page <|fim_middle|> config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: <|fim_middle|> write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.config[k] = config_on_disk[k]
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: <|fim_middle|> while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.in_queue_thread.start()
<|file_name|>APSync_module.py<|end_file_name|><|fim▁begin|># A template for APSync process based modules from multiprocessing import Process, Event import threading import time import signal, select import traceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = "APSync {0} process".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print ("FATAL: module ({0}) exited while multiprocessing".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): <|fim_middle|> else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False <|fim▁end|>
self.unload()