-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
statements.py
1411 lines (1139 loc) · 46.8 KB
/
statements.py
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ast
import re
import warnings
from abc import ABC, abstractmethod
from collections.abc import Iterator, Sequence
from typing import cast, ClassVar, Literal, overload, TYPE_CHECKING, Type, TypeVar
from robot.conf import Language
from robot.running.arguments import UserKeywordArgumentParser
from robot.utils import normalize_whitespace, seq2str, split_from_equals, test_or_task
from robot.variables import (contains_variable, is_scalar_assign, is_dict_variable,
search_variable)
from ..lexer import Token
if TYPE_CHECKING:
from .blocks import ValidationContext
T = TypeVar('T', bound='Statement')
FOUR_SPACES = ' '
EOL = '\n'
class Node(ast.AST, ABC):
_attributes = ('lineno', 'col_offset', 'end_lineno', 'end_col_offset', 'errors')
lineno: int
col_offset: int
end_lineno: int
end_col_offset: int
errors: 'tuple[str, ...]' = ()
class Statement(Node, ABC):
_attributes = ('type', 'tokens') + Node._attributes
type: str
handles_types: 'ClassVar[tuple[str, ...]]' = ()
statement_handlers: 'ClassVar[dict[str, Type[Statement]]]' = {}
# Accepted configuration options. If the value is a tuple, it lists accepted
# values. If the used value contains a variable, it cannot be validated.
options: 'dict[str, tuple|None]' = {}
def __init__(self, tokens: 'Sequence[Token]', errors: 'Sequence[str]' = ()):
self.tokens = tuple(tokens)
self.errors = tuple(errors)
@property
def lineno(self) -> int:
return self.tokens[0].lineno if self.tokens else -1
@property
def col_offset(self) -> int:
return self.tokens[0].col_offset if self.tokens else -1
@property
def end_lineno(self) -> int:
return self.tokens[-1].lineno if self.tokens else -1
@property
def end_col_offset(self) -> int:
return self.tokens[-1].end_col_offset if self.tokens else -1
@classmethod
def register(cls, subcls: Type[T]) -> Type[T]:
types = subcls.handles_types or (subcls.type,)
for typ in types:
cls.statement_handlers[typ] = subcls
return subcls
@classmethod
def from_tokens(cls, tokens: 'Sequence[Token]') -> 'Statement':
"""Create a statement from given tokens.
Statement type is got automatically from token types.
This classmethod should be called from :class:`Statement`, not from
its subclasses. If you know the subclass to use, simply create an
instance of it directly.
"""
handlers = cls.statement_handlers
for token in tokens:
if token.type in handlers:
return handlers[token.type](tokens)
if any(token.type == Token.ASSIGN for token in tokens):
return KeywordCall(tokens)
return EmptyLine(tokens)
@classmethod
@abstractmethod
def from_params(cls, *args, **kwargs) -> 'Statement':
"""Create a statement from passed parameters.
Required and optional arguments in general match class properties.
Values are used to create matching tokens.
Most implementations support following general properties:
- ``separator`` whitespace inserted between each token. Default is four spaces.
- ``indent`` whitespace inserted before first token. Default is four spaces.
- ``eol`` end of line sign. Default is ``'\\n'``.
This classmethod should be called from the :class:`Statement` subclass
to create, not from the :class:`Statement` class itself.
"""
raise NotImplementedError
@property
def data_tokens(self) -> 'list[Token]':
return [t for t in self.tokens if t.type not in Token.NON_DATA_TOKENS]
def get_token(self, *types: str) -> 'Token|None':
"""Return a token with any of the given ``types``.
If there are no matches, return ``None``. If there are multiple
matches, return the first match.
"""
for token in self.tokens:
if token.type in types:
return token
return None
def get_tokens(self, *types: str) -> 'list[Token]':
"""Return tokens having any of the given ``types``."""
return [t for t in self.tokens if t.type in types]
@overload
def get_value(self, type: str, default: str) -> str:
...
@overload
def get_value(self, type: str, default: None = None) -> 'str|None':
...
def get_value(self, type: str, default: 'str|None' = None) -> 'str|None':
"""Return value of a token with the given ``type``.
If there are no matches, return ``default``. If there are multiple
matches, return the value of the first match.
"""
token = self.get_token(type)
return token.value if token else default
def get_values(self, *types: str) -> 'tuple[str, ...]':
"""Return values of tokens having any of the given ``types``."""
return tuple(t.value for t in self.tokens if t.type in types)
def get_option(self, name: str, default: 'str|None' = None) -> 'str|None':
"""Return value of a configuration option with the given ``name``.
If the option has not been used, return ``default``.
If the option has been used multiple times, values are joined together.
This is typically an error situation and validated elsewhere.
New in Robot Framework 6.1.
"""
return self._get_options().get(name, default)
def _get_options(self) -> 'dict[str, str]':
return dict(opt.split('=', 1) for opt in self.get_values(Token.OPTION))
@property
def lines(self) -> 'Iterator[list[Token]]':
line = []
for token in self.tokens:
line.append(token)
if token.type == Token.EOL:
yield line
line = []
if line:
yield line
def validate(self, ctx: 'ValidationContext'):
pass
def _validate_options(self):
for name, value in self._get_options().items():
if self.options[name] is not None:
expected = self.options[name]
if value.upper() not in expected and not contains_variable(value):
self.errors += (f"{self.type} option '{name}' does not accept "
f"value '{value}'. Valid values are "
f"{seq2str(expected)}.",)
def __iter__(self) -> 'Iterator[Token]':
return iter(self.tokens)
def __len__(self) -> int:
return len(self.tokens)
def __getitem__(self, item) -> Token:
return self.tokens[item]
def __repr__(self) -> str:
name = type(self).__name__
tokens = f'tokens={list(self.tokens)}'
errors = f', errors={list(self.errors)}' if self.errors else ''
return f'{name}({tokens}{errors})'
class DocumentationOrMetadata(Statement, ABC):
@property
def value(self) -> str:
return ''.join(self._get_lines()).rstrip()
def _get_lines(self) -> 'Iterator[str]':
base_offset = -1
for tokens in self._get_line_tokens():
yield from self._get_line_values(tokens, base_offset)
first = tokens[0]
if base_offset < 0 or 0 < first.col_offset < base_offset and first.value:
base_offset = first.col_offset
def _get_line_tokens(self) -> 'Iterator[list[Token]]':
line: 'list[Token]' = []
lineno = -1
# There are no EOLs during execution or if data has been parsed with
# `data_only=True` otherwise, so we need to look at line numbers to
# know when lines change. If model is created programmatically using
# `from_params` or otherwise, line numbers may not be set, but there
# ought to be EOLs. If both EOLs and line numbers are missing,
# everything is considered to be on the same line.
for token in self.get_tokens(Token.ARGUMENT, Token.EOL):
eol = token.type == Token.EOL
if token.lineno != lineno or eol:
if line:
yield line
line = []
if not eol:
line.append(token)
lineno = token.lineno
if line:
yield line
def _get_line_values(self, tokens: 'list[Token]', offset: int) -> 'Iterator[str]':
token = None
for index, token in enumerate(tokens):
if token.col_offset > offset > 0:
yield ' ' * (token.col_offset - offset)
elif index > 0:
yield ' '
yield self._remove_trailing_backslash(token.value)
offset = token.end_col_offset
if token and not self._has_trailing_backslash_or_newline(token.value):
yield '\n'
def _remove_trailing_backslash(self, value: str) -> str:
if value and value[-1] == '\\':
match = re.search(r'(\\+)$', value)
if match and len(match.group(1)) % 2 == 1:
value = value[:-1]
return value
def _has_trailing_backslash_or_newline(self, line: str) -> bool:
match = re.search(r'(\\+)n?$', line)
return bool(match and len(match.group(1)) % 2 == 1)
class SingleValue(Statement, ABC):
@property
def value(self) -> 'str|None':
values = self.get_values(Token.NAME, Token.ARGUMENT)
if values and values[0].upper() != 'NONE':
return values[0]
return None
class MultiValue(Statement, ABC):
@property
def values(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
class Fixture(Statement, ABC):
@property
def name(self) -> str:
return self.get_value(Token.NAME, '')
@property
def args(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
@Statement.register
class SectionHeader(Statement):
handles_types = (Token.SETTING_HEADER, Token.VARIABLE_HEADER,
Token.TESTCASE_HEADER, Token.TASK_HEADER,
Token.KEYWORD_HEADER, Token.COMMENT_HEADER,
Token.INVALID_HEADER)
@classmethod
def from_params(cls, type: str, name: 'str|None' = None,
eol: str = EOL) -> 'SectionHeader':
if not name:
names = ('Settings', 'Variables', 'Test Cases', 'Tasks',
'Keywords', 'Comments')
name = dict(zip(cls.handles_types, names))[type]
name = cast(str, name)
header = f'*** {name} ***' if not name.startswith('*') else name
return cls([
Token(type, header),
Token(Token.EOL, eol)
])
@property
def type(self) -> str:
token = self.get_token(*self.handles_types)
return token.type # type: ignore
@property
def name(self) -> str:
token = self.get_token(*self.handles_types)
return normalize_whitespace(token.value).strip('* ') if token else ''
@Statement.register
class LibraryImport(Statement):
type = Token.LIBRARY
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (), alias: 'str|None' = None,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'LibraryImport':
tokens = [Token(Token.LIBRARY, 'Library'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
if alias is not None:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.AS),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, alias)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def name(self) -> str:
return self.get_value(Token.NAME, '')
@property
def args(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
@property
def alias(self) -> 'str|None':
separator = self.get_token(Token.AS)
return self.get_tokens(Token.NAME)[-1].value if separator else None
@Statement.register
class ResourceImport(Statement):
type = Token.RESOURCE
@classmethod
def from_params(cls, name: str, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'ResourceImport':
return cls([
Token(Token.RESOURCE, 'Resource'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name),
Token(Token.EOL, eol)
])
@property
def name(self) -> str:
return self.get_value(Token.NAME, '')
@Statement.register
class VariablesImport(Statement):
type = Token.VARIABLES
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
separator: str = FOUR_SPACES, eol: str = EOL) -> 'VariablesImport':
tokens = [Token(Token.VARIABLES, 'Variables'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def name(self) -> str:
return self.get_value(Token.NAME, '')
@property
def args(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
@Statement.register
class Documentation(DocumentationOrMetadata):
type = Token.DOCUMENTATION
@classmethod
def from_params(cls, value: str, indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL,
settings_section: bool = True) -> 'Documentation':
if settings_section:
tokens = [Token(Token.DOCUMENTATION, 'Documentation'),
Token(Token.SEPARATOR, separator)]
else:
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.DOCUMENTATION, '[Documentation]'),
Token(Token.SEPARATOR, separator)]
multiline_separator = ' ' * (len(tokens[-2].value) + len(separator) - 3)
doc_lines = value.splitlines()
if doc_lines:
tokens.extend([Token(Token.ARGUMENT, doc_lines[0]),
Token(Token.EOL, eol)])
for line in doc_lines[1:]:
if not settings_section:
tokens.append(Token(Token.SEPARATOR, indent))
tokens.append(Token(Token.CONTINUATION))
if line:
tokens.append(Token(Token.SEPARATOR, multiline_separator))
tokens.extend([Token(Token.ARGUMENT, line),
Token(Token.EOL, eol)])
return cls(tokens)
@Statement.register
class Metadata(DocumentationOrMetadata):
type = Token.METADATA
@classmethod
def from_params(cls, name: str, value: str, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'Metadata':
tokens = [Token(Token.METADATA, 'Metadata'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
metadata_lines = value.splitlines()
if metadata_lines:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, metadata_lines[0]),
Token(Token.EOL, eol)])
for line in metadata_lines[1:]:
tokens.extend([Token(Token.CONTINUATION),
Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, line),
Token(Token.EOL, eol)])
return cls(tokens)
@property
def name(self) -> str:
return self.get_value(Token.NAME, '')
@Statement.register
class TestTags(MultiValue):
type = Token.TEST_TAGS
@classmethod
def from_params(cls, values: 'Sequence[str]', separator: str = FOUR_SPACES,
eol: str = EOL) -> 'TestTags':
tokens = [Token(Token.TEST_TAGS, 'Test Tags')]
for tag in values:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, tag)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class DefaultTags(MultiValue):
type = Token.DEFAULT_TAGS
@classmethod
def from_params(cls, values: 'Sequence[str]', separator: str = FOUR_SPACES,
eol: str = EOL) -> 'DefaultTags':
tokens = [Token(Token.DEFAULT_TAGS, 'Default Tags')]
for tag in values:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, tag)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class KeywordTags(MultiValue):
type = Token.KEYWORD_TAGS
@classmethod
def from_params(cls, values: 'Sequence[str]', separator: str = FOUR_SPACES,
eol: str = EOL) -> 'KeywordTags':
tokens = [Token(Token.KEYWORD_TAGS, 'Keyword Tags')]
for tag in values:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, tag)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class SuiteName(SingleValue):
type = Token.SUITE_NAME
@classmethod
def from_params(cls, value: str, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'SuiteName':
return cls([
Token(Token.SUITE_NAME, 'Name'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, value),
Token(Token.EOL, eol)
])
@Statement.register
class SuiteSetup(Fixture):
type = Token.SUITE_SETUP
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
separator: str = FOUR_SPACES, eol: str = EOL) -> 'SuiteSetup':
tokens = [Token(Token.SUITE_SETUP, 'Suite Setup'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class SuiteTeardown(Fixture):
type = Token.SUITE_TEARDOWN
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
separator: str = FOUR_SPACES, eol: str = EOL) -> 'SuiteTeardown':
tokens = [Token(Token.SUITE_TEARDOWN, 'Suite Teardown'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class TestSetup(Fixture):
type = Token.TEST_SETUP
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
separator: str = FOUR_SPACES, eol: str = EOL) -> 'TestSetup':
tokens = [Token(Token.TEST_SETUP, 'Test Setup'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class TestTeardown(Fixture):
type = Token.TEST_TEARDOWN
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
separator: str = FOUR_SPACES, eol: str = EOL) -> 'TestTeardown':
tokens = [Token(Token.TEST_TEARDOWN, 'Test Teardown'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class TestTemplate(SingleValue):
type = Token.TEST_TEMPLATE
@classmethod
def from_params(cls, value: str, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'TestTemplate':
return cls([
Token(Token.TEST_TEMPLATE, 'Test Template'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, value),
Token(Token.EOL, eol)
])
@Statement.register
class TestTimeout(SingleValue):
type = Token.TEST_TIMEOUT
@classmethod
def from_params(cls, value: str, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'TestTimeout':
return cls([
Token(Token.TEST_TIMEOUT, 'Test Timeout'),
Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, value),
Token(Token.EOL, eol)
])
@Statement.register
class Variable(Statement):
type = Token.VARIABLE
options = {
'separator': None
}
@classmethod
def from_params(cls, name: str,
value: 'str|Sequence[str]',
value_separator: 'str|None' = None,
separator: str = FOUR_SPACES,
eol: str = EOL) -> 'Variable':
values = [value] if isinstance(value, str) else value
tokens = [Token(Token.VARIABLE, name)]
for value in values:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, value)])
if value_separator is not None:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.OPTION, f'separator={value_separator}')])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def name(self) -> str:
name = self.get_value(Token.VARIABLE, '')
if name.endswith('='):
return name[:-1].rstrip()
return name
@property
def value(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
@property
def separator(self) -> 'str|None':
return self.get_option('separator')
def validate(self, ctx: 'ValidationContext'):
VariableValidator().validate(self)
self._validate_options()
@Statement.register
class TestCaseName(Statement):
type = Token.TESTCASE_NAME
@classmethod
def from_params(cls, name: str, eol: str = EOL) -> 'TestCaseName':
tokens = [Token(Token.TESTCASE_NAME, name)]
if eol:
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def name(self) -> str:
return self.get_value(Token.TESTCASE_NAME, '')
def validate(self, ctx: 'ValidationContext'):
if not self.name:
self.errors += (test_or_task('{Test} name cannot be empty.', ctx.tasks),)
@Statement.register
class KeywordName(Statement):
type = Token.KEYWORD_NAME
@classmethod
def from_params(cls, name: str, eol: str = EOL) -> 'KeywordName':
tokens = [Token(Token.KEYWORD_NAME, name)]
if eol:
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def name(self) -> str:
return self.get_value(Token.KEYWORD_NAME, '')
def validate(self, ctx: 'ValidationContext'):
if not self.name:
self.errors += ('User keyword name cannot be empty.',)
@Statement.register
class Setup(Fixture):
type = Token.SETUP
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
indent: str = FOUR_SPACES, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'Setup':
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.SETUP, '[Setup]'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class Teardown(Fixture):
type = Token.TEARDOWN
@classmethod
def from_params(cls, name: str, args: 'Sequence[str]' = (),
indent: str = FOUR_SPACES, separator: str = FOUR_SPACES,
eol: str = EOL) -> 'Teardown':
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.TEARDOWN, '[Teardown]'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, name)]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class Tags(MultiValue):
type = Token.TAGS
@classmethod
def from_params(cls, values: 'Sequence[str]', indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'Tags':
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.TAGS, '[Tags]')]
for tag in values:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, tag)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class Template(SingleValue):
type = Token.TEMPLATE
@classmethod
def from_params(cls, value: str, indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'Template':
return cls([
Token(Token.SEPARATOR, indent),
Token(Token.TEMPLATE, '[Template]'),
Token(Token.SEPARATOR, separator),
Token(Token.NAME, value),
Token(Token.EOL, eol)
])
@Statement.register
class Timeout(SingleValue):
type = Token.TIMEOUT
@classmethod
def from_params(cls, value: str, indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'Timeout':
return cls([
Token(Token.SEPARATOR, indent),
Token(Token.TIMEOUT, '[Timeout]'),
Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, value),
Token(Token.EOL, eol)
])
@Statement.register
class Arguments(MultiValue):
type = Token.ARGUMENTS
@classmethod
def from_params(cls, args: 'Sequence[str]', indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'Arguments':
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.ARGUMENTS, '[Arguments]')]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
def validate(self, ctx: 'ValidationContext'):
errors: 'list[str]' = []
UserKeywordArgumentParser(error_reporter=errors.append).parse(self.values)
self.errors = tuple(errors)
@Statement.register
class ReturnSetting(MultiValue):
"""Represents the deprecated ``[Return]`` setting.
This class was named ``Return`` prior to Robot Framework 7.0. A forward
compatible ``ReturnSetting`` alias existed already in Robot Framework 6.1.
"""
type = Token.RETURN
@classmethod
def from_params(cls, args: 'Sequence[str]', indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'ReturnSetting':
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.RETURN, '[Return]')]
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@Statement.register
class KeywordCall(Statement):
type = Token.KEYWORD
@classmethod
def from_params(cls, name: str, assign: 'Sequence[str]' = (),
args: 'Sequence[str]' = (), indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'KeywordCall':
tokens = [Token(Token.SEPARATOR, indent)]
for assignment in assign:
tokens.extend([Token(Token.ASSIGN, assignment),
Token(Token.SEPARATOR, separator)])
tokens.append(Token(Token.KEYWORD, name))
for arg in args:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def keyword(self) -> str:
return self.get_value(Token.KEYWORD, '')
@property
def args(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
@property
def assign(self) -> 'tuple[str, ...]':
return self.get_values(Token.ASSIGN)
@Statement.register
class TemplateArguments(Statement):
type = Token.ARGUMENT
@classmethod
def from_params(cls, args: 'Sequence[str]', indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'TemplateArguments':
tokens = []
for index, arg in enumerate(args):
tokens.extend([Token(Token.SEPARATOR, separator if index else indent),
Token(Token.ARGUMENT, arg)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def args(self) -> 'tuple[str, ...]':
return self.get_values(self.type)
@Statement.register
class ForHeader(Statement):
type = Token.FOR
options = {
'start': None,
'mode': ('STRICT', 'SHORTEST', 'LONGEST'),
'fill': None
}
@classmethod
def from_params(cls, assign: 'Sequence[str]',
values: 'Sequence[str]',
flavor: Literal['IN', 'IN RANGE', 'IN ENUMERATE', 'IN ZIP'] = 'IN',
indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES,
eol: str = EOL) -> 'ForHeader':
tokens = [Token(Token.SEPARATOR, indent),
Token(Token.FOR),
Token(Token.SEPARATOR, separator)]
for variable in assign:
tokens.extend([Token(Token.VARIABLE, variable),
Token(Token.SEPARATOR, separator)])
tokens.append(Token(Token.FOR_SEPARATOR, flavor))
for value in values:
tokens.extend([Token(Token.SEPARATOR, separator),
Token(Token.ARGUMENT, value)])
tokens.append(Token(Token.EOL, eol))
return cls(tokens)
@property
def assign(self) -> 'tuple[str, ...]':
return self.get_values(Token.VARIABLE)
@property
def variables(self) -> 'tuple[str, ...]': # TODO: Remove in RF 8.0.
warnings.warn("'ForHeader.variables' is deprecated and will be removed in "
"Robot Framework 8.0. Use 'ForHeader.assign' instead.")
return self.assign
@property
def values(self) -> 'tuple[str, ...]':
return self.get_values(Token.ARGUMENT)
@property
def flavor(self) -> 'str|None':
separator = self.get_token(Token.FOR_SEPARATOR)
return normalize_whitespace(separator.value) if separator else None
@property
def start(self) -> 'str|None':
return self.get_option('start') if self.flavor == 'IN ENUMERATE' else None
@property
def mode(self) -> 'str|None':
return self.get_option('mode') if self.flavor == 'IN ZIP' else None
@property
def fill(self) -> 'str|None':
return self.get_option('fill') if self.flavor == 'IN ZIP' else None
def validate(self, ctx: 'ValidationContext'):
if not self.assign:
self._add_error('no loop variables')
if not self.flavor:
self._add_error("no 'IN' or other valid separator")
else:
for var in self.assign:
if not is_scalar_assign(var):
self._add_error(f"invalid loop variable '{var}'")
if not self.values:
self._add_error('no loop values')
self._validate_options()
def _add_error(self, error: str):
self.errors += (f'FOR loop has {error}.',)
class IfElseHeader(Statement, ABC):
@property
def condition(self) -> 'str|None':
values = self.get_values(Token.ARGUMENT)
return ', '.join(values) if values else None
@property
def assign(self) -> 'tuple[str, ...]':
return self.get_values(Token.ASSIGN)
def validate(self, ctx: 'ValidationContext'):
conditions = self.get_tokens(Token.ARGUMENT)
if not conditions:
self.errors += (f'{self.type} must have a condition.',)
if len(conditions) > 1:
self.errors += (f'{self.type} cannot have more than one condition, '
f'got {seq2str(c.value for c in conditions)}.',)
@Statement.register
class IfHeader(IfElseHeader):
type = Token.IF
@classmethod
def from_params(cls, condition: str, indent: str = FOUR_SPACES,
separator: str = FOUR_SPACES, eol: str = EOL) -> 'IfHeader':
return cls([
Token(Token.SEPARATOR, indent),
Token(cls.type),
Token(Token.SEPARATOR, separator),