├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.md ├── placebo ├── __init__.py ├── pill.py ├── serializer.py └── utils.py ├── requirements.txt ├── setup.py └── tests ├── __init__.py └── unit ├── __init__.py ├── cfg └── aws_credentials ├── responses └── saved │ ├── ec2.DescribeAddresses_1.json │ ├── ec2.DescribeAddresses_2.json │ ├── ec2.DescribeKeyPairs_1.json │ └── foo.ec2.DescribeAddresses_1.json ├── test_canned.py ├── test_pill.py ├── test_save.py ├── test_serializers.py └── test_utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | # Emacs backup files 60 | *~ 61 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | matrix: 3 | include: 4 | - python: 3.6 5 | dist: trusty 6 | sudo: false 7 | - python: 3.7 8 | dist: xenial 9 | sudo: true 10 | - python: 3.8 11 | dist: xenial 12 | sudo: true 13 | - python: 3.9 14 | dist: xenial 15 | sudo: true 16 | 17 | cache: pip 18 | before_install: 19 | - pip install codecov 20 | install: 21 | - pip install -r requirements.txt 22 | - pip install coverage 23 | script: nosetests tests/unit --cover-erase --with-coverage --cover-package placebo 24 | after_success: 25 | - codecov 26 | 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | include requirements.txt 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | placebo 2 | ======= 3 | 4 | [![codecov](https://codecov.io/gh/garnaat/placebo/branch/develop/graph/badge.svg?token=ukrsVmWxwv)](https://codecov.io/gh/garnaat/placebo) 5 | 6 | Placebo allows you to mock boto3 calls that look just like normal calls but 7 | actually have no effect at all. It does this by allowing you to record a set 8 | of calls and save them to a data file and then replay those calls later 9 | (e.g. in a unit test) without ever hitting the AWS endpoints. 10 | 11 | Installation 12 | ------------ 13 | 14 | ~~~ 15 | $ pip install placebo 16 | ~~~ 17 | 18 | Quickstart 19 | ---------- 20 | 21 | Placebo uses the event mechanism in botocore to do most of its work. To start 22 | with, you need a boto3 Session object. 23 | 24 | ~~~ python 25 | import boto3 26 | import placebo 27 | 28 | session = boto3.Session() 29 | ~~~ 30 | 31 | Once you have a Session object, you can tell placebo about the Session like 32 | this: 33 | 34 | ~~~ python 35 | pill = placebo.attach(session, data_path='/path/to/response/directory') 36 | ~~~ 37 | 38 | The ``data_path`` is a path to a directory where you want responses to be stored 39 | or that contains previously recorded responses you want to playback. 40 | 41 | The ``attach`` function returns an instance of a ``Pill`` object. This object 42 | will be used to control all recording and playback of requests for all clients 43 | created by this session object. 44 | 45 | The first thing you will probably want to do is record some requests. To do 46 | this, simply: 47 | 48 | ~~~ python 49 | pill.record() 50 | ~~~ 51 | 52 | By default, the ``record`` method will cause all responses from all services to 53 | be recorded to the ``data_path``. If you are only interested in responses from 54 | one certain services, you can limit the recording by passing in a list of 55 | service names. 56 | 57 | ~~~ python 58 | pill.record(services='ec2,iam') 59 | ~~~ 60 | 61 | This would limit to recording to responses from the ``ec2`` service and the 62 | ``iam`` service. If you want to restrict recording to only certain operations 63 | in a single service, you can do this: 64 | 65 | ~~~ python 66 | pill.record(services='ec2', operations='DescribeInstances,DescribeKeyPairs') 67 | ~~~ 68 | 69 | From this point on, any clients that match the recording specification and are 70 | created from the session will be placebo-aware. To record responses, just 71 | create the client and use it as you normally would. 72 | 73 | ~~~ python 74 | aws_lambda = session.client('lambda') 75 | aws_lambda.list_functions() 76 | # ... more lambda calls ... 77 | ~~~ 78 | 79 | Each response will be saved as an individual JSON data file in the ``data_path`` 80 | path you specified when you attached the session. Multiple responses from the 81 | same service and operation are stored as separate files and will be replayed in 82 | the same order on playback. 83 | 84 | Later, to replay saved requests: 85 | 86 | ~~~ python 87 | import boto3 88 | import placebo 89 | 90 | session = boto3.Session() 91 | pill = placebo.attach(session, data_path='/path/to/response/directory') 92 | pill.playback() 93 | aws_lambda = session.client('lambda') 94 | aws_lambda.list_functions() 95 | # ... mocked response will be returned 96 | ~~~ 97 | 98 | #### Attaching to the default session 99 | 100 | Sometimes, Placebo needs to be attached to the Boto3 [default session](http://boto3.readthedocs.io/en/latest/guide/session.html#default-session) 101 | object. 102 | 103 | To attach Placebo to the default session, it is necessary to explicitly set up 104 | the default session by making a call to `boto3.setup_default_session()`. The 105 | default session is then accessible at `boto3.DEFAULT_SESSION`. 106 | 107 | For example: 108 | 109 | ~~~ python 110 | import boto3 111 | import placebo 112 | 113 | # Explicity set up the default session and attach Placebo to it. 114 | boto3.setup_default_session() 115 | session = boto3.DEFAULT_SESSION 116 | pill = placebo.attach(session, data_path='/path/to/response/directory') 117 | pill.record() 118 | 119 | # Now make Boto3 calls using the default session. 120 | client = boto3.client('ec2') 121 | client.describe_images(DryRun=False) 122 | ~~~ 123 | 124 | This is particularly useful if you are writing tests for legacy code that 125 | makes use of the Boto3 default session. 126 | 127 | #### Using pickle 128 | 129 | The responses can also be saved using pickle instead of JSON documents. 130 | This can be useful to avoid serialization problems with complex types in 131 | the responses. 132 | 133 | To enable the pickle format: 134 | ``` 135 | pill = pill = placebo.attach(session, record_format="pickle") 136 | ``` 137 | 138 | #### Manual Mocking 139 | 140 | You can also add mocked responses manually: 141 | 142 | ~~~ python 143 | list_functions_response = [ 144 | { 145 | "Version": "$LATEST", 146 | "CodeSha256": "I8Scq2g6ZKcPIvhKzvZqCiV4pDysxq4gZ+jLcMmDy5Y=", 147 | "FunctionName": "foobar", 148 | "MemorySize": 128, 149 | "CodeSize": 876521, 150 | "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:foobar", 151 | "Handler": "foobar.handler", 152 | "Role": "arn:aws:iam::123456789012:role/foobar-role", 153 | "Timeout": 30, 154 | "LastModified": "2015-11-06T22:30:32.164+0000", 155 | "Runtime": "python2.7", 156 | "Description": "Foos all of the bars" 157 | }] 158 | 159 | pill.save_response(service='lambda', operation='ListFunctions', 160 | response_data=list_functions_response, http_response=200) 161 | ~~~ 162 | 163 | You can add additional responses to a particular operation and the responses 164 | will be returned in order. The final parameter is the HTTP response code which 165 | is optional. The default value is 200. 166 | 167 | #### Usage as a decorator 168 | 169 | Placebo also provides a decorator for easier usage. 170 | 171 | First, you'll want to decorate your test method with `placebo_session` and include the `session` kwarg in your method, ex: 172 | ~~~ python 173 | @placebo_session 174 | def test_your_function(self, session): 175 | foo = Foo() 176 | arn = foo.create_iam_roles(session) 177 | self.assertEqual(arn, "arn:aws:iam::123:role/{}".format(foo.role_name)) 178 | ~~~ 179 | 180 | Now, you'll be able to record the AWS interactions with an environment variable: 181 | ~~~ bash 182 | $ PLACEBO_MODE=record nosetests tests.tests:TestFoo.test_create_iam_roles 183 | ~~~ 184 | 185 | You can optionally pass an AWS profile to use: 186 | ~~~ bash 187 | $ PLACEBO_PROFILE=foo PLACEBO_MODE=record nosetests tests.tests:TestFoo.test_create_iam_roles 188 | ~~~ 189 | 190 | You can optionally set the record format to use: 191 | ```bash 192 | $ PLACEBO_FORMAT=pickle PLACEBO_MODE=record nosetests tests.tests:TestFoo.test_create_iam_roles 193 | ``` 194 | 195 | In this example, it has created the following JSON blobs: 196 | ~~~ 197 | tests/placebo/TestFoo.test_create_iam_roles 198 | tests/placebo/TestFoo.test_create_iam_roles/iam.CreateRole_1.json 199 | tests/placebo/TestFoo.test_create_iam_roles/iam.GetRole_1.json 200 | tests/placebo/TestFoo.test_create_iam_roles/iam.GetRolePolicy_1.json 201 | tests/placebo/TestFoo.test_create_iam_roles/iam.PutRolePolicy_1.json 202 | ~~~ 203 | 204 | After the JSON has been created, simply drop the environment variables and re-run your test: 205 | ~~~ bash 206 | $ nosetests tests.tests:TestFoo.test_create_iam_roles 207 | ~~~ 208 | -------------------------------------------------------------------------------- /placebo/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from placebo.pill import Pill 16 | from placebo.serializer import Format 17 | 18 | 19 | def attach(session, data_path, prefix=None, debug=False, record_format=Format.JSON): 20 | pill = Pill(prefix=prefix, debug=debug, record_format=record_format) 21 | pill.attach(session, data_path) 22 | return pill 23 | -------------------------------------------------------------------------------- /placebo/pill.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | import glob 17 | import re 18 | import uuid 19 | import logging 20 | 21 | from placebo.serializer import Format, get_deserializer, get_serializer 22 | 23 | LOG = logging.getLogger(__name__) 24 | DebugFmtString = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 25 | 26 | 27 | class FakeHttpResponse(object): 28 | 29 | def __init__(self, status_code): 30 | self.status_code = status_code 31 | 32 | 33 | class Pill(object): 34 | 35 | clients = [] 36 | 37 | def __init__(self, prefix=None, debug=False, record_format=Format.JSON): 38 | if debug: 39 | self._set_logger(__name__, logging.DEBUG) 40 | 41 | record_format = record_format.lower() 42 | if record_format not in Format.ALLOWED: 43 | LOG.warning("Record format not allowed. Falling back to default.") 44 | record_format = Format.DEFAULT 45 | 46 | self._serializer = get_serializer(record_format) 47 | self._filename_re = re.compile(r'.*\..*_(?P\d+).{0}'.format( 48 | record_format)) 49 | self._record_format = record_format 50 | self.prefix = prefix 51 | self._uuid = str(uuid.uuid4()) 52 | self._data_path = None 53 | self._mode = None 54 | self._session = None 55 | self._index = {} 56 | self.events = [] 57 | self.clients = [] 58 | 59 | @property 60 | def mode(self): 61 | return self._mode 62 | 63 | @property 64 | def data_path(self): 65 | return self._data_path 66 | 67 | @property 68 | def session(self): 69 | return self._session 70 | 71 | @property 72 | def record_format(self): 73 | return self._record_format 74 | 75 | @staticmethod 76 | def _set_logger(logger_name, level=logging.INFO): 77 | """ 78 | Convenience function to quickly configure full debug output 79 | to go to the console. 80 | """ 81 | log = logging.getLogger(logger_name) 82 | log.setLevel(level) 83 | 84 | ch = logging.StreamHandler(None) 85 | ch.setLevel(level) 86 | 87 | formatter = logging.Formatter(DebugFmtString) 88 | 89 | # add formatter to ch 90 | ch.setFormatter(formatter) 91 | 92 | # add ch to logger 93 | log.addHandler(ch) 94 | 95 | def _create_shim_class(self): 96 | # This is kind of tricky. Maybe too tricky. 97 | # We want to know about all of the clients that are created within 98 | # the session we are attached to. To do that, we dynamically 99 | # create a Class object that will become a superclass of each 100 | # new client that gets created. This superclass has an __init__ 101 | # method that appends the new client instance into this Pill 102 | # instance's list of clients. The ugly code messing around with 103 | # mro() is there because we have to define an __init__ method in 104 | # our dynamically created class so we have to make sure it 105 | # calls it's superclass's __init__ methods. We can't use 106 | # super() because that needs the class (which we are in the process 107 | # of creating) so we walk the method resolution order to find 108 | # our superclass. The funny business with foo is because the 109 | # self inside _init_method stomps on the self defined in the 110 | # scope of this method but we really just need a reference to 111 | # the the method for adding a client. 112 | foo = self.add_client 113 | 114 | def _init_method(self, *args, **kwargs): 115 | res_order = self.__class__.mro() 116 | for i, cls in enumerate(res_order): 117 | if cls.__name__ == 'PillShim': 118 | break 119 | super_cls_index = i + 1 120 | if len(res_order) >= super_cls_index + 1: 121 | super_cls = res_order[super_cls_index] 122 | super_cls.__init__(self, *args, **kwargs) 123 | foo(self) 124 | 125 | class_attributes = {'__init__': _init_method} 126 | bases = [] 127 | class_name = 'PillShim' 128 | cls = type(class_name, tuple(bases), class_attributes) 129 | return cls 130 | 131 | def _create_client(self, class_attributes, base_classes, **kwargs): 132 | LOG.debug('_create_client') 133 | base_classes.insert(0, self._create_shim_class()) 134 | 135 | def add_client(self, client): 136 | self.clients.append(client) 137 | 138 | def attach(self, session, data_path): 139 | LOG.debug('attaching to session: %s', session) 140 | LOG.debug('datapath: %s', data_path) 141 | self._session = session 142 | self._data_path = data_path 143 | session.events.register('creating-client-class', self._create_client) 144 | 145 | def record(self, services='*', operations='*'): 146 | if self._mode == 'playback': 147 | self.stop() 148 | self._mode = 'record' 149 | for service in services.split(','): 150 | for operation in operations.split(','): 151 | event = 'after-call.{0}.{1}'.format( 152 | service.strip(), operation.strip()) 153 | LOG.debug('recording: %s', event) 154 | self.events.append(event) 155 | self._session.events.register( 156 | event, self._record_data, 'placebo-record-mode') 157 | for client in self.clients: 158 | client.meta.events.register( 159 | event, self._record_data, 'placebo-record-mode') 160 | 161 | def playback(self): 162 | if self.mode == 'record': 163 | self.stop() 164 | if self.mode is None: 165 | event = 'before-call.*.*' 166 | self.events.append(event) 167 | self._session.events.register( 168 | event, self._mock_request, 'placebo-playback-mode') 169 | self._mode = 'playback' 170 | for client in self.clients: 171 | client.meta.events.register( 172 | event, self._mock_request, 'placebo-playback-mode') 173 | 174 | def stop(self): 175 | LOG.debug('stopping, mode=%s', self.mode) 176 | if self.mode == 'record': 177 | if self._session: 178 | for event in self.events: 179 | self._session.events.unregister( 180 | event, unique_id='placebo-record-mode') 181 | for client in self.clients: 182 | client.meta.events.unregister( 183 | event, unique_id='placebo-record-mode') 184 | self.events = [] 185 | elif self.mode == 'playback': 186 | if self._session: 187 | for event in self.events: 188 | self._session.events.unregister( 189 | event, unique_id='placebo-playback-mode') 190 | for client in self.clients: 191 | client.meta.events.unregister( 192 | event, unique_id='placebo-playback-mode') 193 | self.events = [] 194 | self._mode = None 195 | 196 | def _record_data(self, http_response, parsed, model, **kwargs): 197 | LOG.debug('_record_data') 198 | service_name = model.service_model.endpoint_prefix 199 | operation_name = model.name 200 | self.save_response(service_name, operation_name, parsed, 201 | http_response.status_code) 202 | 203 | def get_new_file_path(self, service, operation): 204 | base_name = '{0}.{1}'.format(service, operation) 205 | if self.prefix: 206 | base_name = '{0}.{1}'.format(self.prefix, base_name) 207 | LOG.debug('get_new_file_path: %s', base_name) 208 | index = 0 209 | glob_pattern = os.path.join(self._data_path, base_name + '_*') 210 | for file_path in glob.glob(glob_pattern): 211 | file_name = os.path.basename(file_path) 212 | m = self._filename_re.match(file_name) 213 | if m: 214 | i = int(m.group('index')) 215 | if i > index: 216 | index = i 217 | index += 1 218 | return os.path.join( 219 | self._data_path, '{0}_{1}.{2}'.format( 220 | base_name, index, self.record_format)) 221 | 222 | @staticmethod 223 | def find_file_format(file_name): 224 | """ 225 | Returns a tuple with the file path and format found, or (None, None) 226 | """ 227 | for file_format in Format.ALLOWED: 228 | file_path = '.'.join((file_name, file_format)) 229 | if os.path.exists(file_path): 230 | return file_path, file_format 231 | return None, None 232 | 233 | def get_next_file_path(self, service, operation): 234 | """ 235 | Returns a tuple with the next file to read and the serializer 236 | format used 237 | """ 238 | base_name = '{0}.{1}'.format(service, operation) 239 | if self.prefix: 240 | base_name = '{0}.{1}'.format(self.prefix, base_name) 241 | LOG.debug('get_next_file_path: %s', base_name) 242 | next_file = None 243 | serializer_format = None 244 | index = self._index.setdefault(base_name, 1) 245 | 246 | while not next_file: 247 | file_name = os.path.join( 248 | self._data_path, base_name + '_{0}'.format(index)) 249 | next_file, serializer_format = self.find_file_format(file_name) 250 | if next_file: 251 | self._index[base_name] += 1 252 | elif index != 1: 253 | index = 1 254 | self._index[base_name] = 1 255 | else: 256 | raise IOError('response file ({0}.[{1}]) not found'.format( 257 | file_name, "|".join(Format.ALLOWED))) 258 | 259 | return next_file, serializer_format 260 | 261 | def save_response(self, service, operation, response_data, 262 | http_response=200): 263 | """ 264 | Store a response to the data directory. The ``operation`` 265 | should be the name of the operation in the service API (e.g. 266 | DescribeInstances), the ``response_data`` should a value you want 267 | to return from a placebo call and the ``http_response`` should be 268 | the HTTP status code returned from the service. You can add 269 | multiple responses for a given operation and they will be 270 | returned in order. 271 | """ 272 | LOG.debug('save_response: %s.%s', service, operation) 273 | filepath = self.get_new_file_path(service, operation) 274 | LOG.debug('save_response: path=%s', filepath) 275 | data = {'status_code': http_response, 276 | 'data': response_data} 277 | with open(filepath, Format.write_mode(self.record_format)) as fp: 278 | self._serializer(data, fp) 279 | 280 | def load_response(self, service, operation): 281 | LOG.debug('load_response: %s.%s', service, operation) 282 | (response_file, file_format) = self.get_next_file_path( 283 | service, operation) 284 | LOG.debug('load_responses: %s', response_file) 285 | with open(response_file, Format.read_mode(file_format)) as fp: 286 | response_data = get_deserializer(file_format)(fp) 287 | return (FakeHttpResponse(response_data['status_code']), 288 | response_data['data']) 289 | 290 | def _mock_request(self, **kwargs): 291 | """ 292 | A mocked out make_request call that bypasses all network calls 293 | and simply returns any mocked responses defined. 294 | """ 295 | model = kwargs.get('model') 296 | service = model.service_model.endpoint_prefix 297 | operation = model.name 298 | LOG.debug('_make_request: %s.%s', service, operation) 299 | return self.load_response(service, operation) 300 | -------------------------------------------------------------------------------- /placebo/serializer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import json 16 | import pickle 17 | import datetime 18 | import base64 19 | from io import BytesIO 20 | 21 | from botocore.response import StreamingBody 22 | 23 | 24 | class UTC(datetime.tzinfo): 25 | """UTC""" 26 | 27 | def utcoffset(self, dt): 28 | return datetime.timedelta(0) 29 | 30 | def tzname(self, dt): 31 | return "UTC" 32 | 33 | def dst(self, dt): 34 | return datetime.timedelta(0) 35 | 36 | utc = UTC() 37 | 38 | 39 | class Format: 40 | """ 41 | Serialization formats 42 | """ 43 | JSON = "json" 44 | PICKLE = "pickle" 45 | 46 | DEFAULT = JSON 47 | ALLOWED = [JSON, PICKLE] 48 | 49 | @classmethod 50 | def read_mode(cls, format): 51 | """ 52 | Return the correct read mode for this type of format. 53 | """ 54 | if format == cls.PICKLE: 55 | return 'rb' 56 | else: 57 | return 'r' 58 | 59 | @classmethod 60 | def write_mode(cls, format): 61 | """ 62 | Return the correct write mode for this type of format. 63 | """ 64 | if format == cls.PICKLE: 65 | return 'wb' 66 | else: 67 | return 'w' 68 | 69 | 70 | def deserialize(obj): 71 | """Convert JSON dicts back into objects.""" 72 | # Be careful of shallow copy here 73 | target = dict(obj) 74 | class_name = None 75 | if '__class__' in target: 76 | class_name = target.pop('__class__') 77 | if '__module__' in obj: 78 | obj.pop('__module__') 79 | # Use getattr(module, class_name) for custom types if needed 80 | if class_name == 'datetime': 81 | return datetime.datetime(tzinfo=utc, **target) 82 | if class_name == 'StreamingBody': 83 | b64_body = obj['body'] 84 | decoded_body = base64.b64decode(b64_body) 85 | return BytesIO(decoded_body) 86 | # Return unrecognized structures as-is 87 | return obj 88 | 89 | 90 | def serialize(obj): 91 | """Convert objects into JSON structures.""" 92 | # Record class and module information for deserialization 93 | result = {'__class__': obj.__class__.__name__} 94 | try: 95 | result['__module__'] = obj.__module__ 96 | except AttributeError: 97 | pass 98 | # Convert objects to dictionary representation based on type 99 | print('+++++ %s' % obj) 100 | print('+++++ %s' % type(obj)) 101 | if isinstance(obj, datetime.datetime): 102 | result['year'] = obj.year 103 | result['month'] = obj.month 104 | result['day'] = obj.day 105 | result['hour'] = obj.hour 106 | result['minute'] = obj.minute 107 | result['second'] = obj.second 108 | result['microsecond'] = obj.microsecond 109 | return result 110 | if isinstance(obj, StreamingBody): 111 | result['body'] = obj.read() 112 | obj._raw_stream = BytesIO(result['body']) 113 | obj._amount_read = 0 114 | return result 115 | if isinstance(obj, bytes): 116 | encoded = base64.b64encode(obj) 117 | return encoded.decode('utf-8') 118 | # Raise a TypeError if the object isn't recognized 119 | raise TypeError("Type not serializable") 120 | 121 | 122 | def _serialize_json(obj, fp): 123 | """ Serialize ``obj`` as a JSON formatted stream to ``fp`` """ 124 | json.dump(obj, fp, indent=4, default=serialize) 125 | 126 | 127 | def _deserialize_json(fp): 128 | """ Deserialize ``fp`` JSON content to a Python object.""" 129 | return json.load(fp, object_hook=deserialize) 130 | 131 | 132 | def _serialize_pickle(obj, fp): 133 | """ Serialize ``obj`` as a PICKLE formatted stream to ``fp`` """ 134 | pickle.dump(obj, fp) 135 | 136 | 137 | def _deserialize_pickle(fp): 138 | """ Deserialize ``fp`` PICKLE content to a Python object.""" 139 | return pickle.load(fp) 140 | 141 | 142 | def get_serializer(serializer_format): 143 | """ Get the serializer for a specific format """ 144 | if serializer_format == Format.JSON: 145 | return _serialize_json 146 | if serializer_format == Format.PICKLE: 147 | return _serialize_pickle 148 | 149 | 150 | def get_deserializer(serializer_format): 151 | """ Get the deserializer for a specific format """ 152 | if serializer_format == Format.JSON: 153 | return _deserialize_json 154 | if serializer_format == Format.PICKLE: 155 | return _deserialize_pickle 156 | -------------------------------------------------------------------------------- /placebo/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import placebo 16 | import boto3 17 | import os 18 | import functools 19 | 20 | from placebo.serializer import Format 21 | 22 | 23 | def placebo_session(function): 24 | """ 25 | Decorator to help do testing with placebo. 26 | Simply wrap the function you want to test and make sure to add 27 | a "session" argument so the decorator can pass the placebo session. 28 | Accepts the following environment variables to configure placebo: 29 | PLACEBO_MODE: set to "record" to record AWS calls and save them 30 | PLACEBO_PROFILE: optionally set an AWS credential profile to record with 31 | PLACEBO_DIR: set the directory to record to / read from 32 | """ 33 | 34 | @functools.wraps(function) 35 | def wrapper(*args, **kwargs): 36 | session_kwargs = { 37 | 'region_name': os.environ.get('AWS_DEFAULT_REGION', 'us-east-1') 38 | } 39 | profile_name = os.environ.get('PLACEBO_PROFILE', None) 40 | if profile_name: 41 | session_kwargs['profile_name'] = profile_name 42 | 43 | session = boto3.Session(**session_kwargs) 44 | 45 | self = args[0] 46 | prefix = self.__class__.__name__ + '.' + function.__name__ 47 | base_dir = os.environ.get( 48 | "PLACEBO_DIR", os.path.join(os.getcwd(), "placebo")) 49 | record_dir = os.path.join(base_dir, prefix) 50 | 51 | record_format = os.environ.get('PLACEBO_FORMAT', Format.DEFAULT) 52 | 53 | if not os.path.exists(record_dir): 54 | os.makedirs(record_dir) 55 | 56 | pill = placebo.attach(session, data_path=record_dir, 57 | record_format=record_format) 58 | 59 | if os.environ.get('PLACEBO_MODE') == 'record': 60 | pill.record() 61 | else: 62 | pill.playback() 63 | 64 | kwargs['session'] = session 65 | 66 | return function(*args, **kwargs) 67 | 68 | return wrapper 69 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3>=1.8.6 2 | nose>=1.3.7 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | 5 | 6 | setup( 7 | name='placebo', 8 | version='0.10.0', 9 | description='Make boto3 calls that look real but have no effect', 10 | long_description=open('README.md').read(), 11 | author='Mitch Garnaat', 12 | author_email='mitch@garnaat.com', 13 | url='https://github.com/garnaat/placebo', 14 | packages=find_packages(exclude=['tests*']), 15 | package_dir={'placebo': 'placebo'}, 16 | license="Apache License 2.0", 17 | classifiers=[ 18 | 'Development Status :: 3 - Alpha', 19 | 'Intended Audience :: Developers', 20 | 'Intended Audience :: System Administrators', 21 | 'Natural Language :: English', 22 | 'License :: OSI Approved :: Apache Software License', 23 | 'Programming Language :: Python :: 3', 24 | 'Programming Language :: Python :: 3.6', 25 | 'Programming Language :: Python :: 3.7', 26 | 'Programming Language :: Python :: 3.8', 27 | 'Programming Language :: Python :: 3.9' 28 | ], 29 | ) 30 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /tests/unit/cfg/aws_credentials: -------------------------------------------------------------------------------- 1 | [foobar] 2 | aws_access_key_id = foo 3 | aws_secret_access_key = bar 4 | -------------------------------------------------------------------------------- /tests/unit/responses/saved/ec2.DescribeAddresses_1.json: -------------------------------------------------------------------------------- 1 | { 2 | "status_code": 200, 3 | "data": { 4 | "Addresses": [ 5 | { 6 | "PublicIp": "52.53.54.55", 7 | "Domain": "vpc", 8 | "AllocationId": "eipalloc-12345678" 9 | } 10 | ], 11 | "ResponseMetadata": { 12 | "HTTPStatusCode": 200, 13 | "RequestId": "b0fe7bb2-6552-4ea8-8a36-9685044048ab" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tests/unit/responses/saved/ec2.DescribeAddresses_2.json: -------------------------------------------------------------------------------- 1 | { 2 | "status_code": 200, 3 | "data": { 4 | "Addresses": [ 5 | { 6 | "PublicIp": "53.54.55.56", 7 | "Domain": "vpc", 8 | "AllocationId": "eipalloc-23456789" 9 | } 10 | ], 11 | "ResponseMetadata": { 12 | "HTTPStatusCode": 200, 13 | "RequestId": "f0117994-a451-40c6-94d8-c226ae2b6195" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tests/unit/responses/saved/ec2.DescribeKeyPairs_1.json: -------------------------------------------------------------------------------- 1 | { 2 | "status_code": 200, 3 | "data": { 4 | "KeyPairs": [ 5 | { 6 | "KeyName": "FooBar", 7 | "KeyFingerprint": "85:83:08:25:fa:96:45:ea:c9:15:04:12:af:45:3f:c0:ef:e8:b8:ce" 8 | }, 9 | { 10 | "KeyName": "FieBaz", 11 | "KeyFingerprint": "9b:02:68:c2:ff:32:38:1a:49:ec:c4:b5:b3:98:36:cf:cd:1f:73:cc" 12 | } 13 | ], 14 | "ResponseMetadata": { 15 | "HTTPStatusCode": 200, 16 | "RequestId": "c0f77cb6-f4f4-42be-9408-bd540c168b90" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/unit/responses/saved/foo.ec2.DescribeAddresses_1.json: -------------------------------------------------------------------------------- 1 | { 2 | "status_code": 200, 3 | "data": { 4 | "Addresses": [ 5 | { 6 | "PublicIp": "42.43.44.45", 7 | "Domain": "vpc", 8 | "AllocationId": "eipalloc-87654321" 9 | } 10 | ], 11 | "ResponseMetadata": { 12 | "HTTPStatusCode": 200, 13 | "RequestId": "b0fe7bb2-6552-4ea8-8a36-9685044048ab" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tests/unit/test_canned.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import unittest 16 | import os 17 | 18 | import boto3 19 | 20 | try: 21 | import mock 22 | except ImportError: 23 | import unittest.mock as mock 24 | 25 | import placebo 26 | 27 | 28 | class TestPlacebo(unittest.TestCase): 29 | 30 | def setUp(self): 31 | self.environ = {} 32 | self.environ_patch = mock.patch('os.environ', self.environ) 33 | self.environ_patch.start() 34 | credential_path = os.path.join(os.path.dirname(__file__), 'cfg', 35 | 'aws_credentials') 36 | self.environ['AWS_SHARED_CREDENTIALS_FILE'] = credential_path 37 | self.data_path = os.path.join(os.path.dirname(__file__), 'responses') 38 | self.data_path = os.path.join(self.data_path, 'saved') 39 | self.session = boto3.Session(profile_name='foobar', 40 | region_name='us-west-2') 41 | self.pill = placebo.attach(self.session, self.data_path) 42 | 43 | def tearDown(self): 44 | pass 45 | 46 | def test_describe_addresses(self): 47 | self.pill.playback() 48 | ec2_client = self.session.client('ec2') 49 | result = ec2_client.describe_addresses() 50 | self.assertEqual(result['Addresses'][0]['PublicIp'], '52.53.54.55') 51 | result = ec2_client.describe_addresses() 52 | self.assertEqual(result['Addresses'][0]['PublicIp'], '53.54.55.56') 53 | result = ec2_client.describe_addresses() 54 | self.assertEqual(result['Addresses'][0]['PublicIp'], '52.53.54.55') 55 | result = ec2_client.describe_addresses() 56 | self.assertEqual(result['Addresses'][0]['PublicIp'], '53.54.55.56') 57 | 58 | def test_describe_key_pairs(self): 59 | self.pill.playback() 60 | ec2_client = self.session.client('ec2') 61 | result = ec2_client.describe_key_pairs() 62 | self.assertEqual(len(result['KeyPairs']), 2) 63 | self.assertEqual(result['KeyPairs'][0]['KeyName'], 'FooBar') 64 | self.assertEqual(result['KeyPairs'][1]['KeyName'], 'FieBaz') 65 | 66 | def test_prefix_new_file_path(self): 67 | self.pill.prefix = 'foo' 68 | service = 'ec2' 69 | operation = 'DescribeAddresses' 70 | filename = '{0}.{1}.{2}_2.json'.format(self.pill.prefix, service, 71 | operation) 72 | target = os.path.join(self.data_path, filename) 73 | self.assertEqual(self.pill.get_new_file_path(service, operation), 74 | target) 75 | 76 | def test_prefix_next_file_path(self): 77 | self.pill.prefix = 'foo' 78 | service = 'ec2' 79 | operation = 'DescribeAddresses' 80 | filename = '{0}.{1}.{2}_1.json'.format(self.pill.prefix, service, 81 | operation) 82 | target = os.path.join(self.data_path, filename) 83 | (file_path, _) = self.pill.get_next_file_path(service, operation) 84 | self.assertEqual(file_path, target) 85 | -------------------------------------------------------------------------------- /tests/unit/test_pill.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import unittest 16 | import os 17 | 18 | import boto3 19 | 20 | try: 21 | import mock 22 | except ImportError: 23 | import unittest.mock as mock 24 | 25 | import placebo.pill 26 | 27 | 28 | class TestPill(unittest.TestCase): 29 | 30 | def setUp(self): 31 | self.environ = {} 32 | self.environ_patch = mock.patch('os.environ', self.environ) 33 | self.environ_patch.start() 34 | credential_path = os.path.join(os.path.dirname(__file__), 'cfg', 35 | 'aws_credentials') 36 | self.environ['AWS_SHARED_CREDENTIALS_FILE'] = credential_path 37 | self.data_path = os.path.join(os.path.dirname(__file__), 'responses') 38 | self.data_path = os.path.join(self.data_path, 'tests') 39 | self.session = boto3.Session(profile_name='foobar', 40 | region_name='us-west-2') 41 | self.pill = placebo.attach(self.session, self.data_path) 42 | 43 | def tearDown(self): 44 | pass 45 | 46 | def test_record(self): 47 | self.assertEqual(self.pill.mode, None) 48 | self.pill.record() 49 | self.assertEqual(self.pill.mode, 'record') 50 | self.assertEqual(self.pill.events, ['after-call.*.*']) 51 | self.pill.stop() 52 | self.assertEqual(self.pill.mode, None) 53 | self.assertEqual(self.pill.events, []) 54 | self.pill.record('ec2') 55 | self.pill.record('iam', 'ListUsers') 56 | self.assertEqual(self.pill.mode, 'record') 57 | self.assertEqual(self.pill.events, ['after-call.ec2.*', 58 | 'after-call.iam.ListUsers']) 59 | self.pill.stop() 60 | self.assertEqual(self.pill.mode, None) 61 | self.assertEqual(self.pill.events, []) 62 | 63 | def test_playback(self): 64 | self.pill.playback() 65 | self.assertEqual(self.pill.mode, 'playback') 66 | self.assertEqual(self.pill.events, ['before-call.*.*']) 67 | self.pill.stop() 68 | self.assertEqual(self.pill.events, []) 69 | 70 | def test_clients(self): 71 | ec2 = self.session.client('ec2') 72 | iam = self.session.client('iam') 73 | self.assertEqual(len(self.pill.clients), 2) 74 | self.assertTrue(ec2 in self.pill.clients) 75 | self.assertTrue(iam in self.pill.clients) 76 | session = boto3.Session(profile_name='foobar', 77 | region_name='us-west-2') 78 | new_ec2 = session.client('ec2') 79 | self.assertEqual(len(self.pill.clients), 2) 80 | self.assertFalse(new_ec2 in self.pill.clients) 81 | -------------------------------------------------------------------------------- /tests/unit/test_save.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import unittest 16 | import os 17 | import shutil 18 | 19 | import boto3 20 | 21 | try: 22 | import mock 23 | except ImportError: 24 | import unittest.mock as mock 25 | 26 | import placebo 27 | 28 | 29 | kp_result_one = { 30 | "KeyPairs": [ 31 | { 32 | "KeyName": "foo", 33 | "KeyFingerprint": "ad:08:8a:b3:13:ea:6c:20:fa" 34 | } 35 | ] 36 | } 37 | 38 | kp_result_two = { 39 | "KeyPairs": [ 40 | { 41 | "KeyName": "bar", 42 | "KeyFingerprint": ":27:21:b9:ce:b5:5a:a2:a3:bc" 43 | } 44 | ] 45 | } 46 | 47 | addresses_result_one = { 48 | "Addresses": [ 49 | { 50 | "InstanceId": "", 51 | "PublicIp": "192.168.0.1", 52 | "Domain": "standard" 53 | } 54 | ] 55 | } 56 | 57 | 58 | class TestPlacebo(unittest.TestCase): 59 | 60 | def setUp(self): 61 | self.environ = {} 62 | self.environ_patch = mock.patch('os.environ', self.environ) 63 | self.environ_patch.start() 64 | credential_path = os.path.join(os.path.dirname(__file__), 'cfg', 65 | 'aws_credentials') 66 | self.environ['AWS_SHARED_CREDENTIALS_FILE'] = credential_path 67 | self.data_path = os.path.join(os.path.dirname(__file__), 'responses') 68 | self.data_path = os.path.join(self.data_path, 'tests') 69 | if os.path.exists(self.data_path): 70 | shutil.rmtree(self.data_path) 71 | os.mkdir(self.data_path) 72 | self.session = boto3.Session(profile_name='foobar', 73 | region_name='us-west-2') 74 | self.pill = placebo.attach(self.session, self.data_path) 75 | 76 | def tearDown(self): 77 | if os.path.exists(self.data_path): 78 | shutil.rmtree(self.data_path) 79 | 80 | def test_ec2(self): 81 | self.assertEqual(len(os.listdir(self.data_path)), 0) 82 | self.pill.save_response( 83 | 'ec2', 'DescribeAddresses', addresses_result_one) 84 | self.assertEqual(len(os.listdir(self.data_path)), 1) 85 | self.pill.playback() 86 | ec2_client = self.session.client('ec2') 87 | result = ec2_client.describe_addresses() 88 | self.assertEqual(result['Addresses'][0]['PublicIp'], '192.168.0.1') 89 | result = ec2_client.describe_addresses() 90 | self.assertEqual(result['Addresses'][0]['PublicIp'], '192.168.0.1') 91 | 92 | def test_ec2_multiple_responses(self): 93 | self.assertEqual(len(os.listdir(self.data_path)), 0) 94 | self.pill.save_response( 95 | 'ec2', 'DescribeKeyPairs', kp_result_one) 96 | self.assertEqual(len(os.listdir(self.data_path)), 1) 97 | self.pill.save_response( 98 | 'ec2', 'DescribeKeyPairs', kp_result_two) 99 | self.assertEqual(len(os.listdir(self.data_path)), 2) 100 | self.pill.playback() 101 | ec2_client = self.session.client('ec2') 102 | result = ec2_client.describe_key_pairs() 103 | self.assertEqual(result['KeyPairs'][0]['KeyName'], 'foo') 104 | result = ec2_client.describe_key_pairs() 105 | self.assertEqual(result['KeyPairs'][0]['KeyName'], 'bar') 106 | result = ec2_client.describe_key_pairs() 107 | self.assertEqual(result['KeyPairs'][0]['KeyName'], 'foo') 108 | 109 | def test_multiple_clients(self): 110 | self.assertEqual(len(os.listdir(self.data_path)), 0) 111 | self.pill.save_response( 112 | 'ec2', 'DescribeAddresses', addresses_result_one) 113 | self.pill.playback() 114 | ec2_client = self.session.client('ec2') 115 | iam_client = self.session.client('iam') 116 | result = ec2_client.describe_addresses() 117 | self.assertEqual(len(os.listdir(self.data_path)), 1) 118 | -------------------------------------------------------------------------------- /tests/unit/test_serializers.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import datetime 16 | import unittest 17 | import json 18 | 19 | from io import StringIO, BytesIO 20 | 21 | from botocore.response import StreamingBody 22 | 23 | from placebo.serializer import serialize, deserialize, utc, Format 24 | from placebo.serializer import get_serializer, get_deserializer 25 | from placebo.serializer import _serialize_json, _deserialize_json 26 | from placebo.serializer import _serialize_pickle, _deserialize_pickle 27 | 28 | 29 | date_sample = { 30 | "LoginProfile": { 31 | "UserName": "baz", 32 | "CreateDate": datetime.datetime(2015, 1, 4, 9, 1, 2, 0, tzinfo=utc), 33 | } 34 | } 35 | 36 | date_json = """{"LoginProfile": {"CreateDate": {"__class__": "datetime", "day": 4, "hour": 9, "microsecond": 0, "minute": 1, "month": 1, "second": 2, "year": 2015}, "UserName": "baz"}}""" 37 | 38 | content = b'this is a test' 39 | stream = BytesIO(content) 40 | 41 | streaming_body_sample = { 42 | 'Body': StreamingBody(stream, len(content)) 43 | } 44 | 45 | streaming_body_json = """{"Body": {"__class__": "StreamingBody", "__module__": "botocore.response", "body": "dGhpcyBpcyBhIHRlc3Q="}}""" 46 | 47 | 48 | class TestSerializers(unittest.TestCase): 49 | 50 | def test_datetime_to_json(self): 51 | result = json.dumps(date_sample, default=serialize, sort_keys=True) 52 | self.assertEqual(result, date_json) 53 | 54 | def test_datetime_from_json(self): 55 | response = json.loads(date_json, object_hook=deserialize) 56 | self.assertEqual(response, date_sample) 57 | 58 | def test_streaming_body_to_json(self): 59 | result = json.dumps( 60 | streaming_body_sample, default=serialize, sort_keys=True) 61 | self.assertEqual(result, streaming_body_json) 62 | 63 | def test_streaming_body_from_json(self): 64 | response = json.loads(streaming_body_json, object_hook=deserialize) 65 | self.assertEqual(response['Body'].read(), content) 66 | 67 | def test_roundtrip_json(self): 68 | ser = get_serializer(Format.JSON) 69 | deser = get_deserializer(Format.JSON) 70 | fp = StringIO() 71 | ser(date_sample, fp) 72 | fp.seek(0) 73 | obj = deser(fp) 74 | self.assertEqual(obj, date_sample) 75 | 76 | def test_roundtrip_pickle(self): 77 | ser = get_serializer(Format.PICKLE) 78 | deser = get_deserializer(Format.PICKLE) 79 | fp = BytesIO() 80 | ser(date_sample, fp) 81 | fp.seek(0) 82 | obj = deser(fp) 83 | self.assertEqual(obj, date_sample) 84 | 85 | def test_get_serializer_json(self): 86 | ser = get_serializer(Format.JSON) 87 | self.assertEqual(ser, _serialize_json) 88 | 89 | def test_get_deserializer_json(self): 90 | ser = get_deserializer(Format.JSON) 91 | self.assertEqual(ser, _deserialize_json) 92 | 93 | def test_get_serializer_pickle(self): 94 | ser = get_serializer(Format.PICKLE) 95 | self.assertEqual(ser, _serialize_pickle) 96 | 97 | def test_get_deserialize_pickle(self): 98 | ser = get_deserializer(Format.PICKLE) 99 | self.assertEqual(ser, _deserialize_pickle) 100 | -------------------------------------------------------------------------------- /tests/unit/test_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2015-2019 Mitch Garnaat 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import unittest 16 | import os 17 | import shutil 18 | 19 | import boto3 20 | 21 | try: 22 | import mock 23 | except ImportError: 24 | import unittest.mock as mock 25 | 26 | from placebo.utils import placebo_session 27 | 28 | 29 | class TestUtils(unittest.TestCase): 30 | 31 | def setUp(self): 32 | self.environ = {} 33 | self.environ_patch = mock.patch('os.environ', self.environ) 34 | self.environ_patch.start() 35 | credential_path = os.path.join(os.path.dirname(__file__), 'cfg', 36 | 'aws_credentials') 37 | self.environ['AWS_SHARED_CREDENTIALS_FILE'] = credential_path 38 | self.environ['PLACEBO_MODE'] = 'record' 39 | self.environ['PLACEBO_DIR'] = 'placebo_test_runs' 40 | self.session = boto3.Session(profile_name='foobar', 41 | region_name='us-west-2') 42 | 43 | @placebo_session 44 | def test_decorator(self, session): 45 | 46 | # Tear it up.. 47 | PLACEBO_TEST_DIR = os.path.join(os.getcwd(), 'placebo_test_runs') 48 | prefix = 'TestUtils.test_decorator' 49 | record_dir = os.path.join(PLACEBO_TEST_DIR, prefix) 50 | self.assertTrue(os.path.exists(record_dir)) 51 | 52 | # Tear it down.. 53 | shutil.rmtree(PLACEBO_TEST_DIR) 54 | --------------------------------------------------------------------------------