Skip to content

Commit e661bb7

Browse files
authored
Merge pull request nschloe#273 from nschloe/new-tests
New tests
2 parents fd5b479 + 8e7cef2 commit e661bb7

File tree

98 files changed

+4906
-653
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+4906
-653
lines changed

.circleci/config.yml

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,13 @@ jobs:
1111
- run: apt update
1212
# <https://stackoverflow.com/a/44333806/353337>
1313
- run: DEBIAN_FRONTEND=noninteractive apt install tzdata
14-
- run: apt install -y texlive-latex-base texlive-latex-extra python3-pip python3-tk wget poppler-utils
14+
- run: apt install -y texlive-latex-base texlive-latex-extra python3-pip python3-tk
1515
- run: pip3 install -U pytest pytest-cov excode black flake8
1616
- checkout
1717
- run: cd ~/work
1818
- run: excode README.md test/zzz_readme_test.py --filter python,test
19-
# install latest pgfplots
20-
- run: mkdir -p $TEXMFLOCAL
21-
- run: wget http://mirrors.ctan.org/install/graphics/pgf/contrib/pgfplots.tds.zip -O /tmp/pgfplots.zip
22-
- run: unzip /tmp/pgfplots.zip -d $TEXMFLOCAL
23-
- run: texhash
24-
# install
25-
- run: pip3 install -r test_requirements.txt
2619
# Install very specific versions of the dependencies; the build is too
2720
# fragile otherwise.
28-
- run: pip3 install matplotlib==2.1.0
2921
- run: pip3 install .[all]
3022
- run: pip3 check
3123
# format and lint

README.md

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -172,37 +172,15 @@ please visit
172172
### Testing
173173
174174
matplotlib2tikz has automatic unit testing to make sure that the software
175-
doesn't accidentally get worse over time. In `test/testfunctions/`, a number of
176-
test cases are specified. Those
177-
178-
* run through matplotlib2tikz,
179-
* the resulting LaTeX file is compiled into a PDF (`pdflatex`),
180-
* the PDF is converted into a PNG (`pdftoppm`),
181-
* a perceptual hash is computed from the PNG and compared to a previously
182-
stored version.
175+
doesn't accidentally get worse over time. In `test/`, a number of
176+
test cases are specified. Those run through matplotlib2tikz and compare the output with
177+
a previously stored reference TeX file.
183178
184179
To run the tests, just check out this repository and type
185180
```
186181
pytest
187182
```
188183
189-
The final pHash may depend on any of the tools used during the process. For
190-
example, if your version of [Pillow](https://pypi.org/project/Pillow/)
191-
is too old, the pHash function might operate slightly differently and produce a
192-
slightly different pHash, resulting in a failing test. If tests are failing on
193-
your local machine, you should first make sure to have an up-to-date Pillow.
194-
195-
If you would like to contribute a test, just take a look at the examples in
196-
`test/testfunctions/`. Essentially a test consists of three things:
197-
198-
* a description,
199-
* a pHash, and
200-
* a function that creates the image in matplotlib.
201-
202-
Just add your file, add it to `test/testfunction/__init__.py`, and run the
203-
tests. A failing test will always print out the pHash, so you can leave it
204-
empty in the first run and fill it in later to make the test pass.
205-
206184
### Distribution
207185
208186
To create a new release

matplotlib2tikz/files.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77
def _gen_filename(data, nb_key, ext):
8-
name = data["base name"] + "-%03d%s" % (data[nb_key], ext)
8+
name = data["base name"] + "-{:03d}{}".format(data[nb_key], ext)
99
return os.path.join(data["output dir"], name), name
1010

1111

matplotlib2tikz/save.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import codecs
66
import os
7+
import tempfile
78
import warnings
89

910
import matplotlib as mpl
@@ -23,8 +24,8 @@
2324

2425

2526
def get_tikz_code(
26-
filepath,
2727
figure="gcf",
28+
filepath=None,
2829
figurewidth=None,
2930
figureheight=None,
3031
textsize=10.0,
@@ -38,15 +39,13 @@ def get_tikz_code(
3839
extra_tikzpicture_parameters=None,
3940
dpi=None,
4041
show_info=True,
42+
include_disclaimer=True,
4143
):
4244
"""Main function. Here, the recursion into the image starts and the
4345
contents are picked up. The actual file gets written in this routine.
4446
4547
:param figure: either a Figure object or 'gcf' (default).
4648
47-
:param filepath: The file to which the TikZ output will be written.
48-
:type filepath: str
49-
5049
:param figurewidth: If not ``None``, this will be used as figure width
5150
within the TikZ/PGFPlots output. If ``figureheight``
5251
is not given, ``matplotlib2tikz`` will try to preserve
@@ -141,8 +140,16 @@ def get_tikz_code(
141140
data["rel data path"] = tex_relative_path_to_data
142141
data["externalize tables"] = externalize_tables
143142
data["override externals"] = override_externals
144-
data["output dir"] = os.path.dirname(filepath)
145-
data["base name"] = os.path.splitext(os.path.basename(filepath))[0]
143+
144+
if filepath:
145+
data["output dir"] = os.path.dirname(filepath)
146+
else:
147+
directory = tempfile.mkdtemp()
148+
data["output dir"] = directory
149+
150+
data["base name"] = (
151+
os.path.splitext(os.path.basename(filepath))[0] if filepath else "tmp"
152+
)
146153
data["strict"] = strict
147154
data["tikz libs"] = set()
148155
data["pgfplots libs"] = set()
@@ -181,11 +188,12 @@ def get_tikz_code(
181188
if "is_in_groupplot_env" in data and data["is_in_groupplot_env"]:
182189
content.extend("\\end{groupplot}\n\n")
183190

184-
disclaimer = "This file was created by matplotlib2tikz v%s." % __version__
185-
186191
# write disclaimer to the file header
187192
code = """"""
188-
code += _tex_comment(disclaimer)
193+
194+
if include_disclaimer:
195+
disclaimer = "This file was created by matplotlib2tikz v%s." % __version__
196+
code += _tex_comment(disclaimer)
189197

190198
# write the contents
191199
if wrap and axis_environment:
@@ -207,15 +215,18 @@ def get_tikz_code(
207215
return code
208216

209217

210-
def save(*args, encoding=None, **kwargs):
218+
def save(filepath, *args, encoding=None, **kwargs):
211219
"""Same as `get_tikz_code()`, but actually saves the code to a file.
212220
221+
:param filepath: The file to which the TikZ output will be written.
222+
:type filepath: str
223+
213224
:param encoding: Sets the text encoding of the output file, e.g. 'utf-8'.
214225
For supported values: see ``codecs`` module.
215226
:returns: None
216227
"""
217228
code = get_tikz_code(*args, **kwargs)
218-
file_handle = codecs.open(args[0], "w", encoding)
229+
file_handle = codecs.open(filepath, "w", encoding)
219230
try:
220231
file_handle.write(code)
221232
except UnicodeEncodeError:

test/create_tex

Lines changed: 62 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -21,20 +21,20 @@ def _main():
2121

2222
if not os.path.isdir(test_dir):
2323
os.mkdir(test_dir)
24-
tex_file_path = os.path.join(test_dir, 'acid.tex')
24+
tex_file_path = os.path.join(test_dir, "acid.tex")
2525

2626
# directory where all the generated files will end up
27-
data_dir = os.path.join(test_dir, 'data')
27+
data_dir = os.path.join(test_dir, "data")
2828
if not os.path.isdir(data_dir):
2929
os.mkdir(data_dir)
3030

3131
# how to get from the LaTeX file to the data
32-
tex_relative_path_to_data = './data'
32+
tex_relative_path_to_data = "./data"
3333

34-
figure_width = '7.5cm'
34+
figure_width = "7.5cm"
3535

3636
# open file for writing
37-
file_handle = open(tex_file_path, 'w')
37+
file_handle = open(tex_file_path, "w")
3838

3939
write_document_header(file_handle, figure_width)
4040

@@ -44,41 +44,38 @@ def _main():
4444
test_list = testfunctions.__all__
4545

4646
for name in test_list:
47-
print('Test function %s...' % name)
47+
print("Test function %s..." % name)
4848

4949
# import the test
50-
test = import_module('testfunctions.' + name)
50+
test = import_module("testfunctions." + name)
5151

5252
pp.cla()
5353
pp.clf()
5454

5555
# plot the test example
5656
test.plot()
57-
tikz_path = os.path.join(data_dir, name + '.tex')
57+
tikz_path = os.path.join(data_dir, name + ".tex")
5858
tikz_tex_path = os.path.join(
59-
tex_relative_path_to_data,
60-
os.path.basename(tikz_path)
61-
)
59+
tex_relative_path_to_data, os.path.basename(tikz_path)
60+
)
6261
# convert to tikz
6362
matplotlib2tikz.save(
6463
tikz_path,
6564
figurewidth=figure_width,
6665
tex_relative_path_to_data=tex_relative_path_to_data,
67-
show_info=False
68-
)
69-
tikz = '\\input{%s}' % tikz_tex_path
66+
show_info=False,
67+
)
68+
tikz = "\\input{%s}" % tikz_tex_path
7069
# file_handle.write('\\input{%s}\n' % tikz_tex_path)
7170

7271
# plot reference figure
73-
pdf_path = os.path.join(data_dir, name + '.pdf')
72+
pdf_path = os.path.join(data_dir, name + ".pdf")
7473
pp.savefig(pdf_path)
75-
pdf_path = os.path.join(
76-
tex_relative_path_to_data,
77-
os.path.basename(pdf_path)
78-
)
74+
pdf_path = os.path.join(tex_relative_path_to_data, os.path.basename(pdf_path))
7975

8076
# Open figure, insert PDF
81-
file_handle.write('''%% test plot %s
77+
file_handle.write(
78+
"""%% test plot %s
8279
\\begin{figure}%%
8380
\\centering%%
8481
\\begin{tabular}{cc}
@@ -89,19 +86,20 @@ def _main():
8986
\\caption{%s.}%%
9087
\\end{figure}\\clearpage
9188
92-
''' % (name, pdf_path, tikz, test.desc)
93-
)
94-
print('done.')
89+
"""
90+
% (name, pdf_path, tikz, test.desc)
91+
)
92+
print("done.")
9593
write_document_closure(file_handle)
9694
file_handle.close()
9795
return
9896

9997

10098
def write_document_header(file_handle, figure_width):
101-
'''Write the LaTeX document header to the file.
102-
'''
99+
"""Write the LaTeX document header to the file.
100+
"""
103101
file_handle.write(
104-
'''\\documentclass[landscape]{scrartcl}
102+
"""\\documentclass[landscape]{scrartcl}
105103
\\usepackage[utf8]{inputenc}
106104
\\usepackage{fontspec}
107105
\\usepackage{graphicx}
@@ -111,66 +109,62 @@ def write_document_header(file_handle, figure_width):
111109
\\pgfplotsset{compat=newest}
112110
\\newlength\\figwidth%%
113111
\\setlength\\figwidth{%s}
114-
\\begin{document}''' % figure_width
112+
\\begin{document}"""
113+
% figure_width
115114
)
116115
return
117116

118117

119118
def write_document_closure(file_handle):
120-
'''Write the LaTeX document closure to the file.
121-
'''
122-
file_handle.write('\\end{document}')
119+
"""Write the LaTeX document closure to the file.
120+
"""
121+
file_handle.write("\\end{document}")
123122
return
124123

125124

126-
def write_file_comparison_entry(file_handle,
127-
pdf_path,
128-
tikz_path,
129-
test_id,
130-
comment
131-
):
132-
'''Write the Tikz vs. PDF comparison figures to the LaTeX file.
133-
'''
134-
file_handle.write('% test plot ' + str(test_id) + '\n'
135-
'\\begin{figure}%\n'
136-
'\\centering%\n'
137-
'\\begin{tabular}{cc}\n'
138-
'\includegraphics[width=\\figwidth]'
139-
'{' + str(pdf_path) + '}%\n'
140-
'&\n'
141-
'\input{' + str(tikz_path) + '}%\n'
142-
'\\end{tabular}\n'
143-
'\\caption{' + str(comment) + ' (test ID ' +
144-
str(test_id) + ').}%\n'
145-
'\\end{figure}\\clearpage\n\n'
146-
)
125+
def write_file_comparison_entry(file_handle, pdf_path, tikz_path, test_id, comment):
126+
"""Write the Tikz vs. PDF comparison figures to the LaTeX file.
127+
"""
128+
file_handle.write(
129+
"% test plot " + str(test_id) + "\n"
130+
"\\begin{figure}%\n"
131+
"\\centering%\n"
132+
"\\begin{tabular}{cc}\n"
133+
"\includegraphics[width=\\figwidth]"
134+
"{" + str(pdf_path) + "}%\n"
135+
"&\n"
136+
"\input{" + str(tikz_path) + "}%\n"
137+
"\\end{tabular}\n"
138+
"\\caption{" + str(comment) + " (test ID " + str(test_id) + ").}%\n"
139+
"\\end{figure}\\clearpage\n\n"
140+
)
147141
return
148142

149143

150144
def _parse_options():
151-
'''Parse input options.'''
145+
"""Parse input options."""
152146
import argparse
153-
parser = argparse.ArgumentParser(
154-
description='Acid test for matplotlib2tikz.'
155-
)
147+
148+
parser = argparse.ArgumentParser(description="Acid test for matplotlib2tikz.")
156149
parser.add_argument(
157-
'--dir', '-d',
158-
metavar='TEST_DIR',
159-
type=str,
160-
default='./tex/',
161-
help='directory for the test output (default: ./tex/)'
162-
)
150+
"--dir",
151+
"-d",
152+
metavar="TEST_DIR",
153+
type=str,
154+
default="./tex/",
155+
help="directory for the test output (default: ./tex/)",
156+
)
163157
parser.add_argument(
164-
'tests',
165-
metavar='TEST_NAME',
166-
nargs='*',
167-
type=str,
168-
help='tests to perform (default: all)'
169-
)
158+
"tests",
159+
metavar="TEST_NAME",
160+
nargs="*",
161+
type=str,
162+
help="tests to perform (default: all)",
163+
)
170164
args = parser.parse_args()
171165
return args.dir, args.tests
172166

173167

174-
if __name__ == '__main__':
168+
if __name__ == "__main__":
175169
# execute the test
176170
_main()

0 commit comments

Comments
 (0)