summaryrefslogtreecommitdiffstats
path: root/src/account/test/common.py
blob: 95abd381089506c3f9b4d6632f2303da322fa585 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# -*- encoding: utf-8 -*-
# Copyright (C) 2012-2014 Red Hat, Inc.  All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
#
# Authors: Roman Rakus <rrakus@redhat.com>
#
"""
Base class and utilities for all OpenLMI Account tests.
"""

import hashlib
import os
import tempfile
import string
import subprocess
from collections import defaultdict
from collections import OrderedDict

import methods
import lmi.test.util
from lmi.test import lmibase


class AccountBase(lmibase.LmiTestCase):
    """
    Base class for all LMI Account tests.
    """

    USE_EXCEPTIONS = True

    @classmethod
    def setUpClass(cls):
        lmibase.LmiTestCase.setUpClass.im_func(cls)
        cls.user_name = os.environ.get("LMI_ACCOUNT_USER")
        cls.group_name = os.environ.get("LMI_ACCOUNT_GROUP")


## ......................................................................... ##
## Validators
## ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ##

class PasswdFile():
    """
    Parse /etc/passwd and perform basic heuristics to assess validity.

    By heuristics, I mean it's OK to include here what is considered to
    be "normal", or "expected" rather than strictly vaid/invalid.  For
    example, you can consider "not normal" to have UID!=GID, but depending
    on what you did, it could be OK.  OTOH, keep in mind that more specific
    things should be in the test itself.
    """

    DEFAULT_OPTIONS = {
        'username_prefix': 'user',
        'unique': [
            "name",
            "uid",
        ]
    }

    def __init__(self, options=None):
        self.options = self.__class__.DEFAULT_OPTIONS
        if options is not None:
            self.options.update(options)
        self.users = []

        with open('/etc/passwd') as pf:
            lines = pf.readlines()
        self.fulltext = "".join(lines)

        for line in lines:
            fields = line.split(":")
            user = {
                "name": fields[0],
                "password": fields[1],
                "uid": fields[2],
                "gid": fields[3],
                "gecos": fields[4],
                "directory": fields[5],
                "shell": fields[6],
            }
            if user['name'].startswith(self.options['username_prefix']):
                self.users.append(user)

    def find_dups(self):
        """
        Find dups in fields that should be unique
        """
        dups = defaultdict(int)
        for field in self.options['unique']:
            if not methods.field_is_unique(field, self.users):
                dups[field] += 1
        return dict(dups)

    def get_errors(self):
        """
        Get hash of errors.
        """
        errlist = {}
        dups = self.find_dups()
        if dups:
            errlist['duplicates'] = dups
        return errlist

    def get_names(self):
        """
        Get list of user names
        """
        return [u['name'] for u in self.users]