prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: <|fim_middle|> @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
return self.searcher.live_trials
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: <|fim_middle|> <|fim▁end|>
return self.searcher.results
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: <|fim_middle|> return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
self.live_trials[trial_id] = 1 return {"test_variable": 2}
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: <|fim_middle|> if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
self._process_result(result)
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: <|fim_middle|> def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
del self.live_trials[trial_id]
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: <|fim_middle|> super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent )
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def <|fim_middle|>(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
__init__
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def <|fim_middle|>(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
suggest
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def <|fim_middle|>(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
on_trial_result
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def <|fim_middle|>( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
on_trial_complete
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def <|fim_middle|>(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
_process_result
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def <|fim_middle|>(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
__init__
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def <|fim_middle|>(self) -> List[Trial]: return self.searcher.live_trials @property def results(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
live_trials
<|file_name|>_mock.py<|end_file_name|><|fim▁begin|>from typing import Dict, List, Optional from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter from ray.tune.suggest.search_generator import SearchGenerator from ray.tune.trial import Trial class _MockSearcher(Searcher): def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs) def suggest(self, trial_id: str): if not self.stall: self.live_trials[trial_id] = 1 return {"test_variable": 2} return None def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result] def on_trial_complete( self, trial_id: str, result: Optional[Dict] = None, error: bool = False ): self.counter["complete"] += 1 if result: self._process_result(result) if trial_id in self.live_trials: del self.live_trials[trial_id] def _process_result(self, result: Dict): self.final_results += [result] class _MockSuggestionAlgorithm(SearchGenerator): def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher) @property def live_trials(self) -> List[Trial]: return self.searcher.live_trials @property def <|fim_middle|>(self) -> List[Dict]: return self.searcher.results <|fim▁end|>
results
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name'])<|fim▁hole|> """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly'])<|fim▁end|>
self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self):
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): <|fim_middle|> <|fim▁end|>
"""Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly'])
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): <|fim_middle|> @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume()
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): <|fim_middle|> @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
"""Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available')
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): <|fim_middle|> @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
"""Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable'])
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): <|fim_middle|> @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
"""Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id'])
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): <|fim_middle|> @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
"""Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format'])
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): <|fim_middle|> @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
"""Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status'])
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): <|fim_middle|> <|fim▁end|>
"""Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly'])
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def <|fim_middle|>(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
resource_setup
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def <|fim_middle|>(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
test_attach_detach_volume_to_instance
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def <|fim_middle|>(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
test_volume_bootable
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def <|fim_middle|>(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
test_get_volume_attachment
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def <|fim_middle|>(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
test_volume_upload
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def <|fim_middle|>(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def test_volume_readonly_update(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
test_reserve_unreserve_volume
<|file_name|>test_volumes_actions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.common import utils from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib.common.utils import test_utils from tempest.lib import decorators CONF = config.CONF class VolumesActionsTest(base.BaseVolumeTest): """Test volume actions""" create_default_network = True @classmethod def resource_setup(cls): super(VolumesActionsTest, cls).resource_setup() # Create a test shared volume for attach/detach tests cls.volume = cls.create_volume() @decorators.idempotent_id('fff42874-7db5-4487-a8e1-ddda5fb5288d') @decorators.attr(type='smoke') @utils.services('compute') def test_attach_detach_volume_to_instance(self): """Test attaching and detaching volume to instance""" # Create a server server = self.create_server() # Volume is attached and detached successfully from an instance self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.volumes_client.detach_volume(self.volume['id']) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') @decorators.idempotent_id('63e21b4c-0a0c-41f6-bfc3-7c2816815599') def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable']) @decorators.idempotent_id('9516a2c8-9135-488c-8dd6-5677a7e5f371') @utils.services('compute') def test_get_volume_attachment(self): """Test getting volume attachments Attach a volume to a server, and then retrieve volume's attachments info. """ # Create a server server = self.create_server() # Verify that a volume's attachment information is retrieved self.volumes_client.attach_volume(self.volume['id'], instance_uuid=server['id'], mountpoint='/dev/%s' % CONF.compute.volume_device_name) waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'in-use') self.addCleanup(waiters.wait_for_volume_resource_status, self.volumes_client, self.volume['id'], 'available') self.addCleanup(self.volumes_client.detach_volume, self.volume['id']) volume = self.volumes_client.show_volume(self.volume['id'])['volume'] attachment = volume['attachments'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'], attachment['volume_id']) @decorators.idempotent_id('d8f1ca95-3d5b-44a3-b8ca-909691c9532d') @utils.services('image') def test_volume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # using the Glance images_client and from Cinder via tearDownClass. image_name = data_utils.rand_name(self.__class__.__name__ + '-Image') body = self.volumes_client.upload_volume( self.volume['id'], image_name=image_name, disk_format=CONF.volume.disk_format)['os-volume_upload_image'] image_id = body["image_id"] self.addCleanup(test_utils.call_and_ignore_notfound_exc, self.images_client.delete_image, image_id) waiters.wait_for_image_status(self.images_client, image_id, 'active') waiters.wait_for_volume_resource_status(self.volumes_client, self.volume['id'], 'available') image_info = self.images_client.show_image(image_id) self.assertEqual(image_name, image_info['name']) self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) @decorators.idempotent_id('92c4ef64-51b2-40c0-9f7e-4749fbaaba33') def test_reserve_unreserve_volume(self): """Test reserving and unreserving volume""" # Mark volume as reserved. self.volumes_client.reserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('attaching', body['status']) # Unmark volume as reserved. self.volumes_client.unreserve_volume(self.volume['id']) # To get the volume info body = self.volumes_client.show_volume(self.volume['id'])['volume'] self.assertIn('available', body['status']) @decorators.idempotent_id('fff74e1e-5bd3-4b33-9ea9-24c103bc3f59') def <|fim_middle|>(self): """Test updating and retrieve volume's readonly flag""" for readonly in [True, False]: # Update volume readonly self.volumes_client.update_volume_readonly(self.volume['id'], readonly=readonly) # Get Volume information fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # NOTE(masayukig): 'readonly' is "True" or "False" in the current # cinder implementation. So we need to cast boolean values to str # to compare here. self.assertEqual(str(readonly), fetched_volume['metadata']['readonly']) <|fim▁end|>
test_volume_readonly_update
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-09 11:32 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Company', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', django.contrib.postgres.fields.jsonb.JSONField(default={})), ('financial_data', django.contrib.postgres.fields.jsonb.JSONField(default={})), ('stock_data', django.contrib.postgres.fields.jsonb.JSONField(default={})), ], ), migrations.CreateModel( name='Exchange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', django.contrib.postgres.fields.jsonb.JSONField(default={})), ], ), migrations.CreateModel( name='News', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', models.URLField(max_length=255)), ('source_title', models.CharField(max_length=255)), ('companies', models.ManyToManyField(related_name='news', to='intellifin.Company')),<|fim▁hole|> model_name='company', name='exchange', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='companies', to='intellifin.Exchange'), ), ]<|fim▁end|>
], ), migrations.AddField(
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-09 11:32 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Company', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', django.contrib.postgres.fields.jsonb.JSONField(default={})), ('financial_data', django.contrib.postgres.fields.jsonb.JSONField(default={})), ('stock_data', django.contrib.postgres.fields.jsonb.JSONField(default={})), ], ), migrations.CreateModel( name='Exchange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', django.contrib.postgres.fields.jsonb.JSONField(default={})), ], ), migrations.CreateModel( name='News', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', models.URLField(max_length=255)), ('source_title', models.CharField(max_length=255)), ('companies', models.ManyToManyField(related_name='news', to='intellifin.Company')), ], ), migrations.AddField( model_name='company', name='exchange', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='companies', to='intellifin.Exchange'), ), ]
<|file_name|>csdn.py<|end_file_name|><|fim▁begin|># coding: utf-8 from common import base class Plugin(base.BASE): __name__ = 'csdn' __title__ = 'CSDN' __url__ = 'http://www.csdn.net/' def register(self, target): self.information = { 'email': { 'url': 'http://passport.csdn.net/account/register', 'method': 'get', 'settings': { 'params': { 'action': 'validateEmail', 'email': target<|fim▁hole|> }, 'result': { 'type': 'str', 'value': 'false' } } }<|fim▁end|>
}
<|file_name|>csdn.py<|end_file_name|><|fim▁begin|># coding: utf-8 from common import base class Plugin(base.BASE): <|fim_middle|> <|fim▁end|>
__name__ = 'csdn' __title__ = 'CSDN' __url__ = 'http://www.csdn.net/' def register(self, target): self.information = { 'email': { 'url': 'http://passport.csdn.net/account/register', 'method': 'get', 'settings': { 'params': { 'action': 'validateEmail', 'email': target } }, 'result': { 'type': 'str', 'value': 'false' } } }
<|file_name|>csdn.py<|end_file_name|><|fim▁begin|># coding: utf-8 from common import base class Plugin(base.BASE): __name__ = 'csdn' __title__ = 'CSDN' __url__ = 'http://www.csdn.net/' def register(self, target): <|fim_middle|> <|fim▁end|>
self.information = { 'email': { 'url': 'http://passport.csdn.net/account/register', 'method': 'get', 'settings': { 'params': { 'action': 'validateEmail', 'email': target } }, 'result': { 'type': 'str', 'value': 'false' } } }
<|file_name|>csdn.py<|end_file_name|><|fim▁begin|># coding: utf-8 from common import base class Plugin(base.BASE): __name__ = 'csdn' __title__ = 'CSDN' __url__ = 'http://www.csdn.net/' def <|fim_middle|>(self, target): self.information = { 'email': { 'url': 'http://passport.csdn.net/account/register', 'method': 'get', 'settings': { 'params': { 'action': 'validateEmail', 'email': target } }, 'result': { 'type': 'str', 'value': 'false' } } } <|fim▁end|>
register
<|file_name|>olt_los_alarm.py<|end_file_name|><|fim▁begin|># Copyright 2017-present Adtran, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory from voltha.extensions.alarms.adapter_alarms import AlarmBase class OltLosAlarm(AlarmBase): def __init__(self, alarm_mgr, intf_id, port_type_name): super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS', alarm='OLT_LOS', alarm_category=AlarmEventCategory.OLT, alarm_type=AlarmEventType.COMMUNICATION, alarm_severity=AlarmEventSeverity.MAJOR) # Added port type to indicate if alarm was on NNI or PON self._intf_id = intf_id self._port_type_name = port_type_name def get_context_data(self): return {'olt-intf-id:': self._intf_id,<|fim▁hole|><|fim▁end|>
'olt-port-type-name': self._port_type_name}
<|file_name|>olt_los_alarm.py<|end_file_name|><|fim▁begin|># Copyright 2017-present Adtran, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory from voltha.extensions.alarms.adapter_alarms import AlarmBase class OltLosAlarm(AlarmBase): <|fim_middle|> <|fim▁end|>
def __init__(self, alarm_mgr, intf_id, port_type_name): super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS', alarm='OLT_LOS', alarm_category=AlarmEventCategory.OLT, alarm_type=AlarmEventType.COMMUNICATION, alarm_severity=AlarmEventSeverity.MAJOR) # Added port type to indicate if alarm was on NNI or PON self._intf_id = intf_id self._port_type_name = port_type_name def get_context_data(self): return {'olt-intf-id:': self._intf_id, 'olt-port-type-name': self._port_type_name}
<|file_name|>olt_los_alarm.py<|end_file_name|><|fim▁begin|># Copyright 2017-present Adtran, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory from voltha.extensions.alarms.adapter_alarms import AlarmBase class OltLosAlarm(AlarmBase): def __init__(self, alarm_mgr, intf_id, port_type_name): <|fim_middle|> def get_context_data(self): return {'olt-intf-id:': self._intf_id, 'olt-port-type-name': self._port_type_name} <|fim▁end|>
super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS', alarm='OLT_LOS', alarm_category=AlarmEventCategory.OLT, alarm_type=AlarmEventType.COMMUNICATION, alarm_severity=AlarmEventSeverity.MAJOR) # Added port type to indicate if alarm was on NNI or PON self._intf_id = intf_id self._port_type_name = port_type_name
<|file_name|>olt_los_alarm.py<|end_file_name|><|fim▁begin|># Copyright 2017-present Adtran, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory from voltha.extensions.alarms.adapter_alarms import AlarmBase class OltLosAlarm(AlarmBase): def __init__(self, alarm_mgr, intf_id, port_type_name): super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS', alarm='OLT_LOS', alarm_category=AlarmEventCategory.OLT, alarm_type=AlarmEventType.COMMUNICATION, alarm_severity=AlarmEventSeverity.MAJOR) # Added port type to indicate if alarm was on NNI or PON self._intf_id = intf_id self._port_type_name = port_type_name def get_context_data(self): <|fim_middle|> <|fim▁end|>
return {'olt-intf-id:': self._intf_id, 'olt-port-type-name': self._port_type_name}
<|file_name|>olt_los_alarm.py<|end_file_name|><|fim▁begin|># Copyright 2017-present Adtran, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory from voltha.extensions.alarms.adapter_alarms import AlarmBase class OltLosAlarm(AlarmBase): def <|fim_middle|>(self, alarm_mgr, intf_id, port_type_name): super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS', alarm='OLT_LOS', alarm_category=AlarmEventCategory.OLT, alarm_type=AlarmEventType.COMMUNICATION, alarm_severity=AlarmEventSeverity.MAJOR) # Added port type to indicate if alarm was on NNI or PON self._intf_id = intf_id self._port_type_name = port_type_name def get_context_data(self): return {'olt-intf-id:': self._intf_id, 'olt-port-type-name': self._port_type_name} <|fim▁end|>
__init__
<|file_name|>olt_los_alarm.py<|end_file_name|><|fim▁begin|># Copyright 2017-present Adtran, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory from voltha.extensions.alarms.adapter_alarms import AlarmBase class OltLosAlarm(AlarmBase): def __init__(self, alarm_mgr, intf_id, port_type_name): super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS', alarm='OLT_LOS', alarm_category=AlarmEventCategory.OLT, alarm_type=AlarmEventType.COMMUNICATION, alarm_severity=AlarmEventSeverity.MAJOR) # Added port type to indicate if alarm was on NNI or PON self._intf_id = intf_id self._port_type_name = port_type_name def <|fim_middle|>(self): return {'olt-intf-id:': self._intf_id, 'olt-port-type-name': self._port_type_name} <|fim▁end|>
get_context_data
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): previous, current = 0, 1<|fim▁hole|> yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)<|fim▁end|>
while True: previous, current = current, previous + current
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): <|fim_middle|> def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)<|fim▁end|>
previous, current = 0, 1 while True: previous, current = current, previous + current yield current
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): <|fim_middle|> print problem2(4000000)<|fim▁end|>
sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: <|fim_middle|> if n % 2 == 0: sum += n return sum print problem2(4000000)<|fim▁end|>
break
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: <|fim_middle|> return sum print problem2(4000000)<|fim▁end|>
sum += n
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def <|fim_middle|>(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)<|fim▁end|>
fibs
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def <|fim_middle|>(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)<|fim▁end|>
problem2
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self):<|fim▁hole|> character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid'])<|fim▁end|>
self.assertEqual( self.count - self.pivot - 1,
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): <|fim_middle|> <|fim▁end|>
def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid'])
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): <|fim_middle|> def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot]
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): <|fim_middle|> def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid))
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): <|fim_middle|> def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid))
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): <|fim_middle|> def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
""" Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid'])
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): <|fim_middle|> def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
""" Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code))
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): <|fim_middle|> def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
""" Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid'])
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): <|fim_middle|> <|fim▁end|>
""" Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid'])
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def <|fim_middle|>(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
setUp
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def <|fim_middle|>(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
test_count_backid
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def <|fim_middle|>(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
test_count_nextid
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def <|fim_middle|>(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
test_see_friends_character
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def <|fim_middle|>(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
test_cannot_see_non_friends_character
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def <|fim_middle|>(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_can_see_own_rating_character(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
test_can_see_own_blocktag_character
<|file_name|>test_character.py<|end_file_name|><|fim▁begin|>import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() self.friend1 = db_utils.create_user() db_utils.create_friendship(self.user1, self.friend1) self.count = 20 self.pivot = 5 s = db_utils.create_characters(self.count, self.user1, ratings.GENERAL.code) self.pivotid = s[self.pivot] def test_count_backid(self): self.assertEqual( self.count - self.pivot - 1, character.select_count(self.user1, ratings.GENERAL.code, backid=self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self): """ Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( c, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def test_cannot_see_non_friends_character(self): """ Should not be able to see a non-friend's friends-ony character in a listing. """ db_utils.create_character(self.user2, friends_only=True) self.assertEqual( self.count, character.select_count(self.user1, ratings.GENERAL.code)) def test_can_see_own_blocktag_character(self): """ Can see your own character in a listing even with a blocked tag. """ block_tagid = db_utils.create_tag("blocked") db_utils.create_blocktag(self.user1, block_tagid, ratings.GENERAL.code) charid = db_utils.create_character(self.user1, name="My blocktag character") db_utils.create_character_tag(block_tagid, charid) # A journal that we should NOT see. other_charid = db_utils.create_character(self.user2, name="Other user's blocktag character") db_utils.create_character_tag(block_tagid, other_charid) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) def <|fim_middle|>(self): """ Can see your own character in a listing even when it's above your max rating. """ charid = db_utils.create_character(self.user1, rating=ratings.EXPLICIT.code) db_utils.create_character(self.user2, rating=ratings.EXPLICIT.code) self.assertEqual( charid, character.select_list(self.user1, ratings.GENERAL.code, 100)[0]['charid']) <|fim▁end|>
test_can_see_own_rating_character
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None):<|fim▁hole|> return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert()<|fim▁end|>
"""Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to'])
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): <|fim_middle|> # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to]
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): <|fim_middle|> def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" }
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): <|fim_middle|> def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference()
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): <|fim_middle|> def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
self.delete_communication_links() self.update_in_reference()
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): <|fim_middle|> def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text)
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments <|fim_middle|> def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name })
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): <|fim_middle|> @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): <|fim_middle|> # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
"""Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to]
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): <|fim_middle|> def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
frappe.db.add_index("ToDo", ["reference_type", "reference_name"])
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): <|fim_middle|> def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user))
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): <|fim_middle|> @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): <|fim_middle|> <|fim▁end|>
frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert()
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): <|fim_middle|> else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" }
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: <|fim_middle|> else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description)
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: <|fim_middle|> self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description)
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method <|fim_middle|> def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" }
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: <|fim_middle|> def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" }
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: <|fim_middle|> else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user))
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: <|fim_middle|> self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user))
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: <|fim_middle|> self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
self.add_assign_comment(**self._assignment)
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): <|fim_middle|> frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): <|fim_middle|> try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table <|fim_middle|> elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): <|fim_middle|> else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference()
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: <|fim_middle|> @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
raise
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: <|fim_middle|> todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
user = frappe.session.user
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: <|fim_middle|> if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
todo_roles.remove('All')
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): <|fim_middle|> else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return None
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: <|fim_middle|> def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user))
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: <|fim_middle|> if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
todo_roles.remove('All')
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): <|fim_middle|> else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return True
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: <|fim_middle|> @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
return doc.allocated_to==user or doc.assigned_by==user
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def <|fim_middle|>(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
validate
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def <|fim_middle|>(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
on_update