ruby-jing 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 3d008f4db22a52baedf6f25339cd24ba6e9848ea
4
+ data.tar.gz: 3ac4428cf7a0d8c372a401e4585f2c13bc1d8ba9
5
+ SHA512:
6
+ metadata.gz: d4d4a4682496576208a44f81ca98fdd712067f874d35747881f8a966f05061b59c9d62c3b643225bd19b115785b1f9a22279675fe4acad91c73ec6b7a255822b
7
+ data.tar.gz: bd73c441aa2ac74bca835316823624234fc1af79d2237847f4e4d4740f1393b915a33f23ee3f30c743f91bd60030d9dc37a1a64c0f92cacf2e139dbd2146eaa4
@@ -0,0 +1,135 @@
1
+ = Ruby Jing
2
+
3
+ {<img src="https://secure.travis-ci.org/sshaw/ruby-jing.png"/>}[http://travis-ci.org/sshaw/ruby-jing]
4
+ {<img src="https://codeclimate.com/github/sshaw/ruby-jing.png" />}[https://codeclimate.com/github/sshaw/ruby-jing]
5
+
6
+ RELAX NG schema validation using the {Jing CLI}[http://www.thaiopensource.com/relaxng/jing.html]
7
+
8
+ === Overview
9
+
10
+ require "jing"
11
+
12
+ jing = Jing.new("schema.rng")
13
+ begin
14
+ errors = jing.validate("doc.xml")
15
+ rescue Jing::OptionError, Jing::ExecutionError => e
16
+ abort "what what what #{e}"
17
+ end
18
+
19
+ if errors.none?
20
+ puts "Valid!"
21
+ else
22
+ errors.each do |error|
23
+ puts "#{error[:message]} @ #{error[:line]}:#{error[:column]}"
24
+ end
25
+ end
26
+
27
+ # This can also raise errors
28
+ abort "Invalid!" unless jing.valid?("/path/to/doc.xml")
29
+
30
+ === Why use Java to validate instead of Ruby libraries like Nokorigi, REXML, libxml, etc..?
31
+
32
+ Simple: good error messages. Let's look at the error messages provided by each of these libraries.
33
+
34
+ <!-- RNG schema -->
35
+ <element name="addressBook" xmlns="http://relaxng.org/ns/structure/1.0">
36
+ <zeroOrMore>
37
+ <element name="card">
38
+ <attribute name="version">
39
+ <choice>
40
+ <value>v1</value>
41
+ <value>v2</value>
42
+ </choice>
43
+ </attribute>
44
+ <element name="name">
45
+ <text/>
46
+ </element>
47
+ </element>
48
+ </zeroOrMore>
49
+ </element>
50
+
51
+ <!-- XML A -->
52
+ <addressBook>
53
+ <card></card>
54
+ </addressBook>
55
+
56
+ <!-- XML B -->
57
+ <addressBook>
58
+ <card verison="v100">
59
+ <name>John Smith</name>
60
+ <oops>Doh!</oops>
61
+ </card>
62
+ </addressBook>
63
+
64
+ ==== Nokorigi/libxml
65
+
66
+ schema = Nokogiri::XML::RelaxNG(File.read(rng))
67
+ doc = Nokogiri::XML(File.read(xml))
68
+ errors = schema.validate(doc)
69
+ errors.each { |e| puts e }
70
+
71
+ Resulting errors:
72
+
73
+ # XML A
74
+ Element card failed to validate attributes
75
+ Expecting an element , got nothing
76
+
77
+ # XML B
78
+ Element card failed to validate attributes
79
+ Did not expect element oops there
80
+
81
+ ==== REXML
82
+
83
+ include REXML
84
+ doc = Document.new(File.read(xml))
85
+ validator = Validation::RelaxNG.new(File.read(rng))
86
+ validator.validate(doc)
87
+
88
+ Fails for XML A and XML B --it treats the XML declaration as a validation error!
89
+
90
+ Validation error. Expected: :start_element( addressBook ) from < S.1 #:start_element( addressBook ), < Z.2 #:start_element( card ), :start_attribute( version ), < C.3 :text( v1 ) or :text( v2 ) >, :end_attribute( ), :start_element( name ), :text( ), :end_element( ), :start_element( email ), :text( ), :end_element( ), :end_element( ) >, :end_element( ), :end_document( ) > but got <?xml ... ?>(
91
+ )
92
+
93
+ ==== Jing
94
+
95
+ jing = Jing.new(schema)
96
+ errors = jing.validate(xml)
97
+ errors.each { |e| puts e[:message] }
98
+
99
+ Resulting errors:
100
+
101
+ # XML A
102
+ element "card" missing required attribute "version"
103
+ element "card" incomplete; missing required element "name"
104
+
105
+ # XML B
106
+ value of attribute "version" is invalid; must be equal to "v1" or "v2"
107
+ element "oops" not allowed anywhere; expected the element end-tag
108
+
109
+ Better, don't ya think?
110
+
111
+ === More Info
112
+
113
+ * {Docs}[http://rdoc.info/gems/ruby-jing/frames]
114
+ * {Bugs}[http://github.com/sshaw/ruby-jing/issues]
115
+
116
+ === Author
117
+
118
+ Skye Shaw [skye.shaw AT gmail.com]
119
+
120
+ === License
121
+
122
+ Released under the MIT License: www.opensource.org/licenses/MIT
123
+
124
+ === Jing Copying Conditions
125
+
126
+ Copyright (c) 2001-2003 Thai Open Source Software Center Ltd
127
+ All rights reserved.
128
+
129
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
130
+
131
+ * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
132
+ * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
133
+ * Neither the name of the Thai Open Source Software Center Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
134
+
135
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Binary file
@@ -0,0 +1,139 @@
1
+ require "optout"
2
+
3
+ class Jing
4
+ VERSION = "0.0.1"
5
+ DEFAULT_JAR = File.join(File.dirname(__FILE__), "jing-20091111.jar")
6
+
7
+ Error = Class.new(StandardError)
8
+ ExecutionError = Class.new(Error)
9
+ OptionError = Class.new(Error)
10
+
11
+ @@option_builder = Optout.options do
12
+ on :java, :required => true, :default => "java"
13
+ on :jar, "-jar", Optout::File.exists, :default => DEFAULT_JAR
14
+ on :compact, "-c", Optout::Boolean
15
+ on :encoding, "-e", String
16
+ on :id_check, "-i", Optout::Boolean, :default => false
17
+ on :schema, Optout::File.exists, :required => true
18
+ on :xmlfile, Optout::File.exists, :required => true
19
+ end
20
+
21
+ ##
22
+ # Cretae an instance to validate against the given schema. The schema can be in the XML or compact syntax.
23
+ #
24
+ # jing = Jing.new("schema.rng", options)
25
+ #
26
+ # === Arguments
27
+ #
28
+ # [schema (String)] Path to the schema
29
+ # [options (Hash)] Jing options, optional
30
+ #
31
+ # === Options
32
+ #
33
+ # [:java (String)] Name and/or location of the java executable. Defaults to <code>"java"</code>.
34
+ # [:jar (String)] Path to the Jing JAR file. Defaults to the bundled JAR.
35
+ # [:compact (Boolean)] Set to +true+ if the schema uses the RELAX NG compact syntax. Defaults to false, will be set to +true+ is the schema has a +.rnc+ extension.
36
+ # [:encoding (String)] Encoding of the XML document.
37
+ # [:id_check (Boolean)] Disable checking of ID/IDREF/IDREFS. Defaults to +false+
38
+
39
+ # === Errors
40
+ #
41
+ # [ArgumentError] If the options are not +nil+ or a +Hash+.
42
+
43
+ def initialize(schema, options = nil)
44
+ if options
45
+ raise ArgumentError, "options must be a Hash" unless Hash === options
46
+ @options = options.dup
47
+ end
48
+
49
+ @options ||= {}
50
+ @options[:schema] = schema
51
+ @options[:compact] = true if @options[:compact].nil? and @options[:schema] =~ /\.rnc\Z/i # Don't override an explicit setting
52
+ # Optout quirk: true will *include* the switch, which means we *don't* want to check
53
+ @options[:id_check] = !@options[:id_check] if @options.include?(:id_check)
54
+ end
55
+
56
+ ##
57
+ # Validate an XML document against the schema.
58
+ #
59
+ # errors = jing.validate("doc.xml")
60
+ #
61
+ # === Arguments
62
+ #
63
+ # [xml (String)] Path to the XML file
64
+ #
65
+ # === Errors
66
+ #
67
+ # [Jing::OptionError] A Jing option was invalid. Note that this <b>does not apply to an invalid <code>:java</code> option.</b>
68
+ # [Jing::ExecutionError] Problems were encountered trying to execute Jing.
69
+ #
70
+ # === Returns
71
+ #
72
+ # [Array] The errors, each element is a +Hash+. See Error Hash for more info.
73
+ #
74
+ # ==== Error Hash
75
+ #
76
+ # The error hash contains the following keys/values
77
+ #
78
+ # [:source (String)] File containing the error, can be the schema or the instance XML.
79
+ # [:line (Fixnum)] Line number
80
+ # [:column (Fixnum)] Column number
81
+ # [:message (String)] The problem
82
+
83
+ def validate(xml)
84
+ @options[:xmlfile] = xml
85
+
86
+ out = execute(@options)
87
+ return [] if $?.success? and out.empty?
88
+ errors = parse_output(out)
89
+ raise ExecutionError, out if errors.none? # There must have been a problem that was not schema related
90
+ errors
91
+ end
92
+
93
+ # Validate an XML document against the schema. To receive a list of vlidation errors use #validate.
94
+ #
95
+ # puts "yay!" if jing.valid?("doc.xml")
96
+ #
97
+ # === Arguments
98
+ #
99
+ # [xml (String)] Path to the XML file
100
+ #
101
+ # === Errors
102
+ #
103
+ # Same as #validate
104
+ #
105
+ # === Returns
106
+ #
107
+ # [Boolean] +true+ if valid, +false+ if invalid
108
+ #
109
+
110
+ def valid?(xml)
111
+ errors = validate(xml)
112
+ errors.none?
113
+ end
114
+
115
+ private
116
+ def execute(options)
117
+ cmd = @@option_builder.shell(options)
118
+ `#{cmd} 2>&1`
119
+ rescue SystemCallError => e
120
+ raise ExecutionError, "jing execution failed: #{e}"
121
+ rescue Optout::OptionError => e
122
+ raise OptionError, e.message
123
+ end
124
+
125
+ def parse_output(output)
126
+ errors = []
127
+ output.split("\n").map do |line|
128
+ if line =~ /\A(.+):(\d+):(\d+):\s+\w+:\s+(.+)\Z/
129
+ errors << {
130
+ :source => $1,
131
+ :line => $2.to_i,
132
+ :column => $3.to_i,
133
+ :message => $4
134
+ }
135
+ end
136
+ end
137
+ errors
138
+ end
139
+ end
@@ -0,0 +1,140 @@
1
+ require "minitest/autorun"
2
+ require "tempfile"
3
+ require "jing"
4
+
5
+ class TestJing < MiniTest::Unit::TestCase
6
+ root = File.join(File.expand_path(File.dirname(__FILE__)), "fixtures")
7
+
8
+ VALID_XML = File.join(root, "valid.xml")
9
+ INVALID_XML = File.join(root, "invalid.xml")
10
+ RNG_SCHEMA = File.join(root, "schema.rng")
11
+ RNC_SCHEMA = File.join(root, "schema.rnc")
12
+
13
+ def test_default_jar_file_used
14
+ cmd = fakeshell { Jing.new(RNG_SCHEMA).validate(VALID_XML) }
15
+ assert_match /\A'java'\s+ -jar\s+ '#{Jing::DEFAULT_JAR}' \s+/x, cmd
16
+ end
17
+
18
+ def test_jar_file_must_exist
19
+ assert_raises Jing::OptionError, /\bjar\b/ do
20
+ Jing.new(RNG_SCHEMA, :jar => "__oopsy__!").validate(VALID_XML)
21
+ end
22
+ end
23
+
24
+ def test_jar_option
25
+ jar = Tempfile.new "jar"
26
+ cmd = fakeshell { Jing.new(RNG_SCHEMA, :jar => jar.path).validate(VALID_XML) }
27
+ assert_match /\A'java'\s+ -jar\s+ '#{jar.path}' \s+/x, cmd
28
+ end
29
+
30
+ def test_java_option
31
+ java = "/usr/alt/java"
32
+ cmd = fakeshell { Jing.new(RNG_SCHEMA, :java => java).validate(VALID_XML) }
33
+ assert_match /\A'#{java}'\s+/, cmd
34
+ end
35
+
36
+ def test_java_must_exist
37
+ # This should be an OptionError!
38
+ assert_raises Jing::ExecutionError, /\bjava\b/ do
39
+ Jing.new(RNG_SCHEMA, :java => "__no_no_no__").validate(VALID_XML)
40
+ end
41
+ end
42
+
43
+ def test_encoding_option
44
+ enc = "iso-8859-1"
45
+ cmd = fakeshell { Jing.new(RNG_SCHEMA, :encoding => enc).validate(VALID_XML) }
46
+ assert_match /\A'java'\s+ -jar\s+ '#{Jing::DEFAULT_JAR}'\s+ -e\s+ '#{enc}'/x, cmd
47
+ end
48
+
49
+ def test_id_check_option
50
+ cmd = fakeshell { Jing.new(RNG_SCHEMA, :id_check => false).validate(VALID_XML) }
51
+ assert_match /\A'java'\s -jar\s+ '#{Jing::DEFAULT_JAR}'\s+ -i/x, cmd
52
+
53
+ cmd = fakeshell { Jing.new(RNG_SCHEMA, :id_check => true).validate(VALID_XML) }
54
+ refute_match /\b-i\b/x, cmd
55
+
56
+ cmd = fakeshell { Jing.new(RNG_SCHEMA).validate(VALID_XML) }
57
+ refute_match /\b-i\b/x, cmd
58
+ end
59
+
60
+ def test_compact_option
61
+ cmd = fakeshell { Jing.new(RNC_SCHEMA, :compact => true).validate(VALID_XML) }
62
+ assert_match /\A'java'\s -jar\s+ '#{Jing::DEFAULT_JAR}'\s+ -c/x, cmd
63
+
64
+ cmd = fakeshell { Jing.new(RNC_SCHEMA, :compact => false).validate(VALID_XML) }
65
+ refute_match /\b-c\b/, cmd
66
+ end
67
+
68
+ def test_compact_option_when_compact_schema_is_used
69
+ cmd = fakeshell { Jing.new(RNC_SCHEMA).validate(VALID_XML) }
70
+ assert_match /\A'java'\s+ -jar\s+ '#{Jing::DEFAULT_JAR}'\s+ -c/x, cmd
71
+ end
72
+
73
+ def test_relaxng_file_must_exist
74
+ assert_raises Jing::OptionError, /cannot read/ do
75
+ Jing.new("bad_file_name").validate(VALID_XML)
76
+ end
77
+ end
78
+
79
+ def test_instance_xml_file_must_exist
80
+ assert_raises Jing::OptionError, /cannot read/ do
81
+ Jing.new(VALID_XML).validate("bad_file_name")
82
+ end
83
+ end
84
+
85
+ def test_valid_instance_xml_returns_true
86
+ assert Jing.new(RNG_SCHEMA).valid?(VALID_XML)
87
+ end
88
+
89
+ def test_valid_instance_xml_returns_no_errors
90
+ errors = Jing.new(RNG_SCHEMA).validate(VALID_XML)
91
+ assert_equal 0, errors.size
92
+ end
93
+
94
+ def test_invalid_instance_xml_returns_false
95
+ assert !Jing.new(RNG_SCHEMA).valid?(INVALID_XML)
96
+ end
97
+
98
+ def test_invalid_instance_xml_returns_errors
99
+ errors = Jing.new(RNG_SCHEMA).validate(INVALID_XML)
100
+ assert_equal 1, errors.size
101
+
102
+ err = errors[0]
103
+ assert_equal INVALID_XML, err[:source]
104
+ assert_equal 4, err[:line]
105
+ assert_match /\A\d\d?\z/, err[:column].to_s
106
+ assert_match /\bemail\b/, err[:message]
107
+ end
108
+
109
+ def test_successful_exit_status_with_unparsable_output_raises_an_exception
110
+ output = "something bad happened"
111
+ assert_raises Jing::ExecutionError, /#{output}/ do
112
+ fakeshell(:exit => 0, :output => output) { Jing.new(RNG_SCHEMA).validate(VALID_XML) }
113
+ end
114
+ end
115
+
116
+ private
117
+ def fakeshell(options = {})
118
+ output = options.delete(:output) || ""
119
+ exit_code = options.delete(:exit) || 0
120
+
121
+ cmd = nil
122
+ Object.class_eval do
123
+ alias_method "real_tick", "`"
124
+ define_method("`") do |arg|
125
+ cmd = arg
126
+ real_tick %{ruby -e"exit #{exit_code}"} # Just to set $?
127
+ output
128
+ end
129
+ end
130
+
131
+ yield
132
+ cmd.tr %{"}, %{'} # replace Win quotes with *nix
133
+ ensure
134
+ Object.class_eval do
135
+ undef_method "`" #`
136
+ alias_method "`", "real_tick"
137
+ undef_method "real_tick"
138
+ end
139
+ end
140
+ end
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ruby-jing
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Skye Shaw
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2013-09-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: optout
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: 0.0.2
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: 0.0.2
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ~>
32
+ - !ruby/object:Gem::Version
33
+ version: 0.9.2
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ~>
39
+ - !ruby/object:Gem::Version
40
+ version: 0.9.2
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ~>
46
+ - !ruby/object:Gem::Version
47
+ version: '4.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ~>
53
+ - !ruby/object:Gem::Version
54
+ version: '4.0'
55
+ description: |2
56
+ RELAX NG schema validation using Jing, a Java based RELAX NG validator that emits clear,
57
+ detailed validation errors. ruby-jing validates XML documents by wrapping Jing's java
58
+ command-line user interface.
59
+ email: skye.shaw@gmail.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files:
63
+ - README.rdoc
64
+ files:
65
+ - lib/jing-20091111.jar
66
+ - lib/jing.rb
67
+ - test/test_jing.rb
68
+ - README.rdoc
69
+ homepage: http://github.com/sshaw/ruby-jing
70
+ licenses:
71
+ - MIT
72
+ metadata: {}
73
+ post_install_message:
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - '>='
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - '>='
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubyforge_project:
89
+ rubygems_version: 2.0.6
90
+ signing_key:
91
+ specification_version: 4
92
+ summary: RELAX NG schema validation using the Jing CLI
93
+ test_files:
94
+ - test/test_jing.rb