File: test_node_reparenting.rb

package info (click to toggle)
ruby-nokogiri 1.11.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,576 kB
  • sloc: xml: 28,086; ruby: 18,456; java: 13,067; ansic: 5,138; yacc: 265; sh: 208; makefile: 27
file content (754 lines) | stat: -rw-r--r-- 30,552 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
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
# frozen_string_literal: true
require "helper"

module Nokogiri
  module XML
    class TestNodeReparenting < Nokogiri::TestCase
      describe "standard node reparenting behavior" do
        # describe "namespace handling during reparenting" do
        #   describe "given a Node" do
        #     describe "with a Namespace" do
        #       it "keeps the Namespace"
        #     end
        #     describe "given a parent Node with a default and a non-default Namespace" do
        #       describe "passed an Node without a namespace" do
        #         it "inserts an Node that inherits the default Namespace"
        #       end
        #       describe "passed a Node with a Namespace that matches the parent's non-default Namespace" do
        #         it "inserts a Node that inherits the matching parent Namespace"
        #       end
        #     end
        #   end
        #   describe "given a markup string" do
        #     describe "parsed relative to the document" do
        #       describe "with a Namespace" do
        #         it "keeps the Namespace"
        #       end
        #       describe "given a parent Node with a default and a non-default Namespace" do
        #         describe "passed an Node without a namespace" do
        #           it "inserts an Node that inherits the default Namespace"
        #         end
        #         describe "passed a Node with a Namespace that matches the parent's non-default Namespace" do
        #           it "inserts a Node that inherits the matching parent Namespace"
        #         end
        #       end
        #     end
        #     describe "parsed relative to a specific node" do
        #       describe "with a Namespace" do
        #         it "keeps the Namespace"
        #       end
        #       describe "given a parent Node with a default and a non-default Namespace" do
        #         describe "passed an Node without a namespace" do
        #           it "inserts an Node that inherits the default Namespace"
        #         end
        #         describe "passed a Node with a Namespace that matches the parent's non-default Namespace" do
        #           it "inserts a Node that inherits the matching parent Namespace"
        #         end
        #       end
        #     end
        #   end
        # end

        before do
          @doc = Nokogiri::XML("<root><a1>First node</a1><a2>Second node</a2><a3>Third <bx />node</a3></root>")
          @doc2 = @doc.dup
          @fragment_string = "<b1>foo</b1><b2>bar</b2>"
          @fragment = Nokogiri::XML::DocumentFragment.parse(@fragment_string)
          @node_set = Nokogiri::XML("<root><b1>foo</b1><b2>bar</b2></root>").xpath("/root/node()")
        end

        {
          :add_child => { target: "/root/a1", returns_self: false, children_tags: %w[text b1 b2] },
          :<< => { target: "/root/a1", returns_self: true, children_tags: %w[text b1 b2] },

          :replace => { target: "/root/a1/node()", returns_self: false, children_tags: %w[b1 b2] },
          :swap => { target: "/root/a1/node()", returns_self: true, children_tags: %w[b1 b2] },

          :children= => { target: "/root/a1", returns_self: false, children_tags: %w[b1 b2] },
          :inner_html= => { target: "/root/a1", returns_self: true, children_tags: %w[b1 b2] },

          :add_previous_sibling => { target: "/root/a1/text()", returns_self: false, children_tags: %w[b1 b2 text] },
          :previous= => { target: "/root/a1/text()", returns_self: false, children_tags: %w[b1 b2 text] },
          :before => { target: "/root/a1/text()", returns_self: true, children_tags: %w[b1 b2 text] },

          :add_next_sibling => { target: "/root/a1/text()", returns_self: false, children_tags: %w[text b1 b2] },
          :next= => { target: "/root/a1/text()", returns_self: false, children_tags: %w[text b1 b2] },
          :after => { target: "/root/a1/text()", returns_self: true, children_tags: %w[text b1 b2] },
        }.each do |method, params|
          describe "##{method}" do
            describe "passed a Node" do
              [:current, :another].each do |which|
                describe "passed a Node in the #{which} document" do
                  before do
                    @other_doc = which == :current ? @doc : @doc2
                    @other_node = @other_doc.at_xpath("/root/a2")
                  end

                  it "unlinks the Node from its previous position" do
                    @doc.at_xpath(params[:target]).send(method, @other_node)
                    result = @other_doc.at_xpath("/root/a2")
                    _(result).must_be_nil
                  end

                  it "inserts the Node in the proper position" do
                    @doc.at_xpath(params[:target]).send(method, @other_node)
                    result = @doc.at_xpath("/root/a1/a2")
                    _(result).wont_be_nil
                  end

                  it "returns the expected value" do
                    sendee = @doc.at_xpath(params[:target])
                    result = sendee.send(method, @other_node)
                    if params[:returns_self]
                      _(result).must_equal(sendee)
                    else
                      _(result).must_equal(@other_node)
                    end
                  end
                end
              end
            end
            describe "passed a markup string" do
              it "inserts the fragment roots in the proper position" do
                @doc.at_xpath(params[:target]).send(method, @fragment_string)
                result = @doc.xpath("/root/a1/node()").collect(&:name)
                _(result).must_equal(params[:children_tags])
              end

              it "returns the expected value" do
                sendee = @doc.at_xpath(params[:target])
                result = sendee.send(method, @fragment_string)
                if params[:returns_self]
                  _(result).must_equal(sendee)
                else
                  _(result).must_be_kind_of(Nokogiri::XML::NodeSet)
                  _(result.to_html).must_equal(@fragment_string)
                end
              end
            end
            describe "passed a fragment" do
              it "inserts the fragment roots in the proper position" do
                @doc.at_xpath(params[:target]).send(method, @fragment)
                result = @doc.xpath("/root/a1/node()").collect(&:name)
                _(result).must_equal(params[:children_tags])
              end
            end
            describe "passed a document" do
              it "raises an exception" do
                assert_raise(ArgumentError) { @doc.at_xpath("/root/a1").send(method, @doc2) }
              end
            end
            describe "passed a non-Node" do
              it "raises an exception" do
                assert_raise(ArgumentError) { @doc.at_xpath("/root/a1").send(method, 42) }
              end
            end
            describe "passed a NodeSet" do
              it "inserts each member of the NodeSet in the proper order" do
                @doc.at_xpath(params[:target]).send(method, @node_set)
                result = @doc.xpath("/root/a1/node()").collect(&:name)
                _(result).must_equal(params[:children_tags])
              end
            end
          end
        end

        describe "text node merging" do
          describe "#add_child" do
            it "merges the Text node with adjacent Text nodes" do
              @doc.at_xpath("/root/a1").add_child(Nokogiri::XML::Text.new("hello", @doc))
              result = @doc.at_xpath("/root/a1/text()").content
              _(result).must_equal("First nodehello")
            end
          end

          describe "#replace" do
            it "merges the Text node with adjacent Text nodes" do
              @doc.at_xpath("/root/a3/bx").replace(Nokogiri::XML::Text.new("hello", @doc))
              result = @doc.at_xpath("/root/a3/text()").content
              _(result).must_equal("Third hellonode")
            end
          end
        end

        describe "in-context parsing" do
          specs = {
            :add_child => :self,
            :<< => :self,

            :replace => :parent,
            :swap => :parent,

            :children= => :self,
            :inner_html= => :self,

            :add_previous_sibling => :parent,
            :previous= => :parent,
            :before => :parent,

            :add_next_sibling => :parent,
            :next= => :parent,
            :after => :parent,
          }

          specs.each do |method, which|
            describe "##{method} parsing input" do
              let(:xml) do
                <<~EOF
                <root>
                  <parent><context></context></parent>
                </root>
              EOF
              end

              let(:doc) { Nokogiri::XML::Document.parse(xml) }
              let(:context_node) { doc.at_css("context") }

              after do
                GC.start
              end

              describe "with a parent" do
                let(:expected_callee) do
                  if which == :self
                    context_node
                  elsif which == :parent
                    context_node.parent
                  else
                    raise("unable to discern what the test means by #{which}")
                  end
                end

                before do
                  class << expected_callee
                    attr_reader :coerce_was_called
                    def coerce(data)
                      @coerce_was_called = true
                      super
                    end
                  end
                end

                it "in context of #{which}" do
                  context_node.__send__(method, "<child>content</child>")

                  assert expected_callee.coerce_was_called, "expected coerce to be called on #{which}"
                end
              end

              if which == :parent
                describe "without a parent" do
                  before { context_node.unlink }

                  it "raises an exception" do
                    ex = assert_raise(RuntimeError) do
                      context_node.__send__(method, "<child>content</child>")
                    end
                    assert_match(/no parent/, ex.message)
                  end
                end
              end
            end
          end
        end
      end

      describe "ad hoc node reparenting behavior" do
        describe "#<<" do
          it "allows chaining" do
            doc = Nokogiri::XML::Document.new
            root = Nokogiri::XML::Element.new("root", doc)
            doc.root = root

            child1 = Nokogiri::XML::Element.new("child1", doc)
            child2 = Nokogiri::XML::Element.new("child2", doc)

            doc.root << child1 << child2

            assert_equal [child1, child2], doc.root.children.to_a
          end
        end

        describe "#add_child" do
          describe "given a new node with a namespace" do
            it "keeps the namespace" do
              doc = Nokogiri::XML::Document.new
              item = Nokogiri::XML::Element.new("item", doc)
              doc.root = item

              entry = Nokogiri::XML::Element.new("entry", doc)
              entry.add_namespace("tlm", "http://tenderlovemaking.com")
              assert_equal "http://tenderlovemaking.com", entry.namespaces["xmlns:tlm"]
              item.add_child(entry)
              assert_equal "http://tenderlovemaking.com", entry.namespaces["xmlns:tlm"]
            end
          end

          describe "given the new document is empty" do
            it "adds the node to the new document" do
              doc1 = Nokogiri::XML.parse("<value>3</value>")
              doc2 = Nokogiri::XML::Document.new
              node = doc1.at_xpath("//value")
              node.remove
              doc2.add_child(node)
              assert_match(%r{<value>3</value>}, doc2.to_xml)
            end
          end

          describe "given a parent node with a default namespace" do
            before do
              @doc = Nokogiri::XML(<<~eoxml)
                <root xmlns="http://tenderlovemaking.com/">
                  <first>
                  </first>
                </root>
              eoxml
            end

            it "inserts a node that inherits the default namespace" do
              assert node = @doc.at("//xmlns:first")
              child = Nokogiri::XML::Node.new("second", @doc)
              node.add_child(child)
              assert @doc.at("//xmlns:second")
            end

            describe "and a child node was added to a new doc with the a different namespace using the same prefix" do
              before do
                @doc = Nokogiri::XML(%{<root xmlns:bar="http://tenderlovemaking.com/"><bar:first/></root>})
                new_doc = Nokogiri::XML(%{<newroot xmlns:bar="http://flavorjon.es/"/>})
                assert node = @doc.at("//tenderlove:first", tenderlove: "http://tenderlovemaking.com/")
                new_doc.root.add_child(node)
                @doc = new_doc
              end

              it "serializes the doc with the proper default namespace" do
                assert_match(%r{<bar:first\ xmlns:bar="http://tenderlovemaking.com/"/>}, @doc.to_xml)
              end
            end

            describe "and a child node was added to a new doc with the same default namespaces" do
              before do
                new_doc = Nokogiri::XML(%{<newroot xmlns="http://tenderlovemaking.com/"/>})
                assert node = @doc.at("//tenderlove:first", tenderlove: "http://tenderlovemaking.com/")
                new_doc.root.add_child(node)
                @doc = new_doc
              end

              it "serializes the doc with the proper default namespace" do
                assert_match(/<first>/, @doc.to_xml)
              end
            end

            describe "and a child node was added to a new doc without any default namespaces" do
              before do
                new_doc = Nokogiri::XML("<newroot/>")
                assert node = @doc.at("//tenderlove:first", tenderlove: "http://tenderlovemaking.com/")
                new_doc.root.add_child(node)
                @doc = new_doc
              end

              it "serializes the doc with the proper default namespace" do
                assert_match(%r{<first xmlns=\"http://tenderlovemaking.com/\">}, @doc.to_xml)
              end
            end

            describe "and a child node became the root of a new doc" do
              before do
                new_doc = Nokogiri::XML::Document.new
                assert node = @doc.at("//tenderlove:first", tenderlove: "http://tenderlovemaking.com/")
                new_doc.root = node
                @doc = new_doc
              end

              it "serializes the doc with the proper default namespace" do
                assert_match(%r{<first xmlns=\"http://tenderlovemaking.com/\">}, @doc.to_xml)
              end
            end
          end

          describe "given a parent node with a default and non-default namespace" do
            before do
              @doc = Nokogiri::XML(<<~eoxml)
                <root xmlns="http://tenderlovemaking.com/" xmlns:foo="http://flavorjon.es/">
                  <first>
                  </first>
                </root>
              eoxml
              assert @node = @doc.at("//xmlns:first")
              @child = Nokogiri::XML::Node.new("second", @doc)
            end

            describe "and a child with a namespace matching the parent's default namespace" do
              describe "and as the default prefix" do
                before do
                  @ns = @child.add_namespace(nil, "http://tenderlovemaking.com/")
                  @child.namespace = @ns
                end

                it "inserts a node that inherits the parent's default namespace" do
                  @node.add_child(@child)
                  assert reparented = @doc.at("//bar:second", "bar" => "http://tenderlovemaking.com/")
                  assert reparented.namespace_definitions.empty?
                  assert_equal @doc.root.namespace, reparented.namespace
                  assert_equal(
                    {
                      "xmlns" => "http://tenderlovemaking.com/",
                      "xmlns:foo" => "http://flavorjon.es/",
                    },
                    reparented.namespaces
                  )
                end
              end

              describe "but with a different prefix" do
                before do
                  @ns = @child.add_namespace("baz", "http://tenderlovemaking.com/")
                  @child.namespace = @ns
                end

                it "inserts a node that uses its own namespace" do
                  @node.add_child(@child)
                  assert reparented = @doc.at("//bar:second", "bar" => "http://tenderlovemaking.com/")
                  assert reparented.namespace_definitions.include?(@ns)
                  assert_equal @ns, reparented.namespace
                  assert_equal(
                    {
                      "xmlns" => "http://tenderlovemaking.com/",
                      "xmlns:foo" => "http://flavorjon.es/",
                      "xmlns:baz" => "http://tenderlovemaking.com/",
                    },
                    reparented.namespaces
                  )
                end
              end
            end

            describe "and a child with a namespace matching the parent's non-default namespace" do
              before do
                @root_ns = @doc.root.namespace_definitions.detect { |x| x.prefix == "foo" }
              end

              describe "set by #namespace=" do
                before do
                  @child.namespace = @root_ns
                end

                it "inserts a node that inherits the matching parent namespace" do
                  @node.add_child(@child)
                  assert reparented = @doc.at("//bar:second", "bar" => "http://flavorjon.es/")
                  assert reparented.namespace_definitions.empty?
                  assert_equal @root_ns, reparented.namespace
                  assert_equal(
                    {
                      "xmlns" => "http://tenderlovemaking.com/",
                      "xmlns:foo" => "http://flavorjon.es/",
                    },
                    reparented.namespaces
                  )
                end
              end

              describe "with the same prefix" do
                before do
                  @ns = @child.add_namespace("foo", "http://flavorjon.es/")
                  @child.namespace = @ns
                end

                it "inserts a node that uses the parent's namespace" do
                  @node.add_child(@child)
                  assert reparented = @doc.at("//bar:second", "bar" => "http://flavorjon.es/")
                  assert reparented.namespace_definitions.empty?
                  assert_equal @root_ns, reparented.namespace
                  assert_equal(
                    {
                      "xmlns" => "http://tenderlovemaking.com/",
                      "xmlns:foo" => "http://flavorjon.es/",
                    },
                    reparented.namespaces
                  )
                end
              end

              describe "as the default prefix" do
                before do
                  @ns = @child.add_namespace(nil, "http://flavorjon.es/")
                  @child.namespace = @ns
                end

                it "inserts a node that keeps its namespace" do
                  @node.add_child(@child)
                  assert reparented = @doc.at("//bar:second", "bar" => "http://flavorjon.es/")
                  assert reparented.namespace_definitions.include?(@ns)
                  assert_equal @ns, reparented.namespace
                  assert_equal(
                    {
                      "xmlns" => "http://flavorjon.es/",
                      "xmlns:foo" => "http://flavorjon.es/",
                    },
                    reparented.namespaces
                  )
                end
              end

              describe "but with a different prefix" do
                before do
                  @ns = @child.add_namespace("baz", "http://flavorjon.es/")
                  @child.namespace = @ns
                end

                it "inserts a node that keeps its namespace" do
                  @node.add_child(@child)
                  assert reparented = @doc.at("//bar:second", "bar" => "http://flavorjon.es/")
                  assert reparented.namespace_definitions.include?(@ns)
                  assert_equal @ns, reparented.namespace
                  assert_equal(
                    {
                      "xmlns" => "http://tenderlovemaking.com/",
                      "xmlns:foo" => "http://flavorjon.es/",
                      "xmlns:baz" => "http://flavorjon.es/",
                    },
                    reparented.namespaces
                  )
                end
              end
            end

            describe "and a child node with a default namespace not matching the parent's default namespace and a namespace matching a parent namespace but with a different prefix" do
              before do
                @ns = @child.add_namespace(nil, "http://example.org/")
                @child.namespace = @ns
                @ns2 = @child.add_namespace("baz", "http://tenderlovemaking.com/")
              end

              it "inserts a node that keeps its namespace" do
                @node.add_child(@child)
                assert reparented = @doc.at("//bar:second", "bar" => "http://example.org/")
                assert reparented.namespace_definitions.include?(@ns)
                assert reparented.namespace_definitions.include?(@ns2)
                assert_equal @ns, reparented.namespace
                assert_equal(
                  {
                    "xmlns" => "http://example.org/",
                    "xmlns:foo" => "http://flavorjon.es/",
                    "xmlns:baz" => "http://tenderlovemaking.com/",
                  },
                  reparented.namespaces
                )
              end
            end
          end
        end

        describe "#add_previous_sibling" do
          it "should not merge text nodes during the operation" do
            xml = Nokogiri::XML(%(<root>text node</root>))
            replacee = xml.root.children.first
            replacee.add_previous_sibling("foo <p></p> bar")
            assert_equal "foo <p></p> bartext node", xml.root.children.to_html
          end

          it "should remove the child node after the operation" do
            fragment = Nokogiri::HTML::DocumentFragment.parse("a<a>b</a>")
            node = fragment.children.last
            node.add_previous_sibling(node.children)
            assert_empty node.children, "should have no childrens"
          end

          describe "with a text node before" do
            it "should not defensively dup the 'before' text node" do
              xml = Nokogiri::XML(%(<root>before<p></p>after</root>))
              pivot = xml.at_css("p")
              before = xml.root.children.first
              after = xml.root.children.last
              pivot.add_previous_sibling("x")

              assert_equal "after", after.content
              assert !after.parent.nil?, "unrelated node should not be affected"

              assert_equal "before", before.content
              assert !before.parent.nil?, "no need to reparent"
            end
          end
        end

        describe "#add_next_sibling" do
          it "should not merge text nodes during the operation" do
            xml = Nokogiri::XML(%(<root>text node</root>))
            replacee = xml.root.children.first
            replacee.add_next_sibling("foo <p></p> bar")
            assert_equal "text nodefoo <p></p> bar", xml.root.children.to_html
          end

          it "should append a text node before an existing non text node" do
            xml = Nokogiri::XML(%(<root><p>foo</p><p>bar</p></root>))
            p = xml.at_css("p")
            p.add_next_sibling("a")
            assert_equal "<root><p>foo</p>a<p>bar</p></root>", xml.root.to_s
          end

          it "should append a text node before an existing text node" do
            xml = Nokogiri::XML(%(<root><p>foo</p>after</root>))
            p = xml.at_css("p")
            p.add_next_sibling("x")
            assert_equal "<root><p>foo</p>xafter</root>", xml.root.to_s
          end

          describe "with a text node after" do
            it "should not defensively dup the 'after' text node" do
              xml = Nokogiri::XML(%(<root>before<p></p>after</root>))
              pivot = xml.at_css("p")
              before = xml.root.children.first
              after = xml.root.children.last
              pivot.add_next_sibling("x")

              assert_equal "before", before.content
              assert !before.parent.nil?, "unrelated node should not be affected"

              assert_equal "after", after.content
              assert !after.parent.nil?
            end
          end
        end

        describe "#replace" do
          describe "a text node with a text node" do
            it "should not merge text nodes during the operation" do
              xml = Nokogiri::XML(%(<root>text node</root>))
              replacee = xml.root.children.first
              replacee.replace("new text node")
              assert_equal "new text node", xml.root.children.first.content
            end
          end

          it "can replace with a comment node" do
            doc = Nokogiri::XML(%{<parent><child>text})
            replacee = doc.at_css("child")
            replacer = doc.create_comment("<b>text</b>")
            replacee.replace(replacer)
            assert_equal 1, doc.root.children.length
            assert_equal replacer, doc.root.children.first
          end

          it "can replace with a CDATA node" do
            doc = Nokogiri::XML(%{<parent><child>text})
            replacee = doc.at_css("child")
            replacer = doc.create_cdata("<b>text</b>")
            replacee.replace(replacer)
            assert_equal 1, doc.root.children.length
            assert_equal replacer, doc.root.children.first
          end

          describe "when a document has a default namespace" do
            before do
              @fruits = Nokogiri::XML(<<~eoxml)
                <fruit xmlns="http://fruits.org">
                  <apple />
                </fruit>
              eoxml
            end

            it "inserts a node with default namespaces" do
              apple = @fruits.css("apple").first

              orange = Nokogiri::XML::Node.new("orange", @fruits)
              apple.replace(orange)

              assert_equal orange, @fruits.css("orange").first
            end
          end
        end

        describe "unlinking a node and then reparenting it" do
          it "not blow up" do
            # see http://github.com/sparklemotion/nokogiri/issues#issue/22
            10.times do
              doc = Nokogiri::XML(<<~EOHTML)
                <root>
                  <a>
                    <b/>
                    <c/>
                  </a>
                </root>
              EOHTML

              assert root = doc.at("root")
              assert a = root.at("a")
              assert b = a.at("b")
              assert c = a.at("c")
              a.add_next_sibling(b.unlink)
              c.unlink

              GC.start
            end
          end
        end

        describe "replace-merging text nodes" do
          [
            ["<root>a<br/></root>", "afoo"],
            ["<root>a<br/>b</root>", "afoob"],
            ["<root><br/>b</root>", "foob"],
          ].each do |xml, result|
            it "doesn't blow up on #{xml}" do
              doc = Nokogiri::XML.parse(xml)
              saved_nodes = doc.root.children
              doc.at_xpath("/root/br").replace(Nokogiri::XML::Text.new("foo", doc))
              saved_nodes.each(&:inspect) # try to cause a crash
              assert_equal result, doc.at_xpath("/root/text()").inner_text
            end
          end
        end

        describe "reparenting and preserving a reference to the original ns" do
          it "should not cause illegal memory access" do
            # this test will only cause a failure in valgrind. it
            # drives out the reason why we can't call xmlFreeNs in
            # relink_namespace and instead have to root the nsdef.
            doc = Nokogiri::XML('<root xmlns="http://flavorjon.es/"><envelope /></root>')
            elem = doc.create_element("package", { "xmlns" => "http://flavorjon.es/" })
            ns = elem.namespace_definitions
            doc.at_css("envelope").add_child(elem)
            ns.inspect
          end
        end

        describe "reparenting into another document" do
          it "correctly sets default namespace of a reparented node" do
            # issue described in #391
            # thanks to Nick Canzoneri @nickcanz for this test case!
            source_doc = Nokogiri::XML(<<~EOX)
              <?xml version="1.0" encoding="utf-8"?>
              <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
                  <Product>
                      <Package />
                      <Directory Id="TARGETDIR" Name="SourceDir">
                          <Component>
                              <File />
                          </Component>
                      </Directory>
                  </Product>
              </Wix>
            EOX

            dest_doc = Nokogiri::XML(<<~EOX)
              <?xml version="1.0" encoding="utf-8"?>
              <Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
                <Fragment Id='MSIComponents'>
                    <DirectoryRef Id='InstallDir'>
                    </DirectoryRef>
                </Fragment>
              </Wix>
            EOX

            stuff = source_doc.at_css("Directory[Id='TARGETDIR']")
            insert_point = dest_doc.at_css("DirectoryRef[Id='InstallDir']")
            insert_point.children = stuff.children

            assert_no_match(/default:/, insert_point.children.to_xml)
            assert_match(/<Component>/, insert_point.children.to_xml)
          end
        end
      end
    end
  end
end