Template generation function is added for most format modules.

packages
Иванов Денис 4 years ago
parent 7db61908ae
commit 63daadb9d3

@ -3,6 +3,7 @@
from collections import OrderedDict
from jinja2 import Environment, PackageLoader
from pprint import pprint
from copy import copy
try:
from lxml.etree.ElementTree import fromstring
except ImportError:
@ -96,40 +97,76 @@ class BaseFormat():
for key_value in template:
if key_value[0] == '!':
# Удаление соответствующего элемента из original.
# Сначала получаем ключ без символа действия.
if isinstance(key_value, tuple):
item_to_delete = ('',) + key_value[1:]
elif isinstance(key_value, str):
item_to_delete = key_value[1:]
# Удаляем соответствующий элемент, если он есть в оригинале.
if item_to_delete in original.keys():
original.pop(item_to_delete)
del(original[item_to_delete])
elif key_value[0] == '-':
# Замена соответствующего элемента из original.
# Сначала получаем ключ без символа действия.
if isinstance(key_value, tuple):
item_to_replace = ('',) + key_value[1:]
elif isinstance(key_value, str):
item_to_replace = key_value[1:]
# Если соответствующего элемента нет в оригинале -- пропускаем.
if item_to_replace not in original.keys():
continue
# Если секция для замены в шаблоне пустая -- удаляем
# соответствующую секцию.
if isinstance(template[key_value], dict) and\
template[key_value] == OrderedDict():
original.pop(item_to_replace)
continue
# Если символ замены стоит перед параметром, а не перед
# секцией -- просто заменяем значение параметра.
if not isinstance(template[key_value], dict):
original[item_to_replace] = template[key_value]
continue
# Если обработка комментариев включена -- сохраняем
# комментарии к заменяемой секции.
if self._comments_processing:
if '#' in original[item_to_replace]:
replaced = OrderedDict({'#':
original[item_to_replace]['#']}
)
replaced.update(template[key_value])
replacement = OrderedDict({'#':
original[item_to_replace]
['#']}
)
# накладываем словарь шаблона на пустой словарь, чтобы
# выполнить все управляющие элементы, которые
# могут туда попасть.
self._join(replacement,
template[key_value],
self._join_before_in_areas)
else:
replaced = template[key_value]
replacement = OrderedDict()
self._join(replacement,
template[key_value],
self._join_before_in_areas)
original[item_to_replace] = replaced
# Если после наложения шаблона словарь замены оказался
# пустым -- удаляем соотвествующий элемент в оригинале.
if (replacement == OrderedDict() or
replacement.keys() == {'#'}):
del(original[item_to_replace])
else:
original[item_to_replace] = replacement
else:
original[item_to_replace] = template[key_value]
original[item_to_replace] = OrderedDict()
self._join(original[item_to_replace],
template[key_value],
self._join_before_in_areas)
if (original[item_to_replace] == OrderedDict() or
original[item_to_replace].keys() == {'#'}):
del(original[item_to_replace])
elif key_value not in original.keys():
if isinstance(template[key_value], dict):
@ -163,6 +200,89 @@ class BaseFormat():
original[key_value] = forwarded_items[key_value]
original.move_to_end(key_value, last=False)
def make_template(self, template):
full_diff, set_to_check = self.compare_dictionaries(
self._document_dictionary,
template._document_dictionary
)
template_object = copy(self)
template_object._document_dictionary = full_diff
return template_object
def compare_dictionaries(self, dict_1, dict_2):
to_remove_dictionary = OrderedDict()
to_add_dictionary = OrderedDict()
to_replace_dictionary = OrderedDict()
unchanged_set = set()
to_remove = dict_1.keys() - dict_2.keys()
if '#' in to_remove:
to_remove.remove('#')
for key in dict_1:
if key in to_remove:
if isinstance(key, tuple):
new_key = ('!', *key[1:])
else:
new_key = '!{}'.format(key)
if isinstance(dict_1[key], dict):
to_remove_dictionary.update({new_key: dict_1[key]})
else:
if self._comments_processing:
to_remove_dictionary.update({new_key:
[dict_1[key][-1]]})
else:
to_remove_dictionary.update({new_key: dict_1[key]})
to_add = dict_2.keys() - dict_1.keys()
if '#' in to_add:
to_add.remove('#')
for key in dict_2:
if key in to_add:
if isinstance(dict_2[key], dict):
section = dict_2[key].copy()
if '#' in section:
section.remove('#')
to_add_dictionary.update({key: section})
else:
if self._comments_processing:
to_add_dictionary.update({key: [dict_2[key][-1]]})
else:
to_add_dictionary.update({key: dict_2[key]})
intersect = dict_1.keys() & dict_2.keys()
for key in intersect:
if (isinstance(dict_1[key], dict) and
isinstance(dict_2[key], dict) and
dict_1[key] != dict_2[key]):
diff, set_to_check = self.compare_dictionaries(dict_1[key],
dict_2[key])
if set_to_check:
to_add_dictionary.update({key: diff})
else:
if isinstance(key, tuple):
new_key = ('-', *key[1:])
else:
new_key = '-{}'.format(key)
to_replace_dictionary.update({new_key:
dict_2[key]})
elif dict_1[key] != dict_2[key]:
if self._comments_processing:
to_add_dictionary.update({key: [dict_2[key][-1]]})
else:
to_add_dictionary.update({key: dict_2[key]})
else:
unchanged_set.add(key)
full_diff = OrderedDict()
full_diff.update(**to_remove_dictionary,
**to_replace_dictionary,
**to_add_dictionary)
return full_diff, unchanged_set
def get_document_text(self):
file_loader = PackageLoader('calculate.templates.format',
self.TEMPLATES_DIRECTORY)

@ -13,7 +13,8 @@ from pyparsing import originalTextFor, Literal, ZeroOrMore, Word, printables,\
class DovecotFormat(BaseFormat):
_initialized = False
def __init__(self, document_text: str, ignore_comments=False):
def __init__(self, document_text: str, ignore_comments=False,
join_before=False):
processing_methods = [self._parse_comment_line,
self._parse_section_start_line,
self._parse_include_line,
@ -25,6 +26,7 @@ class DovecotFormat(BaseFormat):
self._ignore_comments = ignore_comments
self._need_finish = True
self._comments_processing = True
self._join_before = join_before
self._format = 'dovecot'
self._section_stack = OrderedDict()

@ -6,10 +6,13 @@ import json
class JSONFormat(BaseFormat):
def __init__(self, document_text: str, ignore_comments=False):
def __init__(self, document_text: str, ignore_comments=False,
join_before=False):
processing_methods = []
super().__init__(processing_methods)
self._ignore_comments = ignore_comments
self._join_before = join_before
self._comments_processing = False
self._format = 'json'
if document_text == '':

@ -10,18 +10,18 @@
{% endfor %}
{% endif %}
{% if item_name[1] == 'inet' %}
{{ item_name[1:] | join(' ') }}
{{ item_name[0] + item_name[1:] | join(' ') }}
{%- for keyword in item_value %}
{%- if keyword != '#' %} {{ keyword[1] }} { {{ item_value[keyword] | join('; ')}}; }{% endif %}{% endfor %};
{% else %}
{{ item_name[1:] | join(' ') }} {
{{ item_name[0] + item_name[1:] | join(' ') }} {
{{ loop(item_value.items()) | indent}}};
{% endif %}
{% else %}
{% for comment in item_value[:-1] %}
{{ comment }}
{% endfor %}
{{ item_name[1:] | join(' ') }}{% if not item_value[-1] == '' %} {{ item_value[-1] }}{% endif%};
{{ item_name[0] + item_name[1:] | join(' ') }}{% if not item_value[-1] == '' %} {{ item_value[-1] }}{% endif%};
{% endif %}
{% endif %}
{% endfor %}

@ -4,13 +4,13 @@
{{ comment }}
{% endfor %}
{% endif %}
[{{ section_name[1] }}]
[{{ section_name | join('') }}]
{% for parameter_name in document_dictionary[section_name].keys() %}
{% if parameter_name != '#' %}
{% for comment in document_dictionary[section_name][parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }}={{ document_dictionary[section_name][parameter_name][-1] }}
{{ parameter_name | join('') }}={{ document_dictionary[section_name][parameter_name][-1] }}
{% endif %}
{% endfor %}

@ -1,18 +1,18 @@
{% for item_name, item_value in document_dictionary.items() recursive %}
{% if item_name != '#' %}
{% if item_name != '#' and item_name[1] != '!include' %}
{% if item_value is mapping %}
{% if '#' in item_value %}
{% for comment in item_value['#'] %}
{{ comment }}
{% endfor %}
{% endif %}
{{ item_name[1:] | join(' ') }} {
{{ item_name[0] + item_name[1:] | join(' ') }} {
{{ loop(item_value.items()) | indent}}}
{% else %}
{% for comment in item_value[:-1] %}
{{ comment }}
{% endfor %}
{{ item_name[1:] | join(' ') }}{%- if not item_value[-1] == '' %} = {{ item_value[-1] }}
{{ item_name[0] + item_name[1:] | join(' ') }}{%- if not item_value[-1] == '' %} = {{ item_value[-1] }}
{% else %}
{%- if not loop.last%}
@ -24,5 +24,11 @@
{% endif %}
{% endif %}
{% endfor %}
{% for item_name in document_dictionary.keys() %}
{% if item_name[1] == '!include' %}
{{ item_name[0] + item_name[1:] | join(' ') }}
{% if not loop.last%}
{% endif %}
{% endif %}
{% endfor %}

@ -4,15 +4,13 @@
{{ comment }}
{% endfor %}
{% endif %}
{% for section_part in section_name[1:] %}
[{{ section_part }}]{% endfor %}
[{{ section_name[0] + section_name[1:] | join('][') }}]
{% for parameter_name in document_dictionary[section_name].keys() %}
{% if parameter_name != '#' %}
{% for comment in document_dictionary[section_name][parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }}={{ document_dictionary[section_name][parameter_name][-1] }}
{{ parameter_name[0] + parameter_name[1] }}={{ document_dictionary[section_name][parameter_name][-1] }}
{% endif %}
{% endfor %}

@ -2,5 +2,5 @@
{% for comment in document_dictionary[parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }}={{ document_dictionary[parameter_name][-1] }}
{{ parameter_name[0] + parameter_name[1] }}={{ document_dictionary[parameter_name][-1] }}
{% endfor %}

@ -5,13 +5,13 @@
{% endfor %}
{% endif %}
{% if section_type != ('', 'global')%}
{{ section_type[1] }} {{ section_type[2] }}
{{ section_type[0] + section_type[1] }} {{ section_type[2] }}
{% endif %}
{% for directive in document_dictionary[section_type].keys() if directive[1] == 'include' %}
{% for comment in document_dictionary[section_type][directive][:-1] %}
{{ comment }}
{% endfor %}
{{ directive[1] }} {{ directive[2] }}
{{ directive[0] + directive[1] }} {{ directive[2] }}
{% endfor %}
{% for directive in document_dictionary[section_type].keys() %}
{% if directive != '#' and directive[1] != 'include' %}
@ -25,11 +25,11 @@
{% set access_values = access_values[1:] %}
{% endif %}
{% if access_values|length == 1 %}
{{ directive[1] }} {{ directive[2] }} by {{ access_values[0][1] }} {{ directive_value[access_values[0]][0] }}
{{ directive[0] + directive[1] }} {{ directive[2] }} by {{ access_values[0][1] }} {{ directive_value[access_values[0]][0] }}
{% else %}
{{ directive[1] }} {{ directive[2] }}
{{ directive[0] + directive[1] }} {{ directive[2] }}
{% for value in access_values|reverse %}
by {{ value[1] }} {{ directive_value[value][0] }}
by {{ value[0] + value[1] }} {{ directive_value[value][0] }}
{% endfor %}
{% endif %}
{% elif directive[1] == 'syncrepl' %}
@ -40,15 +40,15 @@
{% endfor %}
{% set syncrepl_values = syncrepl_values[1:]%}
{% endif %}
{{ directive[1] }} {{ directive[2] }}
{{ directive[0] + directive[1] }} {{ directive[2] }}
{% for value in syncrepl_values %}
{{ value[1] }}={{ directive_value[value][0] }}
{{ value[0] + value[1] }}={{ directive_value[value][0] }}
{% endfor %}
{% else %}
{% for comment in directive_value[:-1] %}
{{ comment }}
{% endfor %}
{{ directive[1:]|join(' ') }}{% if directive_value[-1] != '' %} {{ directive_value[-1] }}
{{ directive[0] + directive[1:]|join(' ') }}{% if directive_value[-1] != '' %} {{ directive_value[-1] }}
{% else %}
{% endif %}

@ -2,6 +2,6 @@
{% for comment in document_dictionary[parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }}={{ document_dictionary[parameter_name][-1] }}
{{ parameter_name[0] + parameter_name[1] }}={{ document_dictionary[parameter_name][-1] }}
{% endfor %}

@ -2,7 +2,7 @@
{% for comment in document_dictionary[parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }} = {{ document_dictionary[parameter_name][-1] }}
{{ parameter_name[0] + parameter_name[1] }} = {{ document_dictionary[parameter_name][-1] }}
{% endfor %}

@ -2,6 +2,6 @@
{% for comment in document_dictionary[parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }}={{ document_dictionary[parameter_name][-1] }}
{{ parameter_name[0] + parameter_name[1] }}={{ document_dictionary[parameter_name][-1] }}
{% endfor %}

@ -4,13 +4,13 @@
{{ comment }}
{% endfor %}
{% endif %}
[{{ section_name[1] }}]
[{{ section_name | join('') }}]
{% for parameter_name in document_dictionary[section_name].keys() %}
{% if parameter_name != '#' %}
{% for comment in document_dictionary[section_name][parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1] }} = {{ document_dictionary[section_name][parameter_name][-1] }}
{% endif %}
{% endfor %}
{{ parameter_name | join('') }} = {{ document_dictionary[section_name][parameter_name][-1] }}
{% endif %}
{% endfor %}
{% endfor %}

@ -1,14 +0,0 @@
{% for parameter_name, parameter_value in document_dictionary.items() %}
{% for comment in document_dictionary[parameter_name][:-1]%}
{{ comment }}
{% endfor %}
{{ parameter_name[1:] | join(' ') }}{%- if not parameter_value[-1] == '' %} {{ parameter_value[-1] }}
{% else %}
{%- if not loop.last%}
{% endif %}
{% endif %}
{% endfor %}

@ -1,3 +1,5 @@
# vim: fileencoding=utf-8
#
from jinja2.ext import Extension
from jinja2 import Environment, FileSystemLoader, TemplateSyntaxError, nodes
from jinja2.utils import missing

@ -296,3 +296,46 @@ options {
result_text = result_file.read()
assert bind_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''
pid-file "/run/named/named.pid";
disable-empty-zone "12.out-addr.arpa";
acl "dns_servers" {
127.0.0.1;
10.0.1.3;
10.1.0.3;
10.2.0.3;
10.3.0.3;
};
options {
response-policy {
zone "any.zone";
};
recursion no;
}
'''
document_2 = '''pid-file "/run/named/named.pid";
disable-empty-zone "10.in-addr.arpa";
acl "dns_servers" {
127.0.0.1;
10.3.0.3;
10.1.1.3;
10.0.0.3;
};
options {
response-policy {
zone "rpz.zone";
};
recursion yes;
};
'''
document_1_object = BINDFormat(document_1)
document_2_object = BINDFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -216,3 +216,42 @@ class TestParsingMethods:
result_text = result_file.read()
assert compiz_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''[Added Associations]
application/illustrator=zzz-gimp.desktop
application/pdf=evince.desktop;
application/rtf=libreoffice-writer.desktop;
[Non Realistic Section]
audio/mp4=clementine.desktop;
audio/mpeg=clementine.desktop;
audio/x-flac=clementine.desktop;
'''
document_2 = '''[Added Associations]
image/bmp=gwenview.desktop;
image/gif=gwenview.desktop;
image/jpeg=gwenview.desktop;
image/jpg=gwenview.desktop;
image/png=gwenview.desktop;
[Non Realistic Section]
audio/mp4=clementine.desktop;
audio/mpeg=clementine.desktop;
audio/x-ms-wma=clementine.desktop;
audio/x-wav=clementine.desktop;
[Strange Section]
video/mp4=smplayer.desktop;
video/mpeg=smplayer.desktop;
video/quicktime=smplayer.desktop;
video/vnd.mpegurl=smplayer.desktop;
'''
document_1_object = CompizFormat(document_1)
document_2_object = CompizFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -253,3 +253,57 @@ class TestParsingMethods:
result_text = result_file.read()
assert dovecot_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''auth_default_realm = domain.com
auth_mechanisms = plain login
# Log unsuccessful authentication attempts and the reasons why they failed.
auth_verbose = no
dict {
acl = mysql:/usr/local/etc/dovecot/shared-folders.conf
}
namespace inbox {
# These mailboxes are widely used and could perhaps be created automatically:
mailbox Drafts {
special_use = \\Drafts
}
}
!include auth-passwdfile.conf.ext'''
document_2 = '''auth_realms = domain.com domain2.com
auth_verbose_passwords = no
auth_default_realm = other_domain.com
# Log unsuccessful authentication attempts and the reasons why they failed.
auth_verbose = yes
dict {
acl = mysql:/etc/dovecot/shared-folders.conf
sqlquota = mysql:/usr/local/etc/dovecot/quota.conf
}
namespace inbox {
# These mailboxes are widely used and could perhaps be created automatically:
mailbox Drafts {
special_use = \\Drafts
}
mailbox Junk {
special_use = \\Junk
}
}
!include auth-checkpassword.conf.ext
'''
document_1_object = DovecotFormat(document_1, join_before=True)
document_2_object = DovecotFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -42,3 +42,42 @@ class TestParsingMethods:
resultText = resultFile.read()
assert jsonOriginalObject.get_document_text() == resultText
def test_make_template(self):
document_1 = '''
{
"Param1":"ParamValue1",
"Param2": 1,
"BlockParam1":{
"BlockParam1":1,
"BlockParam2":0
},
"BlockParam2":{
"BlockParam1":"value",
"BlockParam2":false,
"BlockParam4":"other value"
},
"Param3": true
}
'''
document_2 = '''{
"Param1": "ParamValue1",
"BlockParam1": {
"BlockParam1": 12,
"BlockParam3": true
},
"BlockParam2": {
"BlockParam2": true,
"BlockParam4": "other value",
"BlockParam3": 12
},
"Param3": false,
"Param4": 12.3
}'''
document_1_object = JSONFormat(document_1)
document_2_object = JSONFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -220,3 +220,41 @@ class TestParsingMethods:
result_text = result_file.read()
assert kde_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''[PlasmaViews][Panel 69][Horizontal 1024]
alignment=132
length=674
panelVisibility=1
thickness=56
[PlasmaViews][Panel 69]
alignment=124
parameter=true
[PlasmaRunnerManager]
LaunchCounts=None
pluginWhiteList=services,shell,bookmarks,baloosearch,locations'''
document_2 = '''[PlasmaViews][Panel 69][Horizontal 1024]
alignment=128
panelVisibility=1
maxLength=674
minLength=674
[PlasmaRunnerManager]
Count=What the freakin count...
pluginWhiteList=shell,bookmarks,locations
[FileDialogSize]
Height 1080=466
Width 1920=747
'''
document_1_object = KDEFormat(document_1)
document_2_object = KDEFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -110,3 +110,28 @@ class TestParsingMethods:
result_text = result_file.read()
assert kernel_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''
CONFIG_CC_IS_GCC=y
CONFIG_GCC_VERSION=90500
CONFIG_CLANG_VERSION=0
CONFIG_CC_HAS_ASM_GOTO=y
CONFIG_IRQ_WORK=y
'''
document_2 = '''CONFIG_CC_IS_GCC=y
CONFIG_GCC_VERSION=90200
CONFIG_IRQ_WORK=n
CONFIG_BUILDTIME_EXTABLE_SORT=y
CONFIG_THREAD_INFO_IN_TASK=n
CONFIG_EXT3_FS_POSIX_ACL=y
CONFIG_EXT3_FS_SECURITY=n
'''
document_1_object = KernelFormat(document_1)
document_2_object = KernelFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -362,3 +362,63 @@ database bdb
result_text = result_file.read()
assert ldap_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''
include /etc/openldap/schema/core.schema
include /etc/openldap/schema/nis.schema
access to attrs=userPassword
by dn="cn=ldapadmin,dc=calculate" write
by dn="ou=Samba,ou=Services,dc=calculate" write
by dn="ou=Mail,ou=Services,dc=calculate" read
by dn="ou=Ftp,ou=Services,dc=calculate" read
by dn="ou=Replication,ou=LDAP,ou=Services,dc=calculate" write
by self read
by * auth
backend bdb
suffix "dc=example"
modulepath /usr/lib/openldap
database bdb
include /etc/openldap/replication.conf
suffix "dc=example, dc=calculate"
cachesize 10000
sizelimit unlimited
'''
document_2 = '''
include /etc/openldap/schema/core.schema
include /etc/openldap/schema/cosine.schema
access to attrs=userPassword
by dn="cn=ldapadmin,dc=calculate" write
by dn="ou=Samba,ou=Services,dc=calculate" write
by dn="ou=Unix,ou=Services,dc=calculate" write
by dn="ou=Jabber,ou=Services,dc=calculate" read
by dn="ou=Replication,ou=LDAP,ou=Services,dc=calculate" write
by self read
by * auth
backend bdb
suffix "dc=example"
rootdn "cn=ldaproot,dc=calculate"
modulepath /usr/lib/openldap
database bdb
include /etc/openldap/replication.conf
suffix "dc=example, dc=calculate"
checkpoint 1024 5
sizelimit limited
'''
document_1_object = LDAPFormat(document_1)
document_2_object = LDAPFormat(document_2)
template = document_1_object.make_template(document_2_object)
print('Template:')
print(template.get_document_text())
document_1_object.join_template(template)
print('Joining result:')
print(document_1_object.get_document_text())
assert False
# assert document_1_object.get_document_text() == document_2

@ -144,3 +144,53 @@ class TestParsingMethods:
result_text = result_file.read()
assert openrc_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''rc_tty_number=12
# The following setting turns on the memory.use_hierarchy setting in the
# root memory cgroup for cgroups v1.
# It must be set to yes in this file if you want this functionality.
rc_cgroup_memory_use_hierarchy="NO"
# This sets the mode used to mount cgroups.
# "hybrid" mounts cgroups version 2 on /sys/fs/cgroup/unified and
# cgroups version 1 on /sys/fs/cgroup.
# "legacy" mounts cgroups version 1 on /sys/fs/cgroup
# "unified" mounts cgroups version 2 on /sys/fs/cgroup
rc_cgroup_mode="hybrid"
# If you use the classical configuration file:
opts_conf="-f /etc/${INSTANCE}/slapd.conf"
# Multiple settings and values can be specified.
# For example, you would use this to set the maximum memory and maximum
# number of pids for a service.
rc_cgroup_settings="10485760"'''
document_2 = '''rc_tty_number=12
# The following setting turns on the memory.use_hierarchy setting in the
# root memory cgroup for cgroups v1.
# It must be set to yes in this file if you want this functionality.
rc_cgroup_memory_use_hierarchy="YES"
# Multiple settings and values can be specified.
# For example, you would use this to set the maximum memory and maximum
# number of pids for a service.
rc_cgroup_settings="10485760"
instance="openldap${SVCNAME#slapd}"
rc_cgroup_cleanup="NO"
rc_send_sighup="YES"
'''
document_1_object = OpenRCFormat(document_1)
document_2_object = OpenRCFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -122,3 +122,58 @@ class TestParsingMethods:
result_text = result_file.read()
assert postfix_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''
#Рабочая директория Postfix. То место, где временно сохраняется
#вся приходящая почта до процесса доставки.
queue_directory = /var/spool/postfix
#Путь для всех выполняемых программ почтового сервера.
command_directory = /usr/sbin
mynetworks = 10.0.0.0/8, 80.246.243.18, 95.213.228.194, 94.159.1.246, 109.167.151.108, 80.246.245.82, 80.246.248.234, 93.100.239.44
#По умолчанию, Postfix пытается посылать почту в Internet напрямую. В зависимости
#от окружения, в котором функционирует Ваш почтовый сервер, это может быть
#невозможно или нежелательно. Например, Ваша машина может быть отключена от
#Internet-а в нерабочее время, она может быть закрыта файрволлом, Ваш провайдер
#может запрещать пересылку почты в Internet напрямую. В таких случаях Вам
#необходимо настроить Postfix на пересылку писем через другой почтовый сервер
#(relay host).
#Вариант, заключенный в квадратные скобки [], заставляет Postfix
#не предпринимать поиск записей DNS MX.
#по умолчанию: посылать в Internet напрямую
#relayhost = [mail.$mydomain]
relay_domains = lists.calculate-linux.org
#Для создания базы используется postmap
transport_maps = hash:/etc/postfix/transport_maps
relay_recipient_maps = hash:/etc/postfix/valid_recipients
'''
document_2 = '''#Рабочая директория Postfix. То место, где временно сохраняется
#вся приходящая почта до процесса доставки.
queue_directory = /var/spool/postfix
#Путь для всех выполняемых программ почтового сервера.
command_directory = /usr/sbin
mynetworks = 10.0.0.0/8, 80.246.243.18, 94.159.1.246, 80.246.245.82, 93.100.239.44
relay_recipient_maps = hash:/etc/postfix/valid_recipient_maps
chmod = 0644
chown = root:root
mail_owner = postfix
'''
document_1_object = PostfixFormat(document_1)
document_2_object = PostfixFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -128,3 +128,35 @@ class TestParsingMethods:
result_text = result_file.read()
assert procmail_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''# port for HTTP (descriptions, SOAP, media transfer) traffic
port=8200
# specify the user account name or uid to run as
user=jmaggard
friendly_name=mike-desktop
vm.dirty_ratio = 3'''
document_2 = '''# port for HTTP (descriptions, SOAP, media transfer) traffic
port=8200
# specify the user account name or uid to run as
user=lol
vm.dirty_ratio=4
media_dir=PV,/var/calculate/server-data/samba/share
net.ipv4.icmp_echo_ignore_broadcasts=1
'''
document_1_object = ProcmailFormat(document_1)
document_2_object = ProcmailFormat(document_2)
template = document_1_object.make_template(document_2_object)
document_1_object.join_template(template)
assert document_1_object.get_document_text() == document_2

@ -227,3 +227,32 @@ class TestParsingMethods:
result_text = result_file.read()
assert samba_original_object.get_document_text() == result_text
def test_make_template(self):
document_1 = '''
# comment
[section name 2]
# comment 2
parameter name = /home/divanov/Home
other parameter = yes
weird parameter = something strange
[section name 3]
another parameter = 1'''
document_2 = '''# comment
[section name 2]
# comment 2
parameter name = /home/divanov/Home
other parameter = yes
[section name 3]
unspoken parameter = 1
unbelievable parameter = Mystical
[section name 1]
parameter name = /homeless/poorness
one more parameter = oh no
'''
document_1_object = SambaFormat(document_1)
document_2_object = SambaFormat(document_2)
template_object = document_1_object.make_template(document_2_object)
document_1_object.join_template(template_object)
assert document_1_object.get_document_text() == document_2

Loading…
Cancel
Save