Skip to content

Commit

Permalink
ensure CData.new will raise TypeError
Browse files Browse the repository at this point in the history
if the _content_ argument is not implicitly convertible into a string.
  • Loading branch information
flavorjones committed Aug 10, 2017
1 parent bf5dff5 commit c766f6e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
14 changes: 9 additions & 5 deletions ext/nokogiri/xml_cdata.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
* new(document, content)
*
* Create a new CDATA element on the +document+ with +content+
*
* If +content+ cannot be implicitly converted to a string, this method will
* raise a TypeError exception.
*/
static VALUE new(int argc, VALUE *argv, VALUE klass)
{
Expand All @@ -14,16 +17,17 @@ static VALUE new(int argc, VALUE *argv, VALUE klass)
VALUE content;
VALUE rest;
VALUE rb_node;
const xmlChar *content_str;
int content_str_len;

rb_scan_args(argc, argv, "2*", &doc, &content, &rest);

Data_Get_Struct(doc, xmlDoc, xml_doc);

node = xmlNewCDataBlock(
xml_doc->doc,
NIL_P(content) ? NULL : (const xmlChar *)StringValuePtr(content),
NIL_P(content) ? 0 : (int)RSTRING_LEN(content)
);
content_str = NIL_P(content) ? NULL : (const xmlChar *)StringValueCStr(content);
content_str_len = (content_str == NULL) ? 0 : strlen(content_str);

node = xmlNewCDataBlock(xml_doc->doc, content_str, content_str_len);

nokogiri_root_node(node);

Expand Down
6 changes: 6 additions & 0 deletions test/xml/test_cdata.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ def test_new_with_nil
assert_equal nil, node.content
end

def test_new_with_non_string
assert_raises(TypeError) do
CDATA.new(@xml, 1.234)
end
end

def test_lots_of_new_cdata
assert 100.times { CDATA.new(@xml, "asdfasdf") }
end
Expand Down

0 comments on commit c766f6e

Please sign in to comment.