Skip to content

Commit

Permalink
refactor for testability, add simple test
Browse files Browse the repository at this point in the history
  • Loading branch information
nico committed Sep 21, 2014
1 parent 15692db commit 335cf1e
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 14 deletions.
34 changes: 20 additions & 14 deletions ninjatracing
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,12 @@ class Threads:
return len(self.workers) - 1


def read_targets(log_file):
def read_targets(log):
"""Reads all targets from .ninja_log file |log_file|."""
with open(log_file, 'r') as f:
header = f.readline()
assert header == "# ninja log v5\n", \
"unrecognized ninja log version %r" % header
targets = [Target(line.strip().split('\t')) for line in f]
header = log.readline()
assert header == "# ninja log v5\n", \
"unrecognized ninja log version %r" % header
targets = [Target(line.strip().split('\t')) for line in log]
return targets


Expand All @@ -65,17 +64,24 @@ def construct_jobs(targets):
return sorted(jobs.values(), key = lambda job: job.start)


def log_to_dicts(log, pid):
"""Reads a file-like object |log| containing a .ninja_log, and yields one
about:tracing dict per command found in the log."""
threads = Threads()
for job in construct_jobs(read_targets(log)):
yield {
'name': '%0s' % ', '.join(job.targets), 'cat': 'targets',
'ph': 'X', 'ts': str(job.start * 1000),
'dur': str((job.end - job.start) * 1000),
'pid': str(pid), 'tid': str(threads.alloc(job)), 'args': {},
}


def main(argv):
entries = []
for pid, log_file in enumerate(argv):
threads = Threads()
for job in construct_jobs(read_targets(log_file)):
entries.append({
'name': '%0s' % ', '.join(job.targets), 'cat': 'targets',
'ph': 'X', 'ts': str(job.start * 1000),
'dur': str((job.end - job.start) * 1000),
'pid': str(pid), 'tid': str(threads.alloc(job)), 'args': {},
})
with open(log_file, 'r') as log:
entries += list(log_to_dicts(log, pid))
json.dump(entries, sys.stdout)


Expand Down
1 change: 1 addition & 0 deletions ninjatracing.py
34 changes: 34 additions & 0 deletions ninjatracing_test
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python

import ninjatracing
import unittest

try:
from StringIO import StringIO
except ImportError:
from io import StringIO

class TestNinjaTracing(unittest.TestCase):

def test_simple(self):
log = StringIO("# ninja log v5\n"
"100\t200\t0\tmy_output\tdeadbeef\n"
"50\t120\t0\tmy_first_output\t0afef\n")
dicts = list(ninjatracing.log_to_dicts(log, 42))
expected = [
{
'name': 'my_first_output', 'cat': 'targets', 'ph': 'X',
'ts': '50000', 'dur': '70000', 'pid': '42', 'tid': '0',
'args': {}
},
{
'name': 'my_output', 'cat': 'targets', 'ph': 'X',
'ts': '100000', 'dur': '100000', 'pid': '42', 'tid': '1',
'args': {}
},
]
self.assertEqual(expected, dicts)


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

0 comments on commit 335cf1e

Please sign in to comment.