更好的assertEqual()用于os.stat(myfile).st_mode [英] Better assertEqual() for os.stat(myfile).st_mode

查看:90
本文介绍了更好的assertEqual()用于os.stat(myfile).st_mode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个检查文件st_mode的代码:

I have a code that checks the st_mode of a file:

self.assertEqual(16877, os.stat(my_directory).st_mode)

只有老式的unix专家才能流畅地解密 16877 的整数值.

Only old school unix experts are able to decipher the integer value 16877 fluently.

是否有更可读的方法来检查此值?

Is there more readable way to check for exactly this value?

推荐答案

如果我可以稍微扩展一下问题并将其理解为是否有更可读的方法来检查文件模式?",那么我建议添加一个自定义断言.目标:

If I may extend the question a bit and understand it as "Is there more readable way to check file modes?", then I'll suggest adding a custom assertion. The target:

self.assertFileMode(my_directory, user="rwx", group="rx", others="rx")

操作方法.

让我们把这个断言放在一个mixin中:

Let's put that assertion in a mixin:

import os
import stat

class FileAssertions(object):
    FILE_PERMS = {
        'user': {'r': stat.S_IRUSR, 'w': stat.S_IWUSR, 'x': stat.S_IXUSR, 's': stat.S_ISUID},
        'group': {'r': stat.S_IRGRP, 'w': stat.S_IWGRP, 'x': stat.S_IXGRP, 's': stat.S_ISGID},
        'others': {'r': stat.S_IROTH, 'w': stat.S_IWOTH, 'x': stat.S_IXOTH},
    }

    def assertFileMode(self, path, **kwargs):
        mode = os.stat(path).st_mode
        for key, perm_defs in self.FILE_PERMS.items():
            expected = kwargs.pop(key, None)
            if expected is not None:
                actual_perms = mode & sum(perm_defs.values())
                expected_perms = sum(perm_defs[flag] for flag in expected)

                if actual_perms != expected_perms:
                    msg = '{key} permissions: {expected} != {actual} for {path}'.format(
                        key=key, path=path,
                        expected=''.join(sorted(expected)),
                        actual=''.join(sorted(flag for flag, value in perm_defs.items()
                                              if value & mode != 0))
                    )
                    raise self.failureException(msg)
        if kwargs:
            raise TypeError('assertFileMode: unknown arguments %s' % ', '.join(kwargs))

使用

现在,我们如何测试某些文件模式?

Now, how about we test some file modes?

# We use our mixin
class MyTestCase(FileAssertions, TestCase):
    def test_some_paths(self):
        # Test all permissions
        self.assertFileMode('/foo/bar', user='rwx', group='rx', others='')

        # Only test user permissions
        self.assertFileMode('/foo/bar', user='rwx')

        # We support the suid/sgid bits as well
        self.assertFileMode('/foo/bar', user='rwxs', group='rxs', others='rx')

示例输出:

AssertionError: user permissions: rw != rwx for /foo/bar

注释:

  • 仅测试授予该方法的权限.要测试不存在任何权限,请传递一个空字符串.
  • 大多数复杂性来自生成用户友好的消息.
  • 权限在错误消息中按字母顺序排序,因此比较容易察觉.
  • 为简单起见,我没有测试粘滞位.
  • li>

这篇关于更好的assertEqual()用于os.stat(myfile).st_mode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆