Matteo Scandolo | 9ce1825 | 2017-06-22 10:48:25 -0700 | [diff] [blame^] | 1 | import sys, os |
| 2 | import unittest |
| 3 | from mock import patch, MagicMock |
| 4 | from tosca.parser import TOSCA_Parser |
| 5 | |
| 6 | class FakeObj: |
| 7 | new = None |
| 8 | filter = None |
| 9 | |
| 10 | class FakeResource: |
| 11 | objects = FakeObj |
| 12 | |
| 13 | class FakeModel: |
| 14 | save = None |
| 15 | |
| 16 | class TOSCA_Parser_Create_or_update_Test(unittest.TestCase): |
| 17 | |
| 18 | @patch.object(FakeResource.objects, "filter") |
| 19 | @patch.object(FakeResource.objects, "new", MagicMock(return_value=FakeModel)) |
| 20 | @patch.object(FakeModel, "save") |
| 21 | def test_new_model(self, mock_save, mock_filter): |
| 22 | """ |
| 23 | [TOSCA_Parser] create_or_update: should create a new model |
| 24 | """ |
| 25 | data = { |
| 26 | "name": "test" |
| 27 | } |
| 28 | |
| 29 | TOSCA_Parser.creat_or_update(FakeResource, data) |
| 30 | mock_filter.assert_called_with(name="test") |
| 31 | mock_save.assert_called_once() |
| 32 | |
| 33 | @patch.object(FakeResource.objects, "filter", MagicMock(return_value=[FakeModel])) |
| 34 | @patch.object(FakeModel, "save") |
| 35 | def test_existing_model(self, mock_save): |
| 36 | """ |
| 37 | [TOSCA_Parser] create_or_update: should update an existing model |
| 38 | """ |
| 39 | data = { |
| 40 | "name": "test" |
| 41 | } |
| 42 | |
| 43 | TOSCA_Parser.creat_or_update(FakeResource, data) |
| 44 | mock_save.assert_called_once() |
| 45 | |
| 46 | @patch.object(FakeResource.objects, "filter", MagicMock(return_value=['a', 'b'])) |
| 47 | def test_multiple_models(self): |
| 48 | """ |
| 49 | [TOSCA_Parser] create_or_update: should raise an exception if multiple instances are found |
| 50 | """ |
| 51 | data = { |
| 52 | "name": "test" |
| 53 | } |
| 54 | with self.assertRaises(Exception) as e: |
| 55 | TOSCA_Parser.creat_or_update(FakeResource, data) |
| 56 | self.assertEqual(e.exception.message, "[XOS-Tosca] Model test has multiple instances, I can't handle it") |
| 57 | |
| 58 | @patch.object(FakeResource.objects, "new", MagicMock(return_value=FakeModel)) |
| 59 | @patch.object(FakeResource.objects, "filter") |
| 60 | @patch.object(FakeModel, "save") |
| 61 | def test_find_model_without_name_property(self, mock_save, mock_filter): |
| 62 | """ |
| 63 | [TOSCA_Parser] create_or_update: should lookup a model by the first property |
| 64 | """ |
| 65 | data = { |
| 66 | 'foo': 'bar', |
| 67 | 'something': 'else' |
| 68 | } |
| 69 | TOSCA_Parser.creat_or_update(FakeResource, data) |
| 70 | mock_filter.assert_called_with(foo="bar") |
| 71 | mock_save.assert_called_once() |
| 72 | |
| 73 | if __name__ == '__main__': |
| 74 | unittest.main() |