def do_test(self, policy_data, writer):
    '''Executes a test case.

    Creates and invokes an instance of PolicyTemplateGenerator with
    the given arguments.

    Notice: Plain comments are used in test methods instead of docstrings,
    so that method names do not get overridden by the docstrings in the
    test output.

    Args:
      policy_data: The list of policies and groups as it would be
        loaded from policy_templates.json.
      writer: A writer used for this test. It is usually derived from
        mock_writer.MockWriter.
    '''
    writer.tester = self
    config = {
      'app_name': '_app_name',
      'frame_name': '_frame_name',
      'os_name': '_os_name',
    }
    if not 'messages' in policy_data:
      policy_data['messages'] = {}
    if not 'placeholders' in policy_data:
      policy_data['placeholders'] = []
    if not 'policy_definitions' in policy_data:
      policy_data['policy_definitions'] = []
    policy_generator = policy_template_generator.PolicyTemplateGenerator(
        config,
        policy_data)
    res = policy_generator.GetTemplateText(writer)
    writer.Test()
    return res
Exemple #2
0
    def GetOutput(self, policy_json, definitions, writer_type):
        '''Generates an output of a writer.

    Args:
      policy_json: Raw policy JSON string.
      definitions: Definitions to create writer configurations.
      writer_type: Writer type (e.g. 'admx'), see template_formatter.py.

    Returns:
      The string of the template created by the writer.
    '''

        # Evaluate policy_json. For convenience, fix indentation in statements like
        # policy_json = '''
        #   {
        #     ...
        #   }''')
        start_idx = 1 if policy_json[0] == '\n' else 0
        policy_data = eval(textwrap.dedent(policy_json[start_idx:]))

        config = writer_configuration.GetConfigurationForBuild(definitions)
        policy_generator = \
            policy_template_generator.PolicyTemplateGenerator(config, policy_data)
        writer = template_formatter.GetWriter(writer_type, config)
        return policy_generator.GetTemplateText(writer)
    def testImportMessage_noIndentation(self):
        message = '''
Simple policy:

Description of simple policy'''

        policy_generator = policy_template_generator.PolicyTemplateGenerator(
            self.TEST_CONFIG, self.TEST_POLICY_DATA)
        self.assertEquals(message, policy_generator._ImportMessage(message))
    def testImportMessage_withIndentation(self):
        message = '''JSON policy:

        JSON spec:
        {
          "key": {
            "key2": "value"
          }
        }'''
        imported_message = '''JSON policy:

JSON spec:
{
  "key": {
    "key2": "value"
  }
}'''

        policy_generator = policy_template_generator.PolicyTemplateGenerator(
            self.TEST_CONFIG, self.TEST_POLICY_DATA)
        self.assertEquals(imported_message,
                          policy_generator._ImportMessage(message))
    def do_test(self, policy_data, writer):
        '''Executes a test case.

    Creates and invokes an instance of PolicyTemplateGenerator with
    the given arguments.

    Notice: Plain comments are used in test methods instead of docstrings,
    so that method names do not get overridden by the docstrings in the
    test output.

    Args:
      policy_data: The list of policies and groups as it would be
        loaded from policy_templates.json.
      writer: A writer used for this test. It is usually derived from
        mock_writer.MockWriter.
    '''
        writer.tester = self

        policy_data = dict(self.TEST_POLICY_DATA, **policy_data)
        policy_generator = policy_template_generator.PolicyTemplateGenerator(
            self.TEST_CONFIG, policy_data)
        res = policy_generator.GetTemplateText(writer)
        writer.Test()
        return res
Exemple #6
0
def main(argv):
    '''Main policy template conversion script.
  Usage: template_formatter
           --translations <translations_path>
           --languages <language_list>
           [--adm <adm_path>]
           ...
           [--android_policy <android_policy_path>]
           -D <grit_define>
           -E <grit_env_variable>
           -t <grit_target_platform>

  Args:
    translations: Absolute path of the translated policy_template.json
        files. Must contain a ${lang} placeholder for the language.
    languages: Comma-separated list of languages. Trailing commas are fine, e.g.
        'en,de,'
    adm, adml, google_adml, doc, plist_string: Absolute path of the
        corresponding file types. Must contain a ${lang} placeholder.
    admx, google_admx, android_policy, reg, json, plist: Absolute path of the
        corresponding file types. Must NOT contain a ${lang} placeholder. There
        is only one output file, not one per language.
    D: List of grit defines, used to assemble writer configuration.
    E, t: Grit environment variables and target platform. Unused, but
        grit_rule.gni adds them, so OptionParser must handle them.
  '''
    parser = optparse.OptionParser()
    parser.add_option('--translations', dest='translations')
    parser.add_option('--languages', dest='languages')
    parser.add_option('--version_path', dest='version_path')
    parser.add_option('--adm', action='append', dest='adm')
    parser.add_option('--adml', action='append', dest='adml')
    parser.add_option('--admx', action='append', dest='admx')
    parser.add_option('--chromeos_adml', action='append', dest='chromeos_adml')
    parser.add_option('--chromeos_admx', action='append', dest='chromeos_admx')
    parser.add_option('--google_adml', action='append', dest='google_adml')
    parser.add_option('--google_admx', action='append', dest='google_admx')
    parser.add_option('--reg', action='append', dest='reg')
    parser.add_option('--doc', action='append', dest='doc')
    parser.add_option('--json', action='append', dest='json')
    parser.add_option('--plist', action='append', dest='plist')
    parser.add_option('--plist_strings', action='append', dest='plist_strings')
    parser.add_option('--android_policy',
                      action='append',
                      dest='android_policy')
    parser.add_option('-D', action='append', dest='grit_defines')
    parser.add_option('-E', action='append', dest='grit_build_env')
    parser.add_option('-t', action='append', dest='grit_target')
    options, args = parser.parse_args(argv[1:])

    _LANG_PLACEHOLDER = "${lang}"
    assert _LANG_PLACEHOLDER in options.translations

    languages = filter(bool, options.languages.split(','))
    assert _DEFAULT_LANGUAGE in languages

    config = _GetWriterConfiguration(options.grit_defines)
    config['major_version'] = _ParseVersionFile(options.version_path)

    # For each language, load policy data once and run all writers on it.
    for lang in languages:
        # Load the policy data.
        policy_templates_json_path = options.translations.replace(
            _LANG_PLACEHOLDER, lang)
        with codecs.open(policy_templates_json_path, 'r',
                         'utf-16') as policy_file:
            policy_data = eval(policy_file.read())

        # Preprocess the policy data.
        policy_generator = policy_template_generator.PolicyTemplateGenerator(
            config, policy_data)

        for writer_desc in _WRITER_DESCS:
            # For writer types that are not per language (e.g. admx), only do it once.
            if (not writer_desc.is_per_language and lang != _DEFAULT_LANGUAGE):
                continue

            # Was the current writer type passed as argument, e.g. --admx <path>?
            # Note that all paths are arrays and we loop over all of them.
            output_paths = getattr(options, writer_desc.type, '')
            if (not output_paths):
                continue
            for output_path in output_paths:
                # Substitute language placeholder in output file.
                if (writer_desc.is_per_language):
                    assert _LANG_PLACEHOLDER in output_path
                    mapped_lang = writer_desc.language_map(
                        lang) if writer_desc.language_map else lang
                    output_path = output_path.replace(_LANG_PLACEHOLDER,
                                                      mapped_lang)
                else:
                    assert _LANG_PLACEHOLDER not in output_path

                # Run the template writer on th policy data.
                writer = GetWriter(writer_desc.type, config)
                output_data = policy_generator.GetTemplateText(writer)
                # Make sure the file uses Windows line endings if needed.  This is
                # important here because codecs.open() opens files in binary more and
                # will not do line ending conversion.
                if writer_desc.force_windows_line_ending:
                    output_data = re.sub(r'([^\r])\n', r'\1\r\n', output_data)

                # Make output directory if it doesn't exist yet.
                output_dir = os.path.split(output_path)[0]
                if not os.path.exists(output_dir):
                    os.makedirs(output_dir)

                # Write output file.
                with codecs.open(output_path, 'w',
                                 writer_desc.encoding) as output_file:
                    output_file.write(output_data)