#!/usr/bin/env python

import unittest
import winbind
import string
import grp

def is_domain_group(group):
    """Return true if group is a domain group"""

    return string.find(group, winbind.config["workgroup"] +
                       winbind.config["separator"]) == 0

class domgroups(unittest.TestCase):
    """Test enumerate domain groups"""

    def test(self):
        """Test enumerated domain groups consistent with getgrent"""

        # Get results of getgrent and enum domain groups
        
        gr = grp.getgrall()
        domgroups = winbind.enum_domain_groups()

        gr_hash = {}
        domgroups_hash = {}

        # Convert lists to hashes

        for group in gr:
            if is_domain_group(group[0]):
                gr_hash[group[0]] = 1

        for group in domgroups:
            if is_domain_group(group):
                domgroups_hash[group] = 1

        # Compare data

        gr_list = gr_hash.keys()
        gr_list.sort()

        domgroups_list = domgroups_hash.keys()
        domgroups_list.sort()

        if gr_list != domgroups_list:

            not_in_domgroups_list = []
            not_in_gr_list = []

            # Look for groups in gr_hash but not in domgroups_hash

            for group in gr_list:
                if not domgroups_hash.has_key(group):
                    not_in_domgroups_list.append(group)

            # Look for groups in domgroups_hash but not in gr_hash

            for group in domgroups_list:
                if not gr_hash.has_key(group):
                    not_in_gr_list.append(group)

            if len(not_in_domgroups_list) > 0:
                self.fail("%s not in domain groups" % not_in_domgroups_list)

            if len(not_in_gr_list) > 0:
                self.fail("%s not in getgrent groups" % not_in_gr_list)

            # Should never happen!

            self.fail("enum domain groups and grent output different")

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