File: commanding.py

package info (click to toggle)
pymol 3.1.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 74,084 kB
  • sloc: cpp: 482,660; python: 89,328; ansic: 29,512; javascript: 6,792; sh: 84; makefile: 25
file content (283 lines) | stat: -rw-r--r-- 7,737 bytes parent folder | download
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from __future__ import print_function

import sys
import pytest

import pymol
import __main__
from pymol import cmd, testing, stored

from typing import List




class TestCommanding(testing.PyMOLTestCase):

    def testAlias(self):
        stored.v = None
        cmd.alias('foo', '/stored.v = 123')
        cmd.do('_ foo', echo=0)
        self.assertEqual(stored.v, 123)

    @testing.requires('gui', 'no_run_all')
    def testCls(self):
        cmd.set('internal_prompt', 0)
        cmd.set('text', 1)
        cmd.cls()

        # check on black screen
        img = self.get_imagearray()
        self.assertFalse(img[...,:3].any())

    def testDelete(self):
        cmd.pseudoatom('m1')
        cmd.pseudoatom('m2')
        cmd.pseudoatom('m3')
        cmd.delete('m1 m2')
        self.assertEqual(cmd.get_names(), ['m3'])

    def testDeleteStates(self):
        cmd.pseudoatom('m1', state=10)
        self.assertEqual(cmd.count_states('m1'), 10)
        cmd.delete_states('m1', '4-8')
        self.assertEqual(cmd.count_states('m1'), 5)

    def testDo(self):
        # tested with other methods
        pass

    def testExtend(self):
        def check(v):
            stored.v = None
            cmd.do('foo', echo=0)
            self.assertEqual(stored.v, v)

        cmd.extend('foo', lambda: setattr(stored, 'v', 123))
        check(123)

        @cmd.extend
        def foo():
            stored.v = 456
        check(456)

    def testLog(self):
        with testing.mktemp('.pml') as logfile:
            cmd.log_open(logfile)
            cmd.do('_ color blue')
            cmd.log('hello world')
            cmd.log_close()
            lines = [_f for _f in map(str.strip, open(logfile)) if _f]
            self.assertEqual(lines, ['color blue', 'hello world'])

    @testing.requires_version('1.8.1.0')
    def testLog2(self):
        """
        Tests robustness of different logging methods:
        1) Python implementation (cmd.log) vs. C implementation (PLog, via cmd.do)
        2) pml vs. py syntax
        3) handling of quoted input (''' broken in 1.8.2)
        """
        self.ambientOnly()
        cmd.viewport(100, 100)
        cmd.fragment('gly')
        cmd.orient()
        cmd.show_as('spheres')

        for ext in ['.pml', '.py']:
            with testing.mktemp(ext) as logfile:
                cmd.log_open(logfile)
                cmd.do('_ color blue')
                cmd.do('/cmd.color("yellow", "elem O")')
                cmd.do('cmd.color("""green""",' " '''elem N''')")
                cmd.log('bg red\n')
                cmd.log('', 'cmd.color(\'magenta\', "hydro")\n')
                cmd.log_close()

                cmd.color('white')
                cmd.bg_color('white')

                if ext == '.pml':
                    cmd.do('@' + logfile)
                else:
                    cmd.do('run ' + logfile)

                img = self.get_imagearray()
                self.assertImageHasColor('blue', img)
                self.assertImageHasColor('yellow', img)
                self.assertImageHasColor('green', img)
                self.assertImageHasColor('red', img)
                self.assertImageHasColor('magenta', img)
                self.assertImageHasNotColor('white', img)

    def testLogClose(self):
        # see testLog
        pass

    def testLogOpen(self):
        # see testLog
        pass

    def testQuit(self):
        cmd.quit
        self.skipTest("cannot test quit")

    def testReinitialize(self):
        def check(v, names):
            self.assertEqual(v, cmd.get('pdb_conect_all'))
            self.assertEqual(cmd.get_names(), names)

        cmd.pseudoatom('m1')
        v = cmd.set('pdb_conect_all')
        cmd.reinitialize('store_defaults')

        cmd.reinitialize('original_settings')
        check('off', ['m1'])

        cmd.reinitialize('settings')
        check('on', ['m1'])

        cmd.reinitialize('purge_defaults')
        cmd.reinitialize('settings')
        check('off', ['m1'])

        cmd.reinitialize('everything')
        check('off', [])

    def testResume(self):
        with testing.mktemp('.pml') as logfile:
            with open(logfile, 'w') as f:
                print('bg yellow', file=f)
            cmd.resume(logfile)
            self.assertEqual('yellow', cmd.get('bg_rgb'))
            cmd.log('hello world')
            cmd.log_close()
            lines = [_f for _f in map(str.strip, open(logfile)) if _f]
            self.assertEqual(lines, ['bg yellow', 'hello world'])

    def testSplash(self):
        cmd.feedback('disable', 'all', 'output')
        cmd.splash()

    def testSync(self):
        cmd.sync()

    @testing.foreach(
        ('local', 'pymol', False),
        ('global', 'pymol', True),
        ('module', '', False),
        ('main', '__main__', True),
        ('private', '__main__', False),
    )
    def testRun(self, namespace, mod, rw):
        stored.tmp = False
        with testing.mktemp('.py') as filename:
            varname = '_tmp_' + namespace
            with open(filename, 'w') as handle:
                print('from pymol import stored', file=handle)
                if mod:
                    print('stored.tmp = (__name__ == "%s")' % (mod), file=handle)
                else:
                    print('stored.tmp = True', file=handle)
                print(varname + ' = True', file=handle)
            cmd.do('run %s, %s' % (filename, namespace), 0, 0)
            self.assertTrue(stored.tmp)
            if mod:
                self.assertEqual(rw, hasattr(sys.modules[mod], varname))

def test_declare_command_casting():
    from pathlib import Path

    @cmd.declare_command
    def func(a: int, b: Path):
        assert isinstance(a, int) and a == 1
        assert isinstance(b, (Path, str)) and "/tmp" == str(b)
    func(1, "/tmp")
    cmd.do('func 1, /tmp')


def test_declare_command_default(capsys):
    from pymol.commanding import Selection
    @cmd.declare_command
    def func(a: Selection = "sele"):
        assert a == "sele"
    func()
    cmd.do("func")
    out, err = capsys.readouterr()
    assert out == ''

def test_declare_command_docstring():
    @cmd.declare_command
    def func():
        """docstring"""
    assert func.__doc__ == "docstring"

    @cmd.declare_command
    def func():
        """
        docstring
        Test:
            --foo
        """
    assert func.__doc__ == "docstring\nTest:\n    --foo"


def test_declare_command_type_return(capsys):
    @cmd.declare_command
    def func() -> int:
        return 1

    assert func() == 1
    out, err = capsys.readouterr()
    assert out == ''

    @cmd.declare_command
    def func():
        return 1
    assert func() == 1

def test_declare_command_list_str(capsys):
    @cmd.declare_command
    def func(a: List[str]):
        print(a[-1])

    func(["a", "b", "c"])
    cmd.do('func a b c')
    out, err = capsys.readouterr()
    assert out == 'c\nc\n'

def test_declare_command_list_int(capsys):
    @cmd.declare_command
    def func(a: List[int]):
        print(a[-1] ** 2)
        return a[-1] ** 2

    assert func([1, 2, 3]) == 9
    cmd.do('func 1 2 3')
    out, err = capsys.readouterr()
    assert out == '9\n9\n'


def test_declare_command_list_float(capsys):
    @cmd.declare_command
    def func(a: List[float]):
        print(a[-1]**2)
        return a[-1]**2

    assert func([1.1, 2.0, 3.0]) == 9.0
    cmd.do('func 1 2 3')
    out, err = capsys.readouterr()
    assert out == '9.0\n9.0\n'


def test_declare_command_bool(capsys):
    @cmd.declare_command
    def func(a: bool, b: bool):
        assert a
        assert not b

    func(True, False)

    cmd.do("func yes, no")
    out, err = capsys.readouterr()
    assert out == '' and err == ''