File: invocation_tests.py

package info (click to toggle)
cmake-format 0.6.13-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,436 kB
  • sloc: python: 16,990; makefile: 14
file content (371 lines) | stat: -rw-r--r-- 14,066 bytes parent folder | download | duplicates (4)
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
from __future__ import unicode_literals
import contextlib
import difflib
import io
import os
import shutil
import subprocess
import sys
import unittest
import tempfile


class TestInvocations(unittest.TestCase):

  def __init__(self, *args, **kwargs):
    super(TestInvocations, self).__init__(*args, **kwargs)
    self.tempdir = None
    self.tempconfig = None

  def setUp(self):
    self.tempdir = tempfile.mkdtemp(prefix='cmakeformattest_')
    thisdir = os.path.realpath(os.path.dirname(__file__))
    parentdir = os.path.dirname(thisdir)

    self.env = {
        'PYTHONPATH': os.path.dirname(parentdir)
    }

    base_override = os.getenv("PYBUILD_TEST_BASE_OVERRIDE")
    if base_override is not None:
      self.thisdir = thisdir.replace(os.environ['PWD'], base_override)
    else:
      self.thisdir = thisdir
    configpath = os.path.join(self.thisdir, 'testdata', 'cmake-format.py')
    self.tempconfig = os.path.join(self.tempdir, '.cmake-format.py')
    shutil.copyfile(configpath, self.tempconfig)

  @contextlib.contextmanager
  def subTest(self, msg=None, **params):
    # pylint: disable=no-member
    if sys.version_info < (3, 4, 0):
      yield None
    else:
      yield super(TestInvocations, self).subTest(msg=msg, **params)

  def tearDown(self):
    shutil.rmtree(self.tempdir)

  def test_pipeout_invocation(self):
    """
    Test invocation with an infile path and output to stdout.
    """

    thisdir = self.thisdir
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    with io.open(os.path.join(self.tempdir, 'test_out.cmake'), 'wb') as outfile:
      subprocess.check_call([sys.executable, '-Bm', 'cmakelang.format',
                             infile_path], stdout=outfile, cwd=self.tempdir,
                            env=self.env)

    with io.open(os.path.join(self.tempdir, 'test_out.cmake'), 'r',
                 encoding='utf8') as infile:
      actual_text = infile.read()
    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_fileout_invocation(self):
    """
    Test invocation with an infile path and outfile path
    """

    thisdir = self.thisdir
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    subprocess.check_call([sys.executable, '-Bm', 'cmakelang.format',
                           '-o', os.path.join(self.tempdir, 'test_out.cmake'),
                           infile_path], cwd=self.tempdir, env=self.env)

    with io.open(os.path.join(self.tempdir, 'test_out.cmake'), 'r',
                 encoding='utf8') as infile:
      actual_text = infile.read()
    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_inplace_invocation(self):
    """
    Test invocation for inplace format of a file
    """

    thisdir = self.thisdir
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    ofd, tmpfile_path = tempfile.mkstemp(suffix='.txt', prefix='CMakeLists',
                                         dir=self.tempdir)
    os.close(ofd)
    shutil.copyfile(infile_path, tmpfile_path)
    os.chmod(tmpfile_path, 0o755)
    subprocess.check_call([sys.executable, '-Bm', 'cmakelang.format',
                           '-i', tmpfile_path], cwd=self.tempdir, env=self.env)

    with io.open(os.path.join(tmpfile_path), 'r', encoding='utf8') as infile:
      actual_text = infile.read()
    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

    # Verify permissions are preserved
    self.assertEqual(oct(os.stat(tmpfile_path).st_mode)[-3:], "755")

  def test_check_invocation(self):
    """
    Test invocation for --check of a file
    """

    thisdir = self.thisdir
    unformatted_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    formatted_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    with open("/dev/null", "wb") as devnull:
      statuscode = subprocess.call([
          sys.executable, '-Bm', 'cmakelang.format',
          '--check', unformatted_path], env=self.env, stderr=devnull)
    self.assertEqual(1, statuscode)

    statuscode = subprocess.call([
        sys.executable, '-Bm', 'cmakelang.format',
        '--check', formatted_path], env=self.env)
    self.assertEqual(0, statuscode)

  def test_stream_invocation(self):
    """
    Test invocation with stdin as the infile and stdout as the outifle
    """

    thisdir = self.thisdir
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    stdinpipe = os.pipe()
    stdoutpipe = os.pipe()

    def preexec():
      os.close(stdinpipe[1])
      os.close(stdoutpipe[0])

    # pylint: disable=W1509
    proc = subprocess.Popen([sys.executable, '-Bm', 'cmakelang.format', '-'],
                            stdin=stdinpipe[0], stdout=stdoutpipe[1],
                            cwd=self.tempdir, env=self.env, preexec_fn=preexec)
    os.close(stdinpipe[0])
    os.close(stdoutpipe[1])

    with io.open(infile_path, 'r', encoding='utf-8') as infile:
      with io.open(stdinpipe[1], 'w', encoding='utf-8') as outfile:
        for line in infile:
          outfile.write(line)

    with io.open(stdoutpipe[0], 'r', encoding='utf-8') as infile:
      actual_text = infile.read()

    proc.wait()

    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_encoding_invocation(self):
    """
    Try to reformat latin1-encoded file, once with default
    encoding (-> prompt utf8-decoding error) and once with
    specifically latin1 encoding (-> should succeed)
    """

    thisdir = self.thisdir
    infile_path = os.path.join(thisdir, 'testdata', 'test_latin1_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_latin1_out.cmake')

    # this invocation should fail
    invocation_result = subprocess.call(
        [sys.executable, '-Bm', 'cmakelang.format',
         '--outfile-path', os.path.join(self.tempdir, 'test_latin1_out.cmake'),
         infile_path],
        cwd=self.tempdir, env=self.env,
        stderr=subprocess.PIPE)
    self.assertNotEqual(
        0, invocation_result,
        msg="Expected cmake-format invocation to fail but did not")

    # this invocation should succeed
    subprocess.check_call(
        [sys.executable, '-Bm', 'cmakelang.format',
         '--input-encoding=latin1',
         '--output-encoding=latin1',
         '--outfile-path', os.path.join(self.tempdir, 'test_latin1_out.cmake'),
         infile_path],
        cwd=self.tempdir, env=self.env)

    with io.open(os.path.join(self.tempdir, 'test_latin1_out.cmake'), 'r',
                 encoding='latin1') as infile:
      actual_text = infile.read()

    with io.open(expectfile_path, 'r', encoding='latin1') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_no_config_invocation(self):
    """
    Test invocation with no config file specified
    """
    os.unlink(self.tempconfig)
    thisdir = self.thisdir
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    subprocess.check_call([sys.executable, '-Bm', 'cmakelang.format',
                           '-o', os.path.join(self.tempdir, 'test_out.cmake'),
                           infile_path], cwd=self.tempdir, env=self.env)

    with io.open(os.path.join(self.tempdir, 'test_out.cmake'), 'r',
                 encoding='utf8') as infile:
      actual_text = infile.read()
    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_multiple_config_invocation(self):
    """
    Repeat the default config test using a config file that is split. The
    custom command definitions are in the second file.
    """
    thisdir = self.thisdir
    configdir = os.path.join(thisdir, 'testdata')
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    subprocess.check_call([
        sys.executable, '-Bm', 'cmakelang.format', '-c',
        os.path.join(configdir, 'cmake-format-split-1.py'),
        os.path.join(configdir, 'cmake-format-split-2.py'),
        '-o', os.path.join(self.tempdir, 'test_out.cmake'),
        infile_path], cwd=self.tempdir, env=self.env)

    with io.open(os.path.join(self.tempdir, 'test_out.cmake'), 'r',
                 encoding='utf8') as infile:
      actual_text = infile.read()
    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_multiple_config_invocation_dupflag(self):
    """
    Repeat the default config test using a config file that is split. The
    custom command definitions are in the second file.
    """
    thisdir = self.thisdir
    configdir = os.path.join(thisdir, 'testdata')
    infile_path = os.path.join(thisdir, 'testdata', 'test_in.cmake')
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')

    subprocess.check_call([
        sys.executable, '-Bm', 'cmakelang.format',
        '-c', os.path.join(configdir, 'cmake-format-split-1.py'),
        '-c', os.path.join(configdir, 'cmake-format-split-2.py'),
        '-o', os.path.join(self.tempdir, 'test_out.cmake'),
        infile_path], cwd=self.tempdir, env=self.env)

    with io.open(os.path.join(self.tempdir, 'test_out.cmake'), 'r',
                 encoding='utf8') as infile:
      actual_text = infile.read()
    with io.open(expectfile_path, 'r', encoding='utf8') as infile:
      expected_text = infile.read()

    delta_lines = list(difflib.unified_diff(expected_text.split('\n'),
                                            actual_text.split('\n')))
    if delta_lines:
      raise AssertionError('\n'.join(delta_lines[2:]))

  def test_auto_lineendings(self):
    """
    Verify that windows line-endings are detected and preserved on input.
    """
    thisdir = self.thisdir
    for suffix in ["win", "unix"]:
      with self.subTest(lineending=suffix):
        filename = "test_lineend_{}.cmake".format(suffix)
        infile_path = os.path.join(thisdir, 'testdata', filename)
        outfile_path = os.path.join(self.tempdir, filename)
        subprocess.check_call([sys.executable, '-Bm', 'cmakelang.format',
                               '--line-ending=auto',
                               '-o', outfile_path, infile_path],
                              cwd=self.tempdir, env=self.env)
        with open(infile_path, "rb") as infile:
          infile_bytes = infile.read()
        with open(outfile_path, "rb") as infile:
          outfile_bytes = infile.read()
        self.assertEqual(infile_bytes, outfile_bytes)

  def test_notouch(self):
    """
    Verify that, if formatting is unchanged, an --in-place file is not modified
    """
    thisdir = self.thisdir
    expectfile_path = os.path.join(thisdir, 'testdata', 'test_out.cmake')
    outfile_path = os.path.join(self.tempdir, 'test_out.cmake')
    shutil.copy2(expectfile_path, outfile_path)
    mtime_before = os.path.getmtime(outfile_path)
    subprocess.check_call(
        [sys.executable, '-Bm', 'cmakelang.format', '-i', outfile_path],
        cwd=self.tempdir, env=self.env)
    mtime_after = os.path.getmtime(outfile_path)
    self.assertEqual(mtime_before, mtime_after)

  def test_require_valid(self):
    """
    Verify that the --require-valid-layout flag works as intended
    """
    thisdir = self.thisdir
    testfilepath = os.path.join(thisdir, 'testdata', 'test_invalid.cmake')

    with tempfile.NamedTemporaryFile(
        suffix=".txt", prefix="CMakeLists", dir=self.tempdir) as outfile:
      statuscode = subprocess.call(
          [sys.executable, '-Bm', 'cmakelang.format', testfilepath],
          stdout=outfile, stderr=outfile, env=self.env)
    self.assertEqual(0, statuscode)

    with tempfile.NamedTemporaryFile(
        suffix=".txt", prefix="CMakeLists", dir=self.tempdir) as outfile:
      statuscode = subprocess.call(
          [sys.executable, '-Bm', 'cmakelang.format', testfilepath,
           "--require-valid-layout"],
          stdout=outfile, stderr=outfile, env=self.env)
    self.assertEqual(1, statuscode)


if __name__ == '__main__':
  unittest.main()