• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6'''Common tools for unit-testing writers.'''
7
8
9import os
10import tempfile
11import unittest
12import StringIO
13
14from grit import grd_reader
15from grit import util
16from grit.tool import build
17
18
19class DummyOutput(object):
20  def __init__(self, type, language, file = 'hello.gif'):
21    self.type = type
22    self.language = language
23    self.file = file
24  def GetType(self):
25    return self.type
26  def GetLanguage(self):
27    return self.language
28  def GetOutputFilename(self):
29    return self.file
30
31
32class WriterUnittestCommon(unittest.TestCase):
33  '''Common class for unittesting writers.'''
34
35  def PrepareTest(self, policy_json):
36    '''Prepares and parses a grit tree along with a data structure of policies.
37
38    Args:
39      policy_json: The policy data structure in JSON format.
40    '''
41    # First create a temporary file that contains the JSON policy list.
42    tmp_file_name = 'test.json'
43    tmp_dir_name = tempfile.gettempdir()
44    json_file_path = tmp_dir_name + '/' + tmp_file_name
45    with open(json_file_path, 'w') as f:
46      f.write(policy_json.strip())
47    # Then assemble the grit tree.
48    grd_text = '''
49    <grit base_dir="." latest_public_release="0" current_release="1" source_lang_id="en">
50      <release seq="1">
51        <structures>
52          <structure name="IDD_POLICY_SOURCE_FILE" file="%s" type="policy_template_metafile" />
53        </structures>
54      </release>
55    </grit>''' % json_file_path
56    grd_string_io = StringIO.StringIO(grd_text)
57    # Parse the grit tree and load the policies' JSON with a gatherer.
58    grd = grd_reader.Parse(grd_string_io, dir=tmp_dir_name)
59    grd.SetOutputLanguage('en')
60    grd.RunGatherers()
61    # Remove the policies' JSON.
62    os.unlink(json_file_path)
63    return grd
64
65  def GetOutput(self, grd, env_lang, env_defs, out_type, out_lang):
66    '''Generates an output of a writer.
67
68    Args:
69      grd: The root of the grit tree.
70      env_lang: The environment language.
71      env_defs: Environment definitions.
72      out_type: Type of the output node for which output will be generated.
73        This selects the writer.
74      out_lang: Language of the output node for which output will be generated.
75
76    Returns:
77      The string of the template created by the writer.
78    '''
79    grd.SetOutputLanguage(env_lang)
80    grd.SetDefines(env_defs)
81    buf = StringIO.StringIO()
82    build.RcBuilder.ProcessNode(grd, DummyOutput(out_type, out_lang), buf)
83    return buf.getvalue()
84