Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

# -*- encoding: utf-8 -*- 

""" 

Parsing docstrings 

 

This module contains functions and classes that parse docstrings. 

 

AUTHORS: 

 

- David Roe (2012-03-27) -- initial version, based on Robert Bradshaw's code. 

 

- Jeroen Demeyer(2014-08-28) -- much improved handling of tolerances 

using interval arithmetic (:trac:`16889`). 

""" 

 

#***************************************************************************** 

# Copyright (C) 2012 David Roe <roed.math@gmail.com> 

# Robert Bradshaw <robertwb@gmail.com> 

# William Stein <wstein@gmail.com> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# as published by the Free Software Foundation; either version 2 of 

# the License, or (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import print_function, absolute_import 

from sage.misc.six import u 

import six 

from six import text_type 

 

import re 

import sys 

import doctest 

import collections 

from sage.repl.preparse import preparse, strip_string_literals 

from Cython.Build.Dependencies import strip_string_literals as cython_strip_string_literals 

from functools import reduce 

 

 

from .external import available_software 

 

float_regex = re.compile('\s*([+-]?\s*((\d*\.?\d+)|(\d+\.?))([eE][+-]?\d+)?)') 

optional_regex = re.compile(r'(py2|py3|long time|not implemented|not tested|known bug)|([^ a-z]\s*optional\s*[:-]*((\s|\w)*))') 

find_sage_prompt = re.compile(r"^(\s*)sage: ", re.M) 

find_sage_continuation = re.compile(r"^(\s*)\.\.\.\.:", re.M) 

random_marker = re.compile('.*random', re.I) 

tolerance_pattern = re.compile(r'\b((?:abs(?:olute)?)|(?:rel(?:ative)?))? *?tol(?:erance)?\b( +[0-9.e+-]+)?') 

backslash_replacer = re.compile(r"""(\s*)sage:(.*)\\\ * 

\ *(((\.){4}:)|((\.){3}))?\ *""") 

 

# Use this real interval field for doctest tolerances. It allows large 

# numbers like 1e1000, it parses strings with spaces like RIF(" - 1 ") 

# out of the box and it is slightly more precise than Python's 53 bits. 

# The interval approach also means that we do not need to worry about 

# rounding errors and it is also very natural to see a number with 

# tolerance as an interval. 

# We need to import from sage.all to avoid circular imports. 

from sage.all import RealIntervalField 

RIFtol = RealIntervalField(64) 

 

 

# This is the correct pattern to match ISO/IEC 6429 ANSI escape sequences: 

# 

ansi_escape_sequence = re.compile(r'(\x1b[@-Z\\-~]|\x1b\[.*?[@-~]|\x9b.*?[@-~])') 

 

 

def remove_unicode_u(string): 

""" 

Given a string, try to remove all unicode u prefixes inside. 

 

This will help to keep the same doctest results in Python2 and Python3. 

The input string is typically the documentation of a method or function. 

This string may contain some letters u that are unicode python2 prefixes. 

The aim is to remove all of these u and only them. 

 

INPUT: 

 

- ``string`` -- either ``unicode`` or ``bytes`` (if ``bytes``, it 

will be converted to ``unicode`` assuming UTF-8) 

 

OUTPUT: ``unicode`` string 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import remove_unicode_u as remu 

sage: remu("u'you'") 

u"'you'" 

sage: remu('u') 

u'u' 

sage: remu("[u'am', 'stram', u'gram']") 

u"['am', 'stram', 'gram']" 

sage: remu('[u"am", "stram", u"gram"]') 

u'["am", "stram", "gram"]' 

 

This deals correctly with nested quotes:: 

 

sage: str = '''[u"Singular's stuff", u'good']''' 

sage: print(remu(str)) 

["Singular's stuff", 'good'] 

 

TESTS: 

 

This supports python2 str type as input:: 

 

sage: euro = "'€'" 

sage: print(remu(euro)) 

'€' 

""" 

stripped, replacements = cython_strip_string_literals(u(string), 

"__remove_unicode_u") 

string = stripped.replace('u"', '"').replace("u'", "'") 

for magic, literal in replacements.items(): 

string = string.replace(magic, literal) 

return string 

 

 

_type_repr_re = re.compile(r"<type '(?P<name>[^']+)'>") 

 

def normalize_type_repr(s): 

r""" 

Convert the repr of type objects (e.g. ``int``, ``float``) from their 

Python 2 representation to their Python 3 representation. 

 

In Python 2, the repr of built-in types like ``int`` is like 

``<type 'int'>``, whereas user-defined pure Python classes are displayed 

as ``<class 'classname'>``. On Python 3 this was normalized so that 

built-in types are represented the same as user-defined classes (e.g. 

``<class 'int'>``. 

 

This simply normalizes all class/type reprs to the Python 3 convention for 

the sake of output checking. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import normalize_type_repr 

sage: s = "<type 'int'>" 

sage: normalize_type_repr(s) 

"<class 'int'>" 

sage: normalize_type_repr(repr(float)) 

"<class 'float'>" 

 

This can work on multi-line output as well:: 

 

sage: s = "The desired output was <class 'int'>\n" 

sage: s += "The received output was <type 'int'>" 

sage: print(normalize_type_repr(s)) 

The desired output was <class 'int'> 

The received output was <class 'int'> 

 

And should work when types are embedded in other nested expressions:: 

 

sage: normalize_type_repr(repr([Integer, float])) 

"[<class 'sage.rings.integer.Integer'>, <class 'float'>]" 

""" 

 

def subst(m): 

return "<class '{0}'>".format(m.group('name')) 

 

return _type_repr_re.sub(subst, s) 

 

 

def parse_optional_tags(string): 

""" 

Returns a set consisting of the optional tags from the following 

set that occur in a comment on the first line of the input string. 

 

- 'long time' 

- 'not implemented' 

- 'not tested' 

- 'known bug' 

- 'py2' 

- 'py3' 

- 'optional: PKG_NAME' -- the set will just contain 'PKG_NAME' 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import parse_optional_tags 

sage: parse_optional_tags("sage: magma('2 + 2')# optional: magma") 

{'magma'} 

sage: parse_optional_tags("sage: #optional -- mypkg") 

{'mypkg'} 

sage: parse_optional_tags("sage: print(1) # parentheses are optional here") 

set() 

sage: parse_optional_tags("sage: print(1) # optional") 

{''} 

sage: sorted(list(parse_optional_tags("sage: #optional -- foo bar, baz"))) 

['bar', 'foo'] 

sage: sorted(list(parse_optional_tags(" sage: factor(10^(10^10) + 1) # LoNg TiME, NoT TeSTED; OptioNAL -- P4cka9e"))) 

['long time', 'not tested', 'p4cka9e'] 

sage: parse_optional_tags(" sage: raise RuntimeError # known bug") 

{'bug'} 

sage: sorted(list(parse_optional_tags(" sage: determine_meaning_of_life() # long time, not implemented"))) 

['long time', 'not implemented'] 

 

We don't parse inside strings:: 

 

sage: parse_optional_tags(" sage: print(' # long time')") 

set() 

sage: parse_optional_tags(" sage: print(' # long time') # not tested") 

{'not tested'} 

 

UTF-8 works:: 

 

sage: parse_optional_tags("'ěščřžýáíéďĎ'") 

set() 

""" 

safe, literals, state = strip_string_literals(string) 

first_line = safe.split('\n', 1)[0] 

if '#' not in first_line: 

return set() 

comment = first_line[first_line.find('#')+1:] 

comment = comment[comment.index('(')+1 : comment.rindex(')')] 

# strip_string_literals replaces comments 

comment = "#" + (literals[comment]).lower() 

 

tags = [] 

for m in optional_regex.finditer(comment): 

cmd = m.group(1) 

if cmd == 'known bug': 

tags.append('bug') # so that such tests will be run by sage -t ... -only-optional=bug 

elif cmd: 

tags.append(cmd) 

else: 

tags.extend(m.group(3).split() or [""]) 

return set(tags) 

 

def parse_tolerance(source, want): 

""" 

Returns a version of ``want`` marked up with the tolerance tags 

specified in ``source``. 

 

INPUT: 

 

- ``source`` -- a string, the source of a doctest 

- ``want`` -- a string, the desired output of the doctest 

 

OUTPUT: 

 

- ``want`` if there are no tolerance tags specified; a 

:class:`MarkedOutput` version otherwise. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import parse_tolerance 

sage: marked = parse_tolerance("sage: s.update(abs_tol = .0000001)", "") 

sage: type(marked) 

<... 'str'> 

sage: marked = parse_tolerance("sage: s.update(tol = 0.1); s.rel_tol # abs tol 0.01 ", "") 

sage: marked.tol 

0 

sage: marked.rel_tol 

0 

sage: marked.abs_tol 

0.010000000000000000000? 

""" 

safe, literals, state = strip_string_literals(source) 

first_line = safe.split('\n', 1)[0] 

if '#' not in first_line: 

return want 

comment = first_line[first_line.find('#')+1:] 

comment = comment[comment.index('(')+1 : comment.rindex(')')] 

# strip_string_literals replaces comments 

comment = literals[comment] 

if random_marker.search(comment): 

want = MarkedOutput(want).update(random=True) 

else: 

m = tolerance_pattern.search(comment) 

if m: 

rel_or_abs, epsilon = m.groups() 

if epsilon is None: 

epsilon = RIFtol("1e-15") 

else: 

epsilon = RIFtol(epsilon) 

if rel_or_abs is None: 

want = MarkedOutput(want).update(tol=epsilon) 

elif rel_or_abs.startswith('rel'): 

want = MarkedOutput(want).update(rel_tol=epsilon) 

elif rel_or_abs.startswith('abs'): 

want = MarkedOutput(want).update(abs_tol=epsilon) 

else: 

raise RuntimeError 

return want 

 

def pre_hash(s): 

""" 

Prepends a string with its length. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import pre_hash 

sage: pre_hash("abc") 

'3:abc' 

""" 

return "%s:%s" % (len(s), s) 

 

def get_source(example): 

""" 

Returns the source with the leading 'sage: ' stripped off. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import get_source 

sage: from sage.doctest.sources import DictAsObject 

sage: example = DictAsObject({}) 

sage: example.sage_source = "2 + 2" 

sage: example.source = "sage: 2 + 2" 

sage: get_source(example) 

'2 + 2' 

sage: example = DictAsObject({}) 

sage: example.source = "3 + 3" 

sage: get_source(example) 

'3 + 3' 

""" 

return getattr(example, 'sage_source', example.source) 

 

def reduce_hex(fingerprints): 

""" 

Return a symmetric function of the arguments as hex strings. 

 

The arguments should be 32 character strings consisting of hex 

digits: 0-9 and a-f. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import reduce_hex 

sage: reduce_hex(["abc", "12399aedf"]) 

'0000000000000000000000012399a463' 

sage: reduce_hex(["12399aedf","abc"]) 

'0000000000000000000000012399a463' 

""" 

from operator import xor 

res = reduce(xor, (int(x, 16) for x in fingerprints), 0) 

if res < 0: 

res += 1 << 128 

return "%032x" % res 

 

 

class MarkedOutput(text_type): 

""" 

A subclass of string with context for whether another string 

matches it. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import MarkedOutput 

sage: s = MarkedOutput("abc") 

sage: s.rel_tol 

0 

sage: s.update(rel_tol = .05) 

u'abc' 

sage: s.rel_tol 

0.0500000000000000 

 

sage: MarkedOutput(u"56 µs") 

u'56 \xb5s' 

""" 

random = False 

rel_tol = 0 

abs_tol = 0 

tol = 0 

def update(self, **kwds): 

""" 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import MarkedOutput 

sage: s = MarkedOutput("0.0007401") 

sage: s.update(abs_tol = .0000001) 

u'0.0007401' 

sage: s.rel_tol 

0 

sage: s.abs_tol 

1.00000000000000e-7 

""" 

self.__dict__.update(kwds) 

return self 

 

def __reduce__(self): 

""" 

Pickling. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import MarkedOutput 

sage: s = MarkedOutput("0.0007401") 

sage: s.update(abs_tol = .0000001) 

u'0.0007401' 

sage: t = loads(dumps(s)) # indirect doctest 

sage: t == s 

True 

sage: t.abs_tol 

1.00000000000000e-7 

""" 

return make_marked_output, (str(self), self.__dict__) 

 

 

def make_marked_output(s, D): 

""" 

Auxilliary function for pickling. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import make_marked_output 

sage: s = make_marked_output("0.0007401", {'abs_tol':.0000001}) 

sage: s 

u'0.0007401' 

sage: s.abs_tol 

1.00000000000000e-7 

""" 

ans = MarkedOutput(s) 

ans.__dict__.update(D) 

return ans 

 

 

class OriginalSource(object): 

r""" 

Context swapping out the pre-parsed source with the original for 

better reporting. 

 

EXAMPLES:: 

 

sage: from sage.doctest.sources import FileDocTestSource 

sage: from sage.doctest.control import DocTestDefaults 

sage: from sage.env import SAGE_SRC 

sage: import os 

sage: filename = os.path.join(SAGE_SRC,'sage','doctest','forker.py') 

sage: FDS = FileDocTestSource(filename,DocTestDefaults()) 

sage: doctests, extras = FDS.create_doctests(globals()) 

sage: ex = doctests[0].examples[0] 

sage: ex.sage_source 

u'doctest_var = 42; doctest_var^2\n' 

sage: ex.source 

u'doctest_var = Integer(42); doctest_var**Integer(2)\n' 

sage: from sage.doctest.parsing import OriginalSource 

sage: with OriginalSource(ex): 

....: ex.source 

u'doctest_var = 42; doctest_var^2\n' 

""" 

def __init__(self, example): 

""" 

Swaps out the source for the sage_source of a doctest example. 

 

INPUT: 

 

- ``example`` -- a :class:`doctest.Example` instance 

 

EXAMPLES:: 

 

sage: from sage.doctest.sources import FileDocTestSource 

sage: from sage.doctest.control import DocTestDefaults 

sage: from sage.env import SAGE_SRC 

sage: import os 

sage: filename = os.path.join(SAGE_SRC,'sage','doctest','forker.py') 

sage: FDS = FileDocTestSource(filename,DocTestDefaults()) 

sage: doctests, extras = FDS.create_doctests(globals()) 

sage: ex = doctests[0].examples[0] 

sage: from sage.doctest.parsing import OriginalSource 

sage: OriginalSource(ex) 

<sage.doctest.parsing.OriginalSource object at ...> 

""" 

self.example = example 

 

def __enter__(self): 

r""" 

EXAMPLES:: 

 

sage: from sage.doctest.sources import FileDocTestSource 

sage: from sage.doctest.control import DocTestDefaults 

sage: from sage.env import SAGE_SRC 

sage: import os 

sage: filename = os.path.join(SAGE_SRC,'sage','doctest','forker.py') 

sage: FDS = FileDocTestSource(filename,DocTestDefaults()) 

sage: doctests, extras = FDS.create_doctests(globals()) 

sage: ex = doctests[0].examples[0] 

sage: from sage.doctest.parsing import OriginalSource 

sage: with OriginalSource(ex): # indirect doctest 

....: ex.source 

... 

u'doctest_var = 42; doctest_var^2\n' 

""" 

if hasattr(self.example, 'sage_source'): 

self.old_source, self.example.source = self.example.source, self.example.sage_source 

 

def __exit__(self, *args): 

r""" 

EXAMPLES:: 

 

sage: from sage.doctest.sources import FileDocTestSource 

sage: from sage.doctest.control import DocTestDefaults 

sage: from sage.env import SAGE_SRC 

sage: import os 

sage: filename = os.path.join(SAGE_SRC,'sage','doctest','forker.py') 

sage: FDS = FileDocTestSource(filename,DocTestDefaults()) 

sage: doctests, extras = FDS.create_doctests(globals()) 

sage: ex = doctests[0].examples[0] 

sage: from sage.doctest.parsing import OriginalSource 

sage: with OriginalSource(ex): # indirect doctest 

....: ex.source 

... 

u'doctest_var = 42; doctest_var^2\n' 

sage: ex.source # indirect doctest 

u'doctest_var = Integer(42); doctest_var**Integer(2)\n' 

""" 

if hasattr(self.example, 'sage_source'): 

self.example.source = self.old_source 

 

 

class SageDocTestParser(doctest.DocTestParser): 

""" 

A version of the standard doctest parser which handles Sage's 

custom options and tolerances in floating point arithmetic. 

""" 

def __init__(self, long=False, optional_tags=()): 

r""" 

INPUT: 

 

- ``long`` -- boolean, whether to run doctests marked as taking a long time. 

- ``optional_tags`` -- a list or tuple of strings. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import SageDocTestParser 

sage: DTP = SageDocTestParser(True, ('sage','magma','guava')) 

sage: ex = DTP.parse("sage: 2 + 2\n")[1] 

sage: ex.sage_source 

'2 + 2\n' 

sage: ex = DTP.parse("sage: R.<x> = ZZ[]")[1] 

sage: ex.source 

"R = ZZ['x']; (x,) = R._first_ngens(1)\n" 

 

TESTS:: 

 

sage: TestSuite(DTP).run() 

""" 

self.long = long 

self.optionals = collections.defaultdict(int) # record skipped optional tests 

if optional_tags is True: # run all optional tests 

self.optional_tags = True 

self.optional_only = False 

else: 

self.optional_tags = set(optional_tags) 

if 'sage' in self.optional_tags: 

self.optional_only = False 

self.optional_tags.remove('sage') 

else: 

self.optional_only = True 

 

def __eq__(self, other): 

""" 

Comparison. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import SageDocTestParser 

sage: DTP = SageDocTestParser(True, ('sage','magma','guava')) 

sage: DTP2 = SageDocTestParser(False, ('sage','magma','guava')) 

sage: DTP == DTP2 

False 

""" 

if not isinstance(other, SageDocTestParser): 

return False 

return self.__dict__ == other.__dict__ 

 

def __ne__(self, other): 

""" 

Test for unequality. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import SageDocTestParser 

sage: DTP = SageDocTestParser(True, ('sage','magma','guava')) 

sage: DTP2 = SageDocTestParser(False, ('sage','magma','guava')) 

sage: DTP != DTP2 

True 

""" 

return not (self == other) 

 

def parse(self, string, *args): 

r""" 

A Sage specialization of :class:`doctest.DocTestParser`. 

 

INPUT: 

 

- ``string`` -- the string to parse. 

- ``name`` -- optional string giving the name identifying string, 

to be used in error messages. 

 

OUTPUT: 

 

- A list consisting of strings and :class:`doctest.Example` 

instances. There will be at least one string between 

successive examples (exactly one unless or long or optional 

tests are removed), and it will begin and end with a string. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import SageDocTestParser 

sage: DTP = SageDocTestParser(True, ('sage','magma','guava')) 

sage: example = 'Explanatory text::\n\n sage: E = magma("EllipticCurve([1, 1, 1, -10, -10])") # optional: magma\n\nLater text' 

sage: parsed = DTP.parse(example) 

sage: parsed[0] 

'Explanatory text::\n\n' 

sage: parsed[1].sage_source 

'E = magma("EllipticCurve([1, 1, 1, -10, -10])") # optional: magma\n' 

sage: parsed[2] 

'\nLater text' 

 

If the doctest parser is not created to accept a given 

optional argument, the corresponding examples will just be 

removed:: 

 

sage: DTP2 = SageDocTestParser(True, ('sage',)) 

sage: parsed2 = DTP2.parse(example) 

sage: parsed2 

['Explanatory text::\n\n', '\nLater text'] 

 

You can mark doctests as having a particular tolerance:: 

 

sage: example2 = 'sage: gamma(1.6) # tol 2.0e-11\n0.893515349287690' 

sage: ex = DTP.parse(example2)[1] 

sage: ex.sage_source 

'gamma(1.6) # tol 2.0e-11\n' 

sage: ex.want 

u'0.893515349287690\n' 

sage: type(ex.want) 

<class 'sage.doctest.parsing.MarkedOutput'> 

sage: ex.want.tol 

2.000000000000000000?e-11 

 

You can use continuation lines:: 

 

sage: s = "sage: for i in range(4):\n....: print(i)\n....:\n" 

sage: ex = DTP2.parse(s)[1] 

sage: ex.source 

'for i in range(Integer(4)):\n print(i)\n' 

 

Sage currently accepts backslashes as indicating that the end 

of the current line should be joined to the next line. This 

feature allows for breaking large integers over multiple lines 

but is not standard for Python doctesting. It's not 

guaranteed to persist, but works in Sage 5.5:: 

 

sage: n = 1234\ 

....: 5678 

sage: print(n) 

12345678 

sage: type(n) 

<type 'sage.rings.integer.Integer'> 

 

It also works without the line continuation:: 

 

sage: m = 8765\ 

4321 

sage: print(m) 

87654321 

""" 

# Hack for non-standard backslash line escapes accepted by the current 

# doctest system. 

m = backslash_replacer.search(string) 

while m is not None: 

next_prompt = find_sage_prompt.search(string,m.end()) 

g = m.groups() 

if next_prompt: 

future = string[m.end():next_prompt.start()] + '\n' + string[next_prompt.start():] 

else: 

future = string[m.end():] 

string = string[:m.start()] + g[0] + "sage:" + g[1] + future 

m = backslash_replacer.search(string,m.start()) 

 

string = find_sage_prompt.sub(r"\1>>> sage: ", string) 

string = find_sage_continuation.sub(r"\1...", string) 

res = doctest.DocTestParser.parse(self, string, *args) 

filtered = [] 

for item in res: 

if isinstance(item, doctest.Example): 

optional_tags = parse_optional_tags(item.source) 

if optional_tags: 

for tag in optional_tags: 

self.optionals[tag] += 1 

if (('not implemented' in optional_tags) or 

('not tested' in optional_tags)): 

continue 

 

if 'long time' in optional_tags: 

if self.long: 

optional_tags.remove('long time') 

else: 

continue 

 

if self.optional_tags is not True: 

extra = optional_tags - self.optional_tags # set difference 

if extra: 

if not('external' in self.optional_tags 

and available_software.issuperset(extra)): 

continue 

elif self.optional_only: 

self.optionals['sage'] += 1 

continue 

item.want = parse_tolerance(item.source, item.want) 

if item.source.startswith("sage: "): 

item.sage_source = item.source[6:] 

if item.sage_source.lstrip().startswith('#'): 

continue 

item.source = preparse(item.sage_source) 

filtered.append(item) 

return filtered 

 

class SageOutputChecker(doctest.OutputChecker): 

r""" 

A modification of the doctest OutputChecker that can check 

relative and absolute tolerance of answers. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import SageOutputChecker, MarkedOutput, SageDocTestParser 

sage: import doctest 

sage: optflag = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS 

sage: DTP = SageDocTestParser(True, ('sage','magma','guava')) 

sage: OC = SageOutputChecker() 

sage: example2 = 'sage: gamma(1.6) # tol 2.0e-11\n0.893515349287690' 

sage: ex = DTP.parse(example2)[1] 

sage: ex.sage_source 

'gamma(1.6) # tol 2.0e-11\n' 

sage: ex.want 

u'0.893515349287690\n' 

sage: type(ex.want) 

<class 'sage.doctest.parsing.MarkedOutput'> 

sage: ex.want.tol 

2.000000000000000000?e-11 

sage: OC.check_output(ex.want, '0.893515349287690', optflag) 

True 

sage: OC.check_output(ex.want, '0.8935153492877', optflag) 

True 

sage: OC.check_output(ex.want, '0', optflag) 

False 

sage: OC.check_output(ex.want, 'x + 0.8935153492877', optflag) 

False 

""" 

def human_readable_escape_sequences(self, string): 

r""" 

Make ANSI escape sequences human readable. 

 

EXAMPLES:: 

 

sage: print('This is \x1b[1mbold\x1b[0m text') 

This is <CSI-1m>bold<CSI-0m> text 

 

TESTS:: 

 

sage: from sage.doctest.parsing import SageOutputChecker 

sage: OC = SageOutputChecker() 

sage: teststr = '-'.join([ 

....: 'bold\x1b[1m', 

....: 'red\x1b[31m', 

....: 'oscmd\x1ba']) 

sage: OC.human_readable_escape_sequences(teststr) 

u'bold<CSI-1m>-red<CSI-31m>-oscmd<ESC-a>' 

""" 

def human_readable(match): 

ansi_escape = match.group(1) 

assert len(ansi_escape) >= 2 

if len(ansi_escape) == 2: 

return u'<ESC-'+ansi_escape[1]+u'>' 

else: 

return u'<CSI-'+ansi_escape.lstrip(u'\x1b[\x9b')+u'>' 

return ansi_escape_sequence.subn(human_readable, string)[0] 

 

def add_tolerance(self, wantval, want): 

""" 

Enlarge the real interval element ``wantval`` according to 

the tolerance options in ``want``. 

 

INPUT: 

 

- ``wantval`` -- a real interval element 

- ``want`` -- a :class:`MarkedOutput` describing the tolerance 

 

OUTPUT: 

 

- an interval element containing ``wantval`` 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import MarkedOutput, SageOutputChecker 

sage: OC = SageOutputChecker() 

sage: want_tol = MarkedOutput().update(tol=0.0001) 

sage: want_abs = MarkedOutput().update(abs_tol=0.0001) 

sage: want_rel = MarkedOutput().update(rel_tol=0.0001) 

sage: OC.add_tolerance(pi.n(64), want_tol).endpoints() 

(3.14127849432443, 3.14190681285516) 

sage: OC.add_tolerance(pi.n(64), want_abs).endpoints() 

(3.14149265358979, 3.14169265358980) 

sage: OC.add_tolerance(pi.n(64), want_rel).endpoints() 

(3.14127849432443, 3.14190681285516) 

sage: OC.add_tolerance(1e1000, want_tol) 

1.000?e1000 

sage: OC.add_tolerance(1e1000, want_abs) 

1.000000000000000?e1000 

sage: OC.add_tolerance(1e1000, want_rel) 

1.000?e1000 

sage: OC.add_tolerance(0, want_tol) 

0.000? 

sage: OC.add_tolerance(0, want_abs) 

0.000? 

sage: OC.add_tolerance(0, want_rel) 

0 

""" 

if want.tol: 

if wantval == 0: 

return want.tol * RIFtol(-1,1) 

else: 

return wantval * (1 + want.tol * RIFtol(-1,1)) 

elif want.abs_tol: 

return wantval + want.abs_tol * RIFtol(-1,1) 

elif want.rel_tol: 

return wantval * (1 + want.rel_tol * RIFtol(-1,1)) 

else: 

return wantval 

 

def check_output(self, want, got, optionflags): 

""" 

Checks to see if the output matches the desired output. 

 

If ``want`` is a :class:`MarkedOutput` instance, takes into account the desired tolerance. 

 

INPUT: 

 

- ``want`` -- a string or :class:`MarkedOutput` 

- ``got`` -- a string 

- ``optionflags`` -- an integer, passed down to :class:`doctest.OutputChecker` 

 

OUTPUT: 

 

- boolean, whether ``got`` matches ``want`` up to the specified tolerance. 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import MarkedOutput, SageOutputChecker 

sage: import doctest 

sage: optflag = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS 

sage: rndstr = MarkedOutput("I'm wrong!").update(random=True) 

sage: tentol = MarkedOutput("10.0").update(tol=.1) 

sage: tenabs = MarkedOutput("10.0").update(abs_tol=.1) 

sage: tenrel = MarkedOutput("10.0").update(rel_tol=.1) 

sage: zerotol = MarkedOutput("0.0").update(tol=.1) 

sage: zeroabs = MarkedOutput("0.0").update(abs_tol=.1) 

sage: zerorel = MarkedOutput("0.0").update(rel_tol=.1) 

sage: zero = "0.0" 

sage: nf = "9.5" 

sage: ten = "10.05" 

sage: eps = "-0.05" 

sage: OC = SageOutputChecker() 

 

:: 

 

sage: OC.check_output(rndstr,nf,optflag) 

True 

 

sage: OC.check_output(tentol,nf,optflag) 

True 

sage: OC.check_output(tentol,ten,optflag) 

True 

sage: OC.check_output(tentol,zero,optflag) 

False 

 

sage: OC.check_output(tenabs,nf,optflag) 

False 

sage: OC.check_output(tenabs,ten,optflag) 

True 

sage: OC.check_output(tenabs,zero,optflag) 

False 

 

sage: OC.check_output(tenrel,nf,optflag) 

True 

sage: OC.check_output(tenrel,ten,optflag) 

True 

sage: OC.check_output(tenrel,zero,optflag) 

False 

 

sage: OC.check_output(zerotol,zero,optflag) 

True 

sage: OC.check_output(zerotol,eps,optflag) 

True 

sage: OC.check_output(zerotol,ten,optflag) 

False 

 

sage: OC.check_output(zeroabs,zero,optflag) 

True 

sage: OC.check_output(zeroabs,eps,optflag) 

True 

sage: OC.check_output(zeroabs,ten,optflag) 

False 

 

sage: OC.check_output(zerorel,zero,optflag) 

True 

sage: OC.check_output(zerorel,eps,optflag) 

False 

sage: OC.check_output(zerorel,ten,optflag) 

False 

 

More explicit tolerance checks:: 

 

sage: _ = x # rel tol 1e10 

sage: raise RuntimeError # rel tol 1e10 

Traceback (most recent call last): 

... 

RuntimeError 

sage: 1 # abs tol 2 

-0.5 

sage: print("0.9999") # rel tol 1e-4 

1.0 

sage: print("1.00001") # abs tol 1e-5 

1.0 

sage: 0 # rel tol 1 

1 

 

Spaces before numbers or between the sign and number are ignored:: 

 

sage: print("[ - 1, 2]") # abs tol 1e-10 

[-1,2] 

 

Tolerance on Python 3 for string results with unicode prefix:: 

 

sage: a = u'Cyrano'; a 

u'Cyrano' 

sage: b = [u'Fermat', u'Euler']; b 

[u'Fermat', u'Euler'] 

sage: c = u'you'; c 

u'you' 

 

Also allowance for the difference in reprs of ``type`` instances (i.e. 

classes) between Python 2 and Python 3:: 

 

sage: int 

<type 'int'> 

sage: float 

<type 'float'> 

""" 

got = self.human_readable_escape_sequences(got) 

if isinstance(want, MarkedOutput): 

if want.random: 

return True 

elif want.tol or want.rel_tol or want.abs_tol: 

# First check the doctest without the numbers 

want_str = [g[0] for g in float_regex.findall(want)] 

got_str = [g[0] for g in float_regex.findall(got)] 

if len(want_str) != len(got_str): 

return False 

starwant = float_regex.sub('*', want) 

stargot = float_regex.sub('*', got) 

if not doctest.OutputChecker.check_output(self, starwant, stargot, optionflags): 

return False 

 

# Now check the numbers 

want_values = [RIFtol(g) for g in want_str] 

want_intervals = [self.add_tolerance(v, want) for v in want_values] 

got_values = [RIFtol(g) for g in got_str] 

# The doctest is successful if the "want" and "got" 

# intervals have a non-empty intersection 

return all(a.overlaps(b) for a, b in zip(want_intervals, got_values)) 

 

ok = doctest.OutputChecker.check_output(self, want, got, optionflags) 

 

if ok: 

return ok 

 

# Possibly fix up the desired output to account for the difference in 

# reprs of some objects between Python 2 and Python 3 

# Since most of the tests are currently written for Python 2 the only 

# fixups we perform right now are on Python 3 

if six.PY2: 

repr_fixups = [] 

else: 

repr_fixups = [ 

(lambda g, w: 'u"' in w or "u'" in w, remove_unicode_u), 

(lambda g, w: '<class' in g and '<type' in w, 

normalize_type_repr) 

] 

 

did_fixup = False 

for quick_check, fixup in repr_fixups: 

do_fixup = quick_check(got, want) 

if do_fixup: 

want = fixup(want) 

did_fixup = True 

 

if not did_fixup: 

# Return the same result as before 

return ok 

 

return doctest.OutputChecker.check_output(self, want, got, optionflags) 

 

def output_difference(self, example, got, optionflags): 

r""" 

Report on the differences between the desired result and what 

was actually obtained. 

 

If ``want`` is a :class:`MarkedOutput` instance, takes into account the desired tolerance. 

 

INPUT: 

 

- ``example`` -- a :class:`doctest.Example` instance 

- ``got`` -- a string 

- ``optionflags`` -- an integer, passed down to :class:`doctest.OutputChecker` 

 

OUTPUT: 

 

- a string, describing how ``got`` fails to match ``example.want`` 

 

EXAMPLES:: 

 

sage: from sage.doctest.parsing import MarkedOutput, SageOutputChecker 

sage: import doctest 

sage: optflag = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS 

sage: tentol = doctest.Example('',MarkedOutput("10.0\n").update(tol=.1)) 

sage: tenabs = doctest.Example('',MarkedOutput("10.0\n").update(abs_tol=.1)) 

sage: tenrel = doctest.Example('',MarkedOutput("10.0\n").update(rel_tol=.1)) 

sage: zerotol = doctest.Example('',MarkedOutput("0.0\n").update(tol=.1)) 

sage: zeroabs = doctest.Example('',MarkedOutput("0.0\n").update(abs_tol=.1)) 

sage: zerorel = doctest.Example('',MarkedOutput("0.0\n").update(rel_tol=.1)) 

sage: tlist = doctest.Example('',MarkedOutput("[10.0, 10.0, 10.0, 10.0, 10.0, 10.0]\n").update(abs_tol=1.0)) 

sage: zero = "0.0" 

sage: nf = "9.5" 

sage: ten = "10.05" 

sage: eps = "-0.05" 

sage: L = "[9.9, 8.7, 10.3, 11.2, 10.8, 10.0]" 

sage: OC = SageOutputChecker() 

 

:: 

 

sage: print(OC.output_difference(tenabs,nf,optflag)) 

Expected: 

10.0 

Got: 

9.5 

Tolerance exceeded: 

10.0 vs 9.5, tolerance 5e-01 > 1e-01 

 

sage: print(OC.output_difference(tentol,zero,optflag)) 

Expected: 

10.0 

Got: 

0.0 

Tolerance exceeded: 

10.0 vs 0.0, tolerance 1e+00 > 1e-01 

 

sage: print(OC.output_difference(tentol,eps,optflag)) 

Expected: 

10.0 

Got: 

-0.05 

Tolerance exceeded: 

10.0 vs -0.05, tolerance 1e+00 > 1e-01 

 

sage: print(OC.output_difference(tlist,L,optflag)) 

Expected: 

[10.0, 10.0, 10.0, 10.0, 10.0, 10.0] 

Got: 

[9.9, 8.7, 10.3, 11.2, 10.8, 10.0] 

Tolerance exceeded in 2 of 6: 

10.0 vs 8.7, tolerance 1e+00 > 1e+00 

10.0 vs 11.2, tolerance 1e+00 > 1e+00 

 

TESTS:: 

 

sage: print(OC.output_difference(tenabs,zero,optflag)) 

Expected: 

10.0 

Got: 

0.0 

Tolerance exceeded: 

10.0 vs 0.0, tolerance 1e+01 > 1e-01 

 

sage: print(OC.output_difference(tenrel,zero,optflag)) 

Expected: 

10.0 

Got: 

0.0 

Tolerance exceeded: 

10.0 vs 0.0, tolerance 1e+00 > 1e-01 

 

sage: print(OC.output_difference(tenrel,eps,optflag)) 

Expected: 

10.0 

Got: 

-0.05 

Tolerance exceeded: 

10.0 vs -0.05, tolerance 1e+00 > 1e-01 

 

sage: print(OC.output_difference(zerotol,ten,optflag)) 

Expected: 

0.0 

Got: 

10.05 

Tolerance exceeded: 

0.0 vs 10.05, tolerance 1e+01 > 1e-01 

 

sage: print(OC.output_difference(zeroabs,ten,optflag)) 

Expected: 

0.0 

Got: 

10.05 

Tolerance exceeded: 

0.0 vs 10.05, tolerance 1e+01 > 1e-01 

 

sage: print(OC.output_difference(zerorel,eps,optflag)) 

Expected: 

0.0 

Got: 

-0.05 

Tolerance exceeded: 

0.0 vs -0.05, tolerance inf > 1e-01 

 

sage: print(OC.output_difference(zerorel,ten,optflag)) 

Expected: 

0.0 

Got: 

10.05 

Tolerance exceeded: 

0.0 vs 10.05, tolerance inf > 1e-01 

""" 

got = self.human_readable_escape_sequences(got) 

want = example.want 

diff = doctest.OutputChecker.output_difference(self, example, got, optionflags) 

if isinstance(want, MarkedOutput) and (want.tol or want.abs_tol or want.rel_tol): 

if diff[-1] != "\n": 

diff += "\n" 

want_str = [g[0] for g in float_regex.findall(want)] 

got_str = [g[0] for g in float_regex.findall(got)] 

want_values = [RIFtol(g) for g in want_str] 

want_intervals = [self.add_tolerance(v, want) for v in want_values] 

got_values = [RIFtol(g) for g in got_str] 

if len(want_values) == len(got_values): 

def failstr(astr, bstr, actual, desired): 

return " %s vs %s, tolerance %.0e > %.0e"%(astr, bstr, RIFtol(actual).center(), RIFtol(desired).center()) 

 

fails = [] 

for a, ainterval, b, astr, bstr in zip(want_values, want_intervals, got_values, want_str, got_str): 

if not ainterval.overlaps(b): 

if want.tol: 

if a == 0: 

fails.append(failstr(astr, bstr, abs(b), want.tol)) 

else: 

fails.append(failstr(astr, bstr, abs(1 - b/a), want.tol)) 

elif want.abs_tol: 

fails.append(failstr(astr, bstr, abs(a - b), want.abs_tol)) 

else: 

fails.append(failstr(astr, bstr, abs(1 - b/a), want.rel_tol)) 

 

if fails: 

if len(want_values) == 1: 

diff += "Tolerance exceeded:\n" 

else: 

diff += "Tolerance exceeded in %s of %s:\n"%(len(fails), len(want_values)) 

diff += "\n".join(fails) + "\n" 

return diff