prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def <|fim_middle|>(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def summary(self) -> str: return "" <|fim▁end|>
start
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def <|fim_middle|>(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def summary(self) -> str: return "" <|fim▁end|>
stop
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def <|fim_middle|>(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def summary(self) -> str: return "" <|fim▁end|>
summary
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def <|fim_middle|>(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def summary(self) -> str: return "" <|fim▁end|>
local_rank
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def <|fim_middle|>(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def summary(self) -> str: return "" <|fim▁end|>
start
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def <|fim_middle|>(self, action_name: str) -> None: pass def summary(self) -> str: return "" <|fim▁end|>
stop
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Copyright The PyTorch Lightning team. # # 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. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def <|fim_middle|>(self) -> str: return "" <|fim▁end|>
summary
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self):<|fim▁hole|> long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'})<|fim▁end|>
template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): <|fim_middle|> class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): <|fim_middle|> def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): <|fim_middle|> def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count))
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): <|fim_middle|> def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): <|fim_middle|> class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): <|fim_middle|> class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str))
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): <|fim_middle|> def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex))
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): <|fim_middle|> def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex))
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): <|fim_middle|> def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found')
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): <|fim_middle|> def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): <|fim_middle|> def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): <|fim_middle|> def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): <|fim_middle|> def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): <|fim_middle|> class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str))
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): <|fim_middle|> class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): <|fim_middle|> class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): <|fim_middle|> <|fim▁end|>
def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'})
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): <|fim_middle|> def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): <|fim_middle|> def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): <|fim_middle|> def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t)
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): <|fim_middle|> def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
self.compare_stacks('Neutron.template', 'Neutron.yaml', {})
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): <|fim_middle|> <|fim▁end|>
self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'})
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: <|fim_middle|> self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
break
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: <|fim_middle|> self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
del(jsn[u'AWSTemplateFormatVersion'])
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): <|fim_middle|> f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
continue
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def <|fim_middle|>(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
setUp
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def <|fim_middle|>(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_convert_all_templates
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def <|fim_middle|>(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
compare_json_vs_yaml
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def <|fim_middle|>(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
convert_all_json_to_yaml
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def <|fim_middle|>(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
_parse_template
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def <|fim_middle|>(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_long_yaml
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def <|fim_middle|>(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_no_version_format
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def <|fim_middle|>(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_string_template
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def <|fim_middle|>(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_invalid_yaml_and_json_template
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def <|fim_middle|>(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_json_document
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def <|fim_middle|>(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_empty_json_template
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def <|fim_middle|>(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_yaml_template
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def <|fim_middle|>(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_parse_to_value_exception
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def <|fim_middle|>(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
setUp
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def <|fim_middle|>(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
load_template
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def <|fim_middle|>(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
compare_stacks
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def <|fim_middle|>(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_neutron_resolved
<|file_name|>test_template_format.py<|end_file_name|><|fim▁begin|># # 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. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '["foo" , "bar"]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def <|fim_middle|>(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) <|fim▁end|>
test_wordpress_resolved
<|file_name|>product.py<|end_file_name|><|fim▁begin|><|fim▁hole|># # Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved # $Kiko Sánchez <[email protected]>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import fields, models, api from datetime import datetime class OutletLoss(models.Model): _name = 'outlet.loss' @api.multi @api.depends('qty', 'price_outlet', 'price_unit') def _get_outlet_loss(self): for loss in self: loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit) product_id = fields.Many2one('product.product', 'Product') price_unit = fields.Float('Price') price_outlet = fields.Float('Outlet Price') total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss, store=True, readonly=True) date_move = fields.Date('Move to outlet on', default=fields.datetime.now()) outlet_ok = fields.Boolean('Outlet') order_line_id = fields.Many2one('sale.order.line', 'Order Line') qty = fields.Float('Quantity') percent = fields.Float('Outlet Percent')<|fim▁end|>
##############################################################################
<|file_name|>product.py<|end_file_name|><|fim▁begin|>############################################################################## # # Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved # $Kiko Sánchez <[email protected]>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import fields, models, api from datetime import datetime class OutletLoss(models.Model): _n<|fim_middle|> <|fim▁end|>
ame = 'outlet.loss' @api.multi @api.depends('qty', 'price_outlet', 'price_unit') def _get_outlet_loss(self): for loss in self: loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit) product_id = fields.Many2one('product.product', 'Product') price_unit = fields.Float('Price') price_outlet = fields.Float('Outlet Price') total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss, store=True, readonly=True) date_move = fields.Date('Move to outlet on', default=fields.datetime.now()) outlet_ok = fields.Boolean('Outlet') order_line_id = fields.Many2one('sale.order.line', 'Order Line') qty = fields.Float('Quantity') percent = fields.Float('Outlet Percent')
<|file_name|>product.py<|end_file_name|><|fim▁begin|>############################################################################## # # Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved # $Kiko Sánchez <[email protected]>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import fields, models, api from datetime import datetime class OutletLoss(models.Model): _name = 'outlet.loss' @api.multi @api.depends('qty', 'price_outlet', 'price_unit') def _get_outlet_loss(self): fo<|fim_middle|> product_id = fields.Many2one('product.product', 'Product') price_unit = fields.Float('Price') price_outlet = fields.Float('Outlet Price') total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss, store=True, readonly=True) date_move = fields.Date('Move to outlet on', default=fields.datetime.now()) outlet_ok = fields.Boolean('Outlet') order_line_id = fields.Many2one('sale.order.line', 'Order Line') qty = fields.Float('Quantity') percent = fields.Float('Outlet Percent') <|fim▁end|>
r loss in self: loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit)
<|file_name|>product.py<|end_file_name|><|fim▁begin|>############################################################################## # # Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved # $Kiko Sánchez <[email protected]>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import fields, models, api from datetime import datetime class OutletLoss(models.Model): _name = 'outlet.loss' @api.multi @api.depends('qty', 'price_outlet', 'price_unit') def _g<|fim_middle|>elf): for loss in self: loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit) product_id = fields.Many2one('product.product', 'Product') price_unit = fields.Float('Price') price_outlet = fields.Float('Outlet Price') total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss, store=True, readonly=True) date_move = fields.Date('Move to outlet on', default=fields.datetime.now()) outlet_ok = fields.Boolean('Outlet') order_line_id = fields.Many2one('sale.order.line', 'Order Line') qty = fields.Float('Quantity') percent = fields.Float('Outlet Percent') <|fim▁end|>
et_outlet_loss(s
<|file_name|>svg_example.py<|end_file_name|><|fim▁begin|># Example made by OssiLehtinen # from svgpathtools import svg2paths, wsvg import numpy as np import uArmRobot<|fim▁hole|>import time #Configure Serial Port #serialport = "com3" # for windows serialport = "/dev/ttyACM0" # for linux like system # Connect to uArm myRobot = uArmRobot.robot(serialport,0) # user 0 for firmware < v4 and use 1 for firmware v4 myRobot.debug = True # Enable / Disable debug output on screen, by default disabled myRobot.connect() myRobot.mode(1) # Set mode to Normal # Read in the svg paths, attributes = svg2paths('drawing.svg') scale = .25 steps_per_seg = 3 coords = [] x_offset = 200 height = 90 draw_speed = 1000 # Convert the paths to a list of coordinates for i in range(len(paths)): path = paths[i] attribute = attributes[i] # A crude check for whether a path should be drawn. Does it have a style defined? if 'style' in attribute: for seg in path: segcoords = [] for p in range(steps_per_seg+1): cp = seg.point(float(p)/float(steps_per_seg)) segcoords.append([-np.real(cp)*scale+x_offset, np.imag(cp)*scale]) coords.append(segcoords) # The starting point myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000) for seg in coords: myRobot.goto(seg[0][0], seg[0][1], height, 6000) time.sleep(0.15) for p in seg: myRobot.goto_laser(p[0], p[1], height, draw_speed) # Back to the starting point (and turn the laser off) myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000)<|fim▁end|>
<|file_name|>svg_example.py<|end_file_name|><|fim▁begin|># Example made by OssiLehtinen # from svgpathtools import svg2paths, wsvg import numpy as np import uArmRobot import time #Configure Serial Port #serialport = "com3" # for windows serialport = "/dev/ttyACM0" # for linux like system # Connect to uArm myRobot = uArmRobot.robot(serialport,0) # user 0 for firmware < v4 and use 1 for firmware v4 myRobot.debug = True # Enable / Disable debug output on screen, by default disabled myRobot.connect() myRobot.mode(1) # Set mode to Normal # Read in the svg paths, attributes = svg2paths('drawing.svg') scale = .25 steps_per_seg = 3 coords = [] x_offset = 200 height = 90 draw_speed = 1000 # Convert the paths to a list of coordinates for i in range(len(paths)): path = paths[i] attribute = attributes[i] # A crude check for whether a path should be drawn. Does it have a style defined? if 'style' in attribute: <|fim_middle|> # The starting point myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000) for seg in coords: myRobot.goto(seg[0][0], seg[0][1], height, 6000) time.sleep(0.15) for p in seg: myRobot.goto_laser(p[0], p[1], height, draw_speed) # Back to the starting point (and turn the laser off) myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000) <|fim▁end|>
for seg in path: segcoords = [] for p in range(steps_per_seg+1): cp = seg.point(float(p)/float(steps_per_seg)) segcoords.append([-np.real(cp)*scale+x_offset, np.imag(cp)*scale]) coords.append(segcoords)
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>import collections puzzle_input = (0,13,1,8,6,15) test_inputs = [ ([(0,3,6), 10], 0), ([(1,3,2)], 1), ([(2,1,3)], 10), ([(1,2,3)], 27), ([(2,3,1)], 78), ([(3,2,1)], 438), ([(3,1,2)], 1836), # Expensive Tests # ([(0,3,6), 30000000], 175594), # ([(1,3,2), 30000000], 2578), # ([(2,1,3), 30000000], 3544142), # ([(1,2,3), 30000000], 261214), # ([(2,3,1), 30000000], 6895259), # ([(3,2,1), 30000000], 18), # ([(3,1,2), 30000000], 362), ] def iterate(input_, iterations=2020) -> int:<|fim▁hole|> prev_number = None for value in input_: turn_last_spoken[prev_number] = turn prev_number = value turn += 1 while turn < iterations: current_number = turn_last_spoken[prev_number] turn_last_spoken[prev_number] = turn if current_number != 0: current_number = turn - current_number prev_number = current_number turn += 1 return prev_number for _input, expected_output in test_inputs: print("Testing:", *_input, "...") actual_output = iterate(*_input) assert actual_output == expected_output, f"Expected: {expected_output}. Actual {actual_output}" print("Part 1:", iterate(puzzle_input)) print("Part 2:", iterate(puzzle_input, 30000000))<|fim▁end|>
turn = 0 turn_last_spoken = collections.defaultdict(int)
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>import collections puzzle_input = (0,13,1,8,6,15) test_inputs = [ ([(0,3,6), 10], 0), ([(1,3,2)], 1), ([(2,1,3)], 10), ([(1,2,3)], 27), ([(2,3,1)], 78), ([(3,2,1)], 438), ([(3,1,2)], 1836), # Expensive Tests # ([(0,3,6), 30000000], 175594), # ([(1,3,2), 30000000], 2578), # ([(2,1,3), 30000000], 3544142), # ([(1,2,3), 30000000], 261214), # ([(2,3,1), 30000000], 6895259), # ([(3,2,1), 30000000], 18), # ([(3,1,2), 30000000], 362), ] def iterate(input_, iterations=2020) -> int: <|fim_middle|> for _input, expected_output in test_inputs: print("Testing:", *_input, "...") actual_output = iterate(*_input) assert actual_output == expected_output, f"Expected: {expected_output}. Actual {actual_output}" print("Part 1:", iterate(puzzle_input)) print("Part 2:", iterate(puzzle_input, 30000000)) <|fim▁end|>
turn = 0 turn_last_spoken = collections.defaultdict(int) prev_number = None for value in input_: turn_last_spoken[prev_number] = turn prev_number = value turn += 1 while turn < iterations: current_number = turn_last_spoken[prev_number] turn_last_spoken[prev_number] = turn if current_number != 0: current_number = turn - current_number prev_number = current_number turn += 1 return prev_number
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>import collections puzzle_input = (0,13,1,8,6,15) test_inputs = [ ([(0,3,6), 10], 0), ([(1,3,2)], 1), ([(2,1,3)], 10), ([(1,2,3)], 27), ([(2,3,1)], 78), ([(3,2,1)], 438), ([(3,1,2)], 1836), # Expensive Tests # ([(0,3,6), 30000000], 175594), # ([(1,3,2), 30000000], 2578), # ([(2,1,3), 30000000], 3544142), # ([(1,2,3), 30000000], 261214), # ([(2,3,1), 30000000], 6895259), # ([(3,2,1), 30000000], 18), # ([(3,1,2), 30000000], 362), ] def iterate(input_, iterations=2020) -> int: turn = 0 turn_last_spoken = collections.defaultdict(int) prev_number = None for value in input_: turn_last_spoken[prev_number] = turn prev_number = value turn += 1 while turn < iterations: current_number = turn_last_spoken[prev_number] turn_last_spoken[prev_number] = turn if current_number != 0: <|fim_middle|> prev_number = current_number turn += 1 return prev_number for _input, expected_output in test_inputs: print("Testing:", *_input, "...") actual_output = iterate(*_input) assert actual_output == expected_output, f"Expected: {expected_output}. Actual {actual_output}" print("Part 1:", iterate(puzzle_input)) print("Part 2:", iterate(puzzle_input, 30000000)) <|fim▁end|>
current_number = turn - current_number
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>import collections puzzle_input = (0,13,1,8,6,15) test_inputs = [ ([(0,3,6), 10], 0), ([(1,3,2)], 1), ([(2,1,3)], 10), ([(1,2,3)], 27), ([(2,3,1)], 78), ([(3,2,1)], 438), ([(3,1,2)], 1836), # Expensive Tests # ([(0,3,6), 30000000], 175594), # ([(1,3,2), 30000000], 2578), # ([(2,1,3), 30000000], 3544142), # ([(1,2,3), 30000000], 261214), # ([(2,3,1), 30000000], 6895259), # ([(3,2,1), 30000000], 18), # ([(3,1,2), 30000000], 362), ] def <|fim_middle|>(input_, iterations=2020) -> int: turn = 0 turn_last_spoken = collections.defaultdict(int) prev_number = None for value in input_: turn_last_spoken[prev_number] = turn prev_number = value turn += 1 while turn < iterations: current_number = turn_last_spoken[prev_number] turn_last_spoken[prev_number] = turn if current_number != 0: current_number = turn - current_number prev_number = current_number turn += 1 return prev_number for _input, expected_output in test_inputs: print("Testing:", *_input, "...") actual_output = iterate(*_input) assert actual_output == expected_output, f"Expected: {expected_output}. Actual {actual_output}" print("Part 1:", iterate(puzzle_input)) print("Part 2:", iterate(puzzle_input, 30000000)) <|fim▁end|>
iterate
<|file_name|>bytenet_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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 #<|fim▁hole|># 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. """ByteNet tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.data_generators import problem_hparams from tensor2tensor.models import bytenet import tensorflow as tf class ByteNetTest(tf.test.TestCase): def testByteNet(self): vocab_size = 9 x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1)) y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1)) hparams = bytenet.bytenet_base() p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size) with self.test_session() as session: features = { "inputs": tf.constant(x, dtype=tf.int32), "targets": tf.constant(y, dtype=tf.int32), } model = bytenet.ByteNet( hparams, tf.estimator.ModeKeys.TRAIN, p_hparams) logits, _ = model(features) session.run(tf.global_variables_initializer()) res = session.run(logits) self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size)) if __name__ == "__main__": tf.test.main()<|fim▁end|>
<|file_name|>bytenet_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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. """ByteNet tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.data_generators import problem_hparams from tensor2tensor.models import bytenet import tensorflow as tf class ByteNetTest(tf.test.TestCase): <|fim_middle|> if __name__ == "__main__": tf.test.main() <|fim▁end|>
def testByteNet(self): vocab_size = 9 x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1)) y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1)) hparams = bytenet.bytenet_base() p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size) with self.test_session() as session: features = { "inputs": tf.constant(x, dtype=tf.int32), "targets": tf.constant(y, dtype=tf.int32), } model = bytenet.ByteNet( hparams, tf.estimator.ModeKeys.TRAIN, p_hparams) logits, _ = model(features) session.run(tf.global_variables_initializer()) res = session.run(logits) self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size))
<|file_name|>bytenet_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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. """ByteNet tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.data_generators import problem_hparams from tensor2tensor.models import bytenet import tensorflow as tf class ByteNetTest(tf.test.TestCase): def testByteNet(self): <|fim_middle|> if __name__ == "__main__": tf.test.main() <|fim▁end|>
vocab_size = 9 x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1)) y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1)) hparams = bytenet.bytenet_base() p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size) with self.test_session() as session: features = { "inputs": tf.constant(x, dtype=tf.int32), "targets": tf.constant(y, dtype=tf.int32), } model = bytenet.ByteNet( hparams, tf.estimator.ModeKeys.TRAIN, p_hparams) logits, _ = model(features) session.run(tf.global_variables_initializer()) res = session.run(logits) self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size))
<|file_name|>bytenet_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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. """ByteNet tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.data_generators import problem_hparams from tensor2tensor.models import bytenet import tensorflow as tf class ByteNetTest(tf.test.TestCase): def testByteNet(self): vocab_size = 9 x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1)) y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1)) hparams = bytenet.bytenet_base() p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size) with self.test_session() as session: features = { "inputs": tf.constant(x, dtype=tf.int32), "targets": tf.constant(y, dtype=tf.int32), } model = bytenet.ByteNet( hparams, tf.estimator.ModeKeys.TRAIN, p_hparams) logits, _ = model(features) session.run(tf.global_variables_initializer()) res = session.run(logits) self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size)) if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
tf.test.main()
<|file_name|>bytenet_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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. """ByteNet tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.data_generators import problem_hparams from tensor2tensor.models import bytenet import tensorflow as tf class ByteNetTest(tf.test.TestCase): def <|fim_middle|>(self): vocab_size = 9 x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1)) y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1)) hparams = bytenet.bytenet_base() p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size) with self.test_session() as session: features = { "inputs": tf.constant(x, dtype=tf.int32), "targets": tf.constant(y, dtype=tf.int32), } model = bytenet.ByteNet( hparams, tf.estimator.ModeKeys.TRAIN, p_hparams) logits, _ = model(features) session.run(tf.global_variables_initializer()) res = session.run(logits) self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size)) if __name__ == "__main__": tf.test.main() <|fim▁end|>
testByteNet
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index):<|fim▁hole|> elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index))
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): <|fim_middle|> def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__))
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): <|fim_middle|> def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
_checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index])
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): <|fim_middle|> def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
_checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index]
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): <|fim_middle|> def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
_checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): <|fim_middle|> def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
if index <= 1: return index return recursion(index - 1) + recursion(index - 2)
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): <|fim_middle|> calculate = fib_from_recursion_func<|fim▁end|>
_checkInput(index) return recursion(index)
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: <|fim_middle|> elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
raise ValueError("Indice negativo non supportato [{}]".format(index))
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: <|fim_middle|> def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__))
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: <|fim_middle|> return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
return index
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def <|fim_middle|>(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
_checkInput
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def <|fim_middle|>(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
fib_from_string
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def <|fim_middle|>(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
fib_from_list
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def <|fim_middle|>(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
fib_from_algo
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def <|fim_middle|>(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
recursion
<|file_name|>fibonacci.py<|end_file_name|><|fim▁begin|>def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def <|fim_middle|>(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func<|fim▁end|>
fib_from_recursion_func
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform():<|fim▁hole|> if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run()<|fim▁end|>
p = kivy_platform()
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): <|fim_middle|> class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): <|fim_middle|> if __name__ == '__main__': Service().run() <|fim▁end|>
def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): <|fim_middle|> def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read')
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): <|fim_middle|> def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
osc.sendMsg()
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): <|fim_middle|> def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
while self._run: osc.readQueue(self.oscid) sleep(.1)
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): <|fim_middle|> def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token)
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): <|fim_middle|> def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
self.token = { 'key': api_key, 'token': token, 'username': username }
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): <|fim_middle|> def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): <|fim_middle|> if __name__ == '__main__': Service().run() <|fim▁end|>
pass
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): <|fim_middle|> else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
return 'desktop'
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: <|fim_middle|> class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
return p
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: <|fim_middle|> else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
self.token = kwargs['token']
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: <|fim_middle|> def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
pocketclient.authorize(platform(), self.save_pocket_token)
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: <|fim_middle|> pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
if self.pocket_last_update: pocketclient.get_items(self. else: pass
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. <|fim_middle|> else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: <|fim_middle|> pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': Service().run() <|fim▁end|>
pass
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from kivy.lib import osc from time import sleep import pocketclient from kivy.utils import platform as kivy_platform SERVICE_PORT = 4000 def platform(): p = kivy_platform() if p.lower() in ('linux', 'waindows', 'osx'): return 'desktop' else: return p class Service(object): def __init__(self): osc.init() self.last_update = 0 self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT) osc.bind(self.oscid, self.pocket_connect, '/pocket/connect') osc.bind(self.oscid, self.pocket_list, '/pocket/list') osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read') def send(self, **kwargs): osc.sendMsg() def run(self): while self._run: osc.readQueue(self.oscid) sleep(.1) def pocket_connect(self, **kwargs): if 'token' in kwargs: self.token = kwargs['token'] else: pocketclient.authorize(platform(), self.save_pocket_token) def save_pocket_token(self, api_key, token, username): self.token = { 'key': api_key, 'token': token, 'username': username } def pocket_list(self, *args): if not self.token: if self.pocket_last_update: pocketclient.get_items(self. else: pass pass def pocket_mark_read(self, *args): pass if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
Service().run()