File: test_cache.py

package info (click to toggle)
pywavefront 1.3.3-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,112 kB
  • sloc: python: 1,586; makefile: 3
file content (202 lines) | stat: -rw-r--r-- 6,415 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import json
import os
from unittest import mock
import unittest
from pathlib import Path

from datetime import datetime
from io import BytesIO

from pywavefront import ObjParser, Wavefront
from pywavefront.parser import Parser
from pywavefront.exceptions import PywavefrontException
from pywavefront.cache import cache_name, meta_name

from utils import fixture


@mock.patch('pywavefront.parser.Parser.auto_post_parse', new=False)
class CacheTest(unittest.TestCase):
    """Create and load cache for a specific obj file"""
    maxDiff = None
    obj_file = fixture('simple.obj')
    create_materials = False

    def load_obj(self, filename, fake_io=None):
        """Helper method loading files with proper mocks"""
        if not fake_io:
            self.fake_io = FakeIO()

        if not fake_io:
            scene = Wavefront(filename, cache=True, create_materials=self.create_materials)

        with mock.patch("pywavefront.cache.gzip.open", new=self.fake_io):
            with mock.patch("pywavefront.cache.open", new=self.fake_io):
                with mock.patch("pywavefront.cache.os.path.exists", new=self.fake_io.exisis):
                    if fake_io:
                        scene = Wavefront(filename, cache=True, create_materials=self.create_materials)
                    scene.parser.post_parse()

        self.meta_file = self.obj_file.with_suffix(self.obj_file.suffix + '.json')
        self.cache_file = self.obj_file.with_suffix(self.obj_file.suffix + '.bin')
        return scene

    @property
    def meta(self):
        return self.fake_io[self.meta_file].json()

    @property
    def cache(self):
        return self.fake_io[self.cache_file]

    def test_create(self):
        scene = self.load_obj(self.obj_file)

        # Sanity check cache data
        self.assertTrue(self.meta.get('version'), msg="Missing version info in meta file: {}".format(self.meta))
        self.assertEqual(self.meta['mtllibs'], scene.mtllibs)
        self.assertEqual(self.cache.size, sum(len(m.vertices) for m in scene.materials.values()) * 4)

    def test_load(self):
        # Load the file creating a cache
        scene_pre = self.load_obj(self.obj_file)
        # Load again using cache
        scene_post = self.load_obj(self.obj_file, self.fake_io)

        self.assertFalse(scene_pre.parser.cache_loaded, msg="File was loaded from cache")
        self.assertTrue(scene_post.parser.cache_loaded, msg="File was not loaded from cache")

        # Compare pre and post cache
        self.assertEqual(sorted(scene_pre.materials.keys()), sorted(scene_post.materials.keys()))
        for name, pre_mat in scene_pre.materials.items():
            post_mat = scene_post.materials[name]
            self.assertNotEqual(pre_mat, post_mat)  # Ensure they are differnt objects!
            self.assertEqual(len(pre_mat.vertices), len(post_mat.vertices))
            for a, b in zip(pre_mat.vertices, post_mat.vertices):
                self.assertAlmostEqual(a, b, msg="{} != {}".format(pre_mat.vertices, post_mat.vertices))
            self.assertEqual(pre_mat.vertex_format, post_mat.vertex_format)
            self.assertEqual(pre_mat.name, post_mat.name)

    def test_missing_meta(self):
        # Load the file creating a cache
        scene_pre = self.load_obj(self.obj_file)

        # Be naughty deleting the meta file
        del self.fake_io[self.meta_file]

        # Load again using cache
        scene_post = self.load_obj(self.obj_file, self.fake_io)
        # No cache loader should be created
        self.assertFalse(scene_pre.parser.cache_loaded)
        self.assertFalse(scene_post.parser.cache_loaded)


@mock.patch('pywavefront.parser.Parser.auto_post_parse', new=False)
class CacheTestNoMaterials(CacheTest):
    obj_file = fixture('simple_no_mtl.obj')


@mock.patch('pywavefront.parser.Parser.auto_post_parse', new=False)
class CacheTestSimpleColors(CacheTest):
    obj_file = fixture('simple_colors.obj')


@mock.patch('pywavefront.parser.Parser.auto_post_parse', new=False)
class CacheTestNegativeIndices(CacheTest):
    obj_file = fixture('simple_negative_indices.obj')


@mock.patch('pywavefront.parser.Parser.auto_post_parse', new=False)
class CacheTestNoObjNoMtl(CacheTest):
    obj_file = fixture('simple_no_object_no_mtl.obj')


@mock.patch('pywavefront.parser.Parser.auto_post_parse', new=False)
class CacheTestUnknownMtl(CacheTest):
    obj_file = fixture('simple_unknown_usemtl.obj')
    create_materials = True


class FakeFileExists:

    def __init__(self, fake_io):
        self.fake_io = fake_io

    def __call__(self, value):
        return self.fake_io.exists(value)


class FakeIO:
    """A collection of files written during a mock session"""

    def __init__(self):
        self.files = {}
        self.exisis = FakeFileExists(self)

    def __call__(self, name, mode, *args, **kwargs):
        """Simulates open()"""
        fake_file = self.files.get(name)

        if not fake_file:
            if 'w' in mode:
                fake_file = FakeFile(name, mode)
                self.files[str(name)] = fake_file
            else:
                raise IOError("File not found: {}\n{}".format(name, self.files))

        return fake_file

    def exists(self, value):
        return self.files.get(value) is not None

    def __getitem__(self, name):
        return self.files[str(name)]

    def __delitem__(self, name):
        del self.files[str(name)]

class FakeFile:
    """Fake file object"""

    def __init__(self, name, mode):
        self.mode = mode
        self.name = name
        self.data = BytesIO()
        self.size = 0

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def read(self, length=-1):
        if length == -1:
            if 'b' in self.mode:
                return self.data.read()

            return self.data.read().decode('utf-8')

        if 'b' in self.mode:
            return self.data.read(length)
        
        return self.data.read(length).decode('utf-8')

    def write(self, data):
        if 'b' not in self.mode:
            data = data.encode()

        self.data.write(data)

    def close(self):
        self.size = self.data.tell()
        self.data.seek(0)

    def contents(self):
        cont = self.data.read()
        self.data.seek(0)
        return cont

    def json(self):
        d = self.contents().decode()
        return json.loads(d)