summaryrefslogtreecommitdiff
path: root/ruby_1_8_6/test
diff options
context:
space:
mode:
Diffstat (limited to 'ruby_1_8_6/test')
-rw-r--r--ruby_1_8_6/test/csv/test_csv.rb1753
-rw-r--r--ruby_1_8_6/test/dbm/test_dbm.rb545
-rw-r--r--ruby_1_8_6/test/digest/test_digest.rb120
-rw-r--r--ruby_1_8_6/test/drb/drbtest.rb351
-rw-r--r--ruby_1_8_6/test/drb/ignore_test_drb.rb24
-rw-r--r--ruby_1_8_6/test/drb/test_acl.rb195
-rw-r--r--ruby_1_8_6/test/drb/test_drb.rb301
-rw-r--r--ruby_1_8_6/test/drb/test_drbssl.rb62
-rw-r--r--ruby_1_8_6/test/drb/test_drbunix.rb46
-rw-r--r--ruby_1_8_6/test/drb/ut_array.rb15
-rw-r--r--ruby_1_8_6/test/drb/ut_array_drbssl.rb24
-rw-r--r--ruby_1_8_6/test/drb/ut_array_drbunix.rb15
-rw-r--r--ruby_1_8_6/test/drb/ut_drb.rb160
-rw-r--r--ruby_1_8_6/test/drb/ut_drb_drbssl.rb25
-rw-r--r--ruby_1_8_6/test/drb/ut_drb_drbunix.rb16
-rw-r--r--ruby_1_8_6/test/drb/ut_eval.rb31
-rw-r--r--ruby_1_8_6/test/drb/ut_large.rb38
-rw-r--r--ruby_1_8_6/test/drb/ut_port.rb14
-rw-r--r--ruby_1_8_6/test/drb/ut_safe1.rb15
-rw-r--r--ruby_1_8_6/test/drb/ut_timerholder.rb49
-rw-r--r--ruby_1_8_6/test/erb/test_erb.rb40
-rw-r--r--ruby_1_8_6/test/fileutils/fileasserts.rb67
-rw-r--r--ruby_1_8_6/test/fileutils/test_dryrun.rb25
-rw-r--r--ruby_1_8_6/test/fileutils/test_fileutils.rb1085
-rw-r--r--ruby_1_8_6/test/fileutils/test_nowrite.rb99
-rw-r--r--ruby_1_8_6/test/fileutils/test_verbose.rb25
-rw-r--r--ruby_1_8_6/test/gdbm/test_gdbm.rb692
-rw-r--r--ruby_1_8_6/test/io/nonblock/test_flush.rb28
-rw-r--r--ruby_1_8_6/test/logger/test_logger.rb376
-rw-r--r--ruby_1_8_6/test/monitor/test_monitor.rb161
-rw-r--r--ruby_1_8_6/test/net/http/test_httpheader.rb317
-rw-r--r--ruby_1_8_6/test/net/http/test_https_proxy.rb30
-rw-r--r--ruby_1_8_6/test/net/imap/test_imap.rb11
-rw-r--r--ruby_1_8_6/test/nkf/test_kconv.rb71
-rw-r--r--ruby_1_8_6/test/nkf/test_nkf.rb16
-rw-r--r--ruby_1_8_6/test/openssl/ssl_server.rb81
-rw-r--r--ruby_1_8_6/test/openssl/test_asn1.rb197
-rw-r--r--ruby_1_8_6/test/openssl/test_cipher.rb95
-rw-r--r--ruby_1_8_6/test/openssl/test_digest.rb88
-rw-r--r--ruby_1_8_6/test/openssl/test_hmac.rb34
-rw-r--r--ruby_1_8_6/test/openssl/test_ns_spki.rb59
-rw-r--r--ruby_1_8_6/test/openssl/test_pair.rb144
-rw-r--r--ruby_1_8_6/test/openssl/test_pkcs7.rb154
-rw-r--r--ruby_1_8_6/test/openssl/test_pkey_rsa.rb49
-rw-r--r--ruby_1_8_6/test/openssl/test_ssl.rb286
-rw-r--r--ruby_1_8_6/test/openssl/test_x509cert.rb175
-rw-r--r--ruby_1_8_6/test/openssl/test_x509crl.rb218
-rw-r--r--ruby_1_8_6/test/openssl/test_x509ext.rb74
-rw-r--r--ruby_1_8_6/test/openssl/test_x509name.rb266
-rw-r--r--ruby_1_8_6/test/openssl/test_x509req.rb140
-rw-r--r--ruby_1_8_6/test/openssl/test_x509store.rb218
-rw-r--r--ruby_1_8_6/test/openssl/utils.rb135
-rw-r--r--ruby_1_8_6/test/optparse/test_getopts.rb31
-rw-r--r--ruby_1_8_6/test/optparse/test_noarg.rb57
-rw-r--r--ruby_1_8_6/test/optparse/test_optarg.rb44
-rw-r--r--ruby_1_8_6/test/optparse/test_optparse.rb46
-rw-r--r--ruby_1_8_6/test/optparse/test_placearg.rb45
-rw-r--r--ruby_1_8_6/test/optparse/test_reqarg.rb63
-rw-r--r--ruby_1_8_6/test/ostruct/test_ostruct.rb23
-rw-r--r--ruby_1_8_6/test/pathname/test_pathname.rb486
-rw-r--r--ruby_1_8_6/test/rdoc/parsers/test_parse_c.rb261
-rw-r--r--ruby_1_8_6/test/readline/test_readline.rb84
-rw-r--r--ruby_1_8_6/test/rinda/test_rinda.rb525
-rw-r--r--ruby_1_8_6/test/rss/rss-assertions.rb506
-rw-r--r--ruby_1_8_6/test/rss/rss-testcase.rb286
-rw-r--r--ruby_1_8_6/test/rss/test_1.0.rb249
-rw-r--r--ruby_1_8_6/test/rss/test_2.0.rb390
-rw-r--r--ruby_1_8_6/test/rss/test_accessor.rb103
-rw-r--r--ruby_1_8_6/test/rss/test_content.rb94
-rw-r--r--ruby_1_8_6/test/rss/test_dublincore.rb189
-rw-r--r--ruby_1_8_6/test/rss/test_image.rb191
-rw-r--r--ruby_1_8_6/test/rss/test_inherit.rb41
-rw-r--r--ruby_1_8_6/test/rss/test_maker_0.9.rb399
-rw-r--r--ruby_1_8_6/test/rss/test_maker_1.0.rb431
-rw-r--r--ruby_1_8_6/test/rss/test_maker_2.0.rb667
-rw-r--r--ruby_1_8_6/test/rss/test_maker_content.rb34
-rw-r--r--ruby_1_8_6/test/rss/test_maker_dc.rb145
-rw-r--r--ruby_1_8_6/test/rss/test_maker_image.rb62
-rw-r--r--ruby_1_8_6/test/rss/test_maker_sy.rb43
-rw-r--r--ruby_1_8_6/test/rss/test_maker_taxo.rb81
-rw-r--r--ruby_1_8_6/test/rss/test_maker_trackback.rb41
-rw-r--r--ruby_1_8_6/test/rss/test_maker_xml-stylesheet.rb79
-rw-r--r--ruby_1_8_6/test/rss/test_parser.rb60
-rw-r--r--ruby_1_8_6/test/rss/test_parser_1.0.rb503
-rw-r--r--ruby_1_8_6/test/rss/test_parser_2.0.rb122
-rw-r--r--ruby_1_8_6/test/rss/test_setup_maker_0.9.rb233
-rw-r--r--ruby_1_8_6/test/rss/test_setup_maker_1.0.rb534
-rw-r--r--ruby_1_8_6/test/rss/test_setup_maker_2.0.rb308
-rw-r--r--ruby_1_8_6/test/rss/test_syndication.rb127
-rw-r--r--ruby_1_8_6/test/rss/test_taxonomy.rb160
-rw-r--r--ruby_1_8_6/test/rss/test_to_s.rb440
-rw-r--r--ruby_1_8_6/test/rss/test_trackback.rb135
-rw-r--r--ruby_1_8_6/test/rss/test_version.rb9
-rw-r--r--ruby_1_8_6/test/rss/test_xml-stylesheet.rb108
-rw-r--r--ruby_1_8_6/test/ruby/beginmainend.rb80
-rw-r--r--ruby_1_8_6/test/ruby/endblockwarn.rb12
-rw-r--r--ruby_1_8_6/test/ruby/envutil.rb28
-rw-r--r--ruby_1_8_6/test/ruby/marshaltestlib.rb494
-rw-r--r--ruby_1_8_6/test/ruby/suicide.rb2
-rw-r--r--ruby_1_8_6/test/ruby/test_alias.rb40
-rw-r--r--ruby_1_8_6/test/ruby/test_array.rb145
-rw-r--r--ruby_1_8_6/test/ruby/test_assignment.rb467
-rw-r--r--ruby_1_8_6/test/ruby/test_beginendblock.rb86
-rw-r--r--ruby_1_8_6/test/ruby/test_bignum.rb87
-rw-r--r--ruby_1_8_6/test/ruby/test_call.rb19
-rw-r--r--ruby_1_8_6/test/ruby/test_case.rb49
-rw-r--r--ruby_1_8_6/test/ruby/test_clone.rb28
-rw-r--r--ruby_1_8_6/test/ruby/test_condition.rb16
-rw-r--r--ruby_1_8_6/test/ruby/test_const.rb33
-rw-r--r--ruby_1_8_6/test/ruby/test_defined.rb43
-rw-r--r--ruby_1_8_6/test/ruby/test_dir.rb42
-rw-r--r--ruby_1_8_6/test/ruby/test_env.rb82
-rw-r--r--ruby_1_8_6/test/ruby/test_eval.rb157
-rw-r--r--ruby_1_8_6/test/ruby/test_exception.rb187
-rw-r--r--ruby_1_8_6/test/ruby/test_file.rb108
-rw-r--r--ruby_1_8_6/test/ruby/test_float.rb113
-rw-r--r--ruby_1_8_6/test/ruby/test_gc.rb30
-rw-r--r--ruby_1_8_6/test/ruby/test_hash.rb74
-rw-r--r--ruby_1_8_6/test/ruby/test_ifunless.rb14
-rw-r--r--ruby_1_8_6/test/ruby/test_io.rb11
-rw-r--r--ruby_1_8_6/test/ruby/test_iterator.rb477
-rw-r--r--ruby_1_8_6/test/ruby/test_marshal.rb48
-rw-r--r--ruby_1_8_6/test/ruby/test_math.rb12
-rw-r--r--ruby_1_8_6/test/ruby/test_method.rb53
-rw-r--r--ruby_1_8_6/test/ruby/test_objectspace.rb36
-rw-r--r--ruby_1_8_6/test/ruby/test_pack.rb60
-rw-r--r--ruby_1_8_6/test/ruby/test_path.rb224
-rw-r--r--ruby_1_8_6/test/ruby/test_pipe.rb18
-rw-r--r--ruby_1_8_6/test/ruby/test_proc.rb89
-rw-r--r--ruby_1_8_6/test/ruby/test_process.rb41
-rw-r--r--ruby_1_8_6/test/ruby/test_rand.rb131
-rw-r--r--ruby_1_8_6/test/ruby/test_range.rb17
-rw-r--r--ruby_1_8_6/test/ruby/test_readpartial.rb74
-rw-r--r--ruby_1_8_6/test/ruby/test_settracefunc.rb138
-rw-r--r--ruby_1_8_6/test/ruby/test_signal.rb68
-rw-r--r--ruby_1_8_6/test/ruby/test_string.rb19
-rw-r--r--ruby_1_8_6/test/ruby/test_stringchar.rb166
-rw-r--r--ruby_1_8_6/test/ruby/test_struct.rb24
-rw-r--r--ruby_1_8_6/test/ruby/test_super.rb134
-rw-r--r--ruby_1_8_6/test/ruby/test_symbol.rb77
-rw-r--r--ruby_1_8_6/test/ruby/test_system.rb64
-rw-r--r--ruby_1_8_6/test/ruby/test_time.rb74
-rw-r--r--ruby_1_8_6/test/ruby/test_trace.rb21
-rw-r--r--ruby_1_8_6/test/ruby/test_variable.rb53
-rw-r--r--ruby_1_8_6/test/ruby/test_whileuntil.rb77
-rw-r--r--ruby_1_8_6/test/ruby/ut_eof.rb128
-rw-r--r--ruby_1_8_6/test/runner.rb7
-rw-r--r--ruby_1_8_6/test/sdbm/test_sdbm.rb534
-rw-r--r--ruby_1_8_6/test/soap/asp.net/hello.wsdl96
-rw-r--r--ruby_1_8_6/test/soap/asp.net/test_aspdotnet.rb111
-rw-r--r--ruby_1_8_6/test/soap/calc/calc.rb17
-rw-r--r--ruby_1_8_6/test/soap/calc/calc2.rb29
-rw-r--r--ruby_1_8_6/test/soap/calc/server.cgi13
-rw-r--r--ruby_1_8_6/test/soap/calc/server.rb17
-rw-r--r--ruby_1_8_6/test/soap/calc/server2.rb20
-rw-r--r--ruby_1_8_6/test/soap/calc/test_calc.rb49
-rw-r--r--ruby_1_8_6/test/soap/calc/test_calc2.rb53
-rw-r--r--ruby_1_8_6/test/soap/calc/test_calc_cgi.rb69
-rw-r--r--ruby_1_8_6/test/soap/fault/test_customfault.rb58
-rw-r--r--ruby_1_8_6/test/soap/header/server.cgi119
-rw-r--r--ruby_1_8_6/test/soap/header/test_authheader.rb240
-rw-r--r--ruby_1_8_6/test/soap/header/test_authheader_cgi.rb121
-rw-r--r--ruby_1_8_6/test/soap/header/test_simplehandler.rb116
-rw-r--r--ruby_1_8_6/test/soap/helloworld/hw_s.rb16
-rw-r--r--ruby_1_8_6/test/soap/helloworld/test_helloworld.rb40
-rw-r--r--ruby_1_8_6/test/soap/marshal/test_digraph.rb56
-rw-r--r--ruby_1_8_6/test/soap/marshal/test_marshal.rb26
-rw-r--r--ruby_1_8_6/test/soap/marshal/test_struct.rb47
-rw-r--r--ruby_1_8_6/test/soap/ssl/README1
-rw-r--r--ruby_1_8_6/test/soap/ssl/ca.cert23
-rw-r--r--ruby_1_8_6/test/soap/ssl/client.cert19
-rw-r--r--ruby_1_8_6/test/soap/ssl/client.key15
-rw-r--r--ruby_1_8_6/test/soap/ssl/server.cert19
-rw-r--r--ruby_1_8_6/test/soap/ssl/server.key15
-rw-r--r--ruby_1_8_6/test/soap/ssl/sslsvr.rb57
-rw-r--r--ruby_1_8_6/test/soap/ssl/subca.cert21
-rw-r--r--ruby_1_8_6/test/soap/ssl/test_ssl.rb204
-rw-r--r--ruby_1_8_6/test/soap/struct/test_struct.rb77
-rw-r--r--ruby_1_8_6/test/soap/swa/test_file.rb73
-rw-r--r--ruby_1_8_6/test/soap/test_basetype.rb970
-rw-r--r--ruby_1_8_6/test/soap/test_envelopenamespace.rb92
-rw-r--r--ruby_1_8_6/test/soap/test_httpconfigloader.rb39
-rw-r--r--ruby_1_8_6/test/soap/test_mapping.rb59
-rw-r--r--ruby_1_8_6/test/soap/test_no_indent.rb86
-rw-r--r--ruby_1_8_6/test/soap/test_property.rb424
-rw-r--r--ruby_1_8_6/test/soap/test_soapelement.rb122
-rw-r--r--ruby_1_8_6/test/soap/test_streamhandler.rb209
-rw-r--r--ruby_1_8_6/test/soap/test_styleuse.rb333
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/README.txt2
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/calc.wsdl126
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/document.wsdl54
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/echo_version.rb20
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/simpletype.wsdl63
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/test_calc.rb100
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/test_document.rb78
-rw-r--r--ruby_1_8_6/test/soap/wsdlDriver/test_simpletype.rb87
-rw-r--r--ruby_1_8_6/test/socket/test_nonblock.rb179
-rw-r--r--ruby_1_8_6/test/socket/test_socket.rb83
-rw-r--r--ruby_1_8_6/test/socket/test_unix.rb141
-rw-r--r--ruby_1_8_6/test/stringio/test_stringio.rb43
-rw-r--r--ruby_1_8_6/test/strscan/test_stringscanner.rb571
-rw-r--r--ruby_1_8_6/test/testunit/collector/test_dir.rb406
-rw-r--r--ruby_1_8_6/test/testunit/collector/test_objectspace.rb98
-rw-r--r--ruby_1_8_6/test/testunit/runit/test_assert.rb402
-rw-r--r--ruby_1_8_6/test/testunit/runit/test_testcase.rb91
-rw-r--r--ruby_1_8_6/test/testunit/runit/test_testresult.rb144
-rw-r--r--ruby_1_8_6/test/testunit/runit/test_testsuite.rb49
-rw-r--r--ruby_1_8_6/test/testunit/test_assertions.rb528
-rw-r--r--ruby_1_8_6/test/testunit/test_error.rb26
-rw-r--r--ruby_1_8_6/test/testunit/test_failure.rb33
-rw-r--r--ruby_1_8_6/test/testunit/test_testcase.rb275
-rw-r--r--ruby_1_8_6/test/testunit/test_testresult.rb104
-rw-r--r--ruby_1_8_6/test/testunit/test_testsuite.rb129
-rw-r--r--ruby_1_8_6/test/testunit/util/test_backtracefilter.rb41
-rw-r--r--ruby_1_8_6/test/testunit/util/test_observable.rb102
-rw-r--r--ruby_1_8_6/test/testunit/util/test_procwrapper.rb36
-rw-r--r--ruby_1_8_6/test/thread/test_thread.rb67
-rw-r--r--ruby_1_8_6/test/uri/test_common.rb56
-rw-r--r--ruby_1_8_6/test/uri/test_ftp.rb42
-rw-r--r--ruby_1_8_6/test/uri/test_generic.rb698
-rw-r--r--ruby_1_8_6/test/uri/test_http.rb63
-rw-r--r--ruby_1_8_6/test/uri/test_ldap.rb100
-rw-r--r--ruby_1_8_6/test/uri/test_mailto.rb122
-rw-r--r--ruby_1_8_6/test/webrick/test_cgi.rb78
-rw-r--r--ruby_1_8_6/test/webrick/test_cookie.rb104
-rw-r--r--ruby_1_8_6/test/webrick/test_filehandler.rb65
-rw-r--r--ruby_1_8_6/test/webrick/test_httpauth.rb82
-rw-r--r--ruby_1_8_6/test/webrick/test_httprequest.rb272
-rw-r--r--ruby_1_8_6/test/webrick/test_httpserver.rb260
-rw-r--r--ruby_1_8_6/test/webrick/test_httputils.rb96
-rw-r--r--ruby_1_8_6/test/webrick/test_httpversion.rb40
-rw-r--r--ruby_1_8_6/test/webrick/test_server.rb64
-rw-r--r--ruby_1_8_6/test/webrick/utils.rb40
-rw-r--r--ruby_1_8_6/test/webrick/webrick.cgi36
-rw-r--r--ruby_1_8_6/test/wsdl/any/any.wsdl50
-rw-r--r--ruby_1_8_6/test/wsdl/any/expectedDriver.rb54
-rw-r--r--ruby_1_8_6/test/wsdl/any/expectedEcho.rb14
-rw-r--r--ruby_1_8_6/test/wsdl/any/expectedService.rb52
-rw-r--r--ruby_1_8_6/test/wsdl/any/test_any.rb58
-rw-r--r--ruby_1_8_6/test/wsdl/axisArray/axisArray.wsdl60
-rw-r--r--ruby_1_8_6/test/wsdl/axisArray/itemList.rb27
-rw-r--r--ruby_1_8_6/test/wsdl/axisArray/test_axisarray.rb69
-rw-r--r--ruby_1_8_6/test/wsdl/datetime/DatetimeService.rb44
-rw-r--r--ruby_1_8_6/test/wsdl/datetime/datetime.rb0
-rw-r--r--ruby_1_8_6/test/wsdl/datetime/datetime.wsdl45
-rw-r--r--ruby_1_8_6/test/wsdl/datetime/datetimeServant.rb21
-rw-r--r--ruby_1_8_6/test/wsdl/datetime/test_datetime.rb82
-rw-r--r--ruby_1_8_6/test/wsdl/document/document.wsdl74
-rw-r--r--ruby_1_8_6/test/wsdl/document/echo.rb92
-rw-r--r--ruby_1_8_6/test/wsdl/document/number.wsdl54
-rw-r--r--ruby_1_8_6/test/wsdl/document/ping_nosoapaction.wsdl66
-rw-r--r--ruby_1_8_6/test/wsdl/document/test_nosoapaction.rb109
-rw-r--r--ruby_1_8_6/test/wsdl/document/test_number.rb99
-rw-r--r--ruby_1_8_6/test/wsdl/document/test_rpc.rb177
-rw-r--r--ruby_1_8_6/test/wsdl/emptycomplextype.wsdl31
-rw-r--r--ruby_1_8_6/test/wsdl/map/map.wsdl92
-rw-r--r--ruby_1_8_6/test/wsdl/map/map.xml43
-rw-r--r--ruby_1_8_6/test/wsdl/map/test_map.rb99
-rw-r--r--ruby_1_8_6/test/wsdl/marshal/person.wsdl21
-rw-r--r--ruby_1_8_6/test/wsdl/marshal/person_org.rb22
-rw-r--r--ruby_1_8_6/test/wsdl/marshal/test_wsdlmarshal.rb80
-rw-r--r--ruby_1_8_6/test/wsdl/multiplefault.wsdl68
-rw-r--r--ruby_1_8_6/test/wsdl/qualified/lp.rb0
-rw-r--r--ruby_1_8_6/test/wsdl/qualified/lp.wsdl47
-rw-r--r--ruby_1_8_6/test/wsdl/qualified/lp.xsd26
-rw-r--r--ruby_1_8_6/test/wsdl/qualified/np.wsdl50
-rw-r--r--ruby_1_8_6/test/wsdl/qualified/test_qualified.rb154
-rw-r--r--ruby_1_8_6/test/wsdl/qualified/test_unqualified.rb143
-rw-r--r--ruby_1_8_6/test/wsdl/raa/RAA.rb243
-rw-r--r--ruby_1_8_6/test/wsdl/raa/RAAServant.rb99
-rw-r--r--ruby_1_8_6/test/wsdl/raa/RAAService.rb100
-rw-r--r--ruby_1_8_6/test/wsdl/raa/README.txt8
-rw-r--r--ruby_1_8_6/test/wsdl/raa/raa.wsdl264
-rw-r--r--ruby_1_8_6/test/wsdl/raa/server.rb103
-rw-r--r--ruby_1_8_6/test/wsdl/raa/test_raa.rb71
-rw-r--r--ruby_1_8_6/test/wsdl/ref/expectedProduct.rb90
-rw-r--r--ruby_1_8_6/test/wsdl/ref/product.wsdl86
-rw-r--r--ruby_1_8_6/test/wsdl/ref/test_ref.rb54
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/echoDriver.rb55
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/echo_serviceClient.rb23
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/rpc.wsdl75
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/test-rpc-lit.wsdl364
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/test-rpc-lit12.wsdl455
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/test_rpc.rb118
-rw-r--r--ruby_1_8_6/test/wsdl/rpc/test_rpc_lit.rb399
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/expectedClient.rb34
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/expectedDriver.rb62
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/expectedEchoVersion.rb23
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/expectedServant.rb32
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/expectedService.rb60
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/rpc.wsdl80
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/rpc/test_rpc.rb62
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/simpletype.wsdl95
-rw-r--r--ruby_1_8_6/test/wsdl/simpletype/test_simpletype.rb99
-rw-r--r--ruby_1_8_6/test/wsdl/soap/soapbodyparts.wsdl103
-rw-r--r--ruby_1_8_6/test/wsdl/soap/test_soapbodyparts.rb79
-rw-r--r--ruby_1_8_6/test/wsdl/test_emptycomplextype.rb21
-rw-r--r--ruby_1_8_6/test/wsdl/test_fault.rb51
-rw-r--r--ruby_1_8_6/test/wsdl/test_multiplefault.rb39
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/bug_bool.expected3
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/bug_bool.xml8
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/bug_cdata.expected3
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/bug_cdata.xml8
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/bug_covert.expected10
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/bug_covert.xml6
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/datetime_iso8601.xml8
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/fault.xml16
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/value.expected7
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/value.xml22
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/xml1.expected243
-rw-r--r--ruby_1_8_6/test/xmlrpc/data/xml1.xml1
-rw-r--r--ruby_1_8_6/test/xmlrpc/test_datetime.rb159
-rw-r--r--ruby_1_8_6/test/xmlrpc/test_features.rb48
-rw-r--r--ruby_1_8_6/test/xmlrpc/test_marshal.rb93
-rw-r--r--ruby_1_8_6/test/xmlrpc/test_parser.rb85
-rw-r--r--ruby_1_8_6/test/xmlrpc/test_webrick_server.rb98
-rw-r--r--ruby_1_8_6/test/xmlrpc/webrick_testing.rb37
-rw-r--r--ruby_1_8_6/test/xsd/codegen/test_classdef.rb214
-rw-r--r--ruby_1_8_6/test/xsd/noencoding.xml4
-rw-r--r--ruby_1_8_6/test/xsd/test_noencoding.rb32
-rw-r--r--ruby_1_8_6/test/xsd/test_xmlschemaparser.rb22
-rw-r--r--ruby_1_8_6/test/xsd/test_xsd.rb1511
-rw-r--r--ruby_1_8_6/test/xsd/xmlschema.xml12
-rw-r--r--ruby_1_8_6/test/yaml/test_yaml.rb1284
-rw-r--r--ruby_1_8_6/test/zlib/test_zlib.rb57
325 files changed, 43029 insertions, 0 deletions
diff --git a/ruby_1_8_6/test/csv/test_csv.rb b/ruby_1_8_6/test/csv/test_csv.rb
new file mode 100644
index 0000000000..1db540921b
--- /dev/null
+++ b/ruby_1_8_6/test/csv/test_csv.rb
@@ -0,0 +1,1753 @@
+require 'test/unit'
+require 'tempfile'
+require 'fileutils'
+
+require 'csv'
+
+class CSV
+ class StreamBuf
+ # Let buffer work hard.
+ remove_const("BufSize")
+ BufSize = 2
+ end
+end
+
+
+module CSVTestSupport
+ def d(data)
+ data
+ end
+end
+
+
+class TestCSV < Test::Unit::TestCase
+ file = Tempfile.new("crlf")
+ file << "\n"
+ file.open
+ file.binmode
+ RSEP = file.read
+ file.close
+
+ include CSVTestSupport
+
+ class << self
+ include CSVTestSupport
+ end
+
+ @@simpleCSVData = {
+ [nil] => '',
+ [''] => '""',
+ [nil, nil] => ',',
+ [nil, nil, nil] => ',,',
+ ['foo'] => 'foo',
+ [','] => '","',
+ [',', ','] => '",",","',
+ [';'] => ';',
+ [';', ';'] => ';,;',
+ ["\"\r", "\"\r"] => "\"\"\"\r\",\"\"\"\r\"",
+ ["\"\n", "\"\n"] => "\"\"\"\n\",\"\"\"\n\"",
+ ["\t"] => "\t",
+ ["\t", "\t"] => "\t,\t",
+ ['foo', 'bar'] => 'foo,bar',
+ ['foo', '"bar"', 'baz'] => 'foo,"""bar""",baz',
+ ['foo', 'foo,bar', 'baz'] => 'foo,"foo,bar",baz',
+ ['foo', '""', 'baz'] => 'foo,"""""",baz',
+ ['foo', '', 'baz'] => 'foo,"",baz',
+ ['foo', nil, 'baz'] => 'foo,,baz',
+ [nil, 'foo', 'bar'] => ',foo,bar',
+ ['foo', 'bar', nil] => 'foo,bar,',
+ ['foo', "\r", 'baz'] => "foo,\"\r\",baz",
+ ['foo', "\n", 'baz'] => "foo,\"\n\",baz",
+ ['foo', "\r\n\r", 'baz'] => "foo,\"\r\n\r\",baz",
+ ['foo', "\r\n", 'baz'] => "foo,\"\r\n\",baz",
+ ['foo', "\r.\n", 'baz'] => "foo,\"\r.\n\",baz",
+ ['foo', "\r\n\n", 'baz'] => "foo,\"\r\n\n\",baz",
+ ['foo', '"', 'baz'] => 'foo,"""",baz',
+ }
+
+ @@fullCSVData = {
+ [d(nil)] => '',
+ [d('')] => '""',
+ [d(nil), d(nil)] => ',',
+ [d(nil), d(nil), d(nil)] => ',,',
+ [d('foo')] => 'foo',
+ [d('foo'), d('bar')] => 'foo,bar',
+ [d('foo'), d('"bar"'), d('baz')] => 'foo,"""bar""",baz',
+ [d('foo'), d('foo,bar'), d('baz')] => 'foo,"foo,bar",baz',
+ [d('foo'), d('""'), d('baz')] => 'foo,"""""",baz',
+ [d('foo'), d(''), d('baz')] => 'foo,"",baz',
+ [d('foo'), d(nil), d('baz')] => 'foo,,baz',
+ [d('foo'), d("\r"), d('baz')] => "foo,\"\r\",baz",
+ [d('foo'), d("\n"), d('baz')] => "foo,\"\n\",baz",
+ [d('foo'), d("\r\n"), d('baz')] => "foo,\"\r\n\",baz",
+ [d('foo'), d("\r.\n"), d('baz')] => "foo,\"\r.\n\",baz",
+ [d('foo'), d("\r\n\n"), d('baz')] => "foo,\"\r\n\n\",baz",
+ [d('foo'), d('"'), d('baz')] => 'foo,"""",baz',
+ }
+
+ @@fullCSVDataArray = @@fullCSVData.collect { |key, value| key }
+
+ def ssv2csv(ssvStr, row_sep = nil)
+ sepConv(ssvStr, ?;, ?,, row_sep)
+ end
+
+ def csv2ssv(csvStr, row_sep = nil)
+ sepConv(csvStr, ?,, ?;, row_sep)
+ end
+
+ def tsv2csv(tsvStr, row_sep = nil)
+ sepConv(tsvStr, ?\t, ?,, row_sep)
+ end
+
+ def csv2tsv(csvStr, row_sep = nil)
+ sepConv(csvStr, ?,, ?\t, row_sep)
+ end
+
+ def sepConv(srcStr, srcSep, destSep, row_sep = nil)
+ rows = []
+ cols, idx = CSV.parse_row(srcStr, 0, rows, srcSep, row_sep)
+ destStr = ''
+ cols = CSV.generate_row(rows, rows.size, destStr, destSep, row_sep)
+ destStr
+ end
+
+public
+
+ def setup
+ @tmpdir = File.join(Dir.tmpdir, "ruby_test_csv_tmp_#{$$}")
+ Dir.mkdir(@tmpdir)
+ @infile = File.join(@tmpdir, 'in.csv')
+ @infiletsv = File.join(@tmpdir, 'in.tsv')
+ @emptyfile = File.join(@tmpdir, 'empty.csv')
+ @outfile = File.join(@tmpdir, 'out.csv')
+ @bomfile = File.join(@tmpdir, "bom.csv")
+ @macfile = File.join(@tmpdir, "mac.csv")
+
+ CSV.open(@infile, "wb") do |writer|
+ @@fullCSVDataArray.each do |row|
+ writer.add_row(row)
+ end
+ end
+
+ CSV.open(@infiletsv, "wb", ?\t) do |writer|
+ @@fullCSVDataArray.each do |row|
+ writer.add_row(row)
+ end
+ end
+
+ CSV.generate(@emptyfile) do |writer|
+ # Create empty file.
+ end
+
+ File.open(@bomfile, "wb") do |f|
+ f.write("\357\273\277\"foo\"\r\n\"bar\"\r\n")
+ end
+
+ File.open(@macfile, "wb") do |f|
+ f.write("\"Avenches\",\"aus Umgebung\"\r\"Bad Hersfeld\",\"Ausgrabung\"")
+ end
+ end
+
+ def teardown
+ FileUtils.rm_rf(@tmpdir)
+ end
+
+ #### CSV::Reader unit test
+
+ def test_Reader_each
+ file = File.open(@infile, "rb")
+ begin
+ reader = CSV::Reader.create(file)
+ expectedArray = @@fullCSVDataArray.dup
+ first = true
+ ret = reader.each { |row|
+ if first
+ assert_instance_of(Array, row)
+ first = false
+ end
+ expected = expectedArray.shift
+ assert_equal(expected, row)
+ }
+ assert_nil(ret, "Return is nil")
+ assert(expectedArray.empty?)
+ ensure
+ file.close
+ end
+
+ # Illegal format.
+ reader = CSV::Reader.create("a,b\r\na,b,\"c\"\ra")
+ assert_raises(CSV::IllegalFormatError) do
+ reader.each do |row|
+ end
+ end
+
+ reader = CSV::Reader.create("a,b\r\n\"")
+ assert_raises(CSV::IllegalFormatError) do
+ reader.each do |row|
+ end
+ end
+ end
+
+ def test_Reader_shift
+ file = File.open(@infile, "rb")
+ begin
+ reader = CSV::Reader.create(file)
+ first = true
+ checked = 0
+ @@fullCSVDataArray.each do |expected|
+ actual = reader.shift
+ if first
+ assert_instance_of(Array, actual)
+ first = false
+ end
+ assert_equal(expected, actual)
+ checked += 1
+ end
+ assert(checked == @@fullCSVDataArray.size)
+ ensure
+ file.close
+ end
+
+ # Illegal format.
+ reader = CSV::Reader.create("a,b\r\na,b,\"c\"\ra")
+ assert_raises(CSV::IllegalFormatError) do
+ reader.shift
+ reader.shift
+ end
+
+ reader = CSV::Reader.create("a,b\r\na,b,\"c\"\ra")
+ assert_raises(CSV::IllegalFormatError) do
+ reader.shift
+ reader.shift
+ end
+ end
+
+ def test_Reader_getRow
+ if CSV::Reader.respond_to?(:allocate)
+ obj = CSV::Reader.allocate
+ assert_raises(NotImplementedError) do
+ row = []
+ obj.shift
+ end
+ end
+ end
+
+ def test_IOReader_close_on_terminate
+ f = File.open(@infile, "r")
+ reader = CSV::IOReader.create(f)
+ reader.close
+ assert(!f.closed?)
+ f.close
+
+ f = File.open(@infile, "r")
+ writer = CSV::IOReader.create(f)
+ writer.close_on_terminate
+ writer.close
+ assert(f.closed?)
+ end
+
+ def test_Reader_close
+ f = File.open(@infile, "r")
+ reader = CSV::IOReader.create(f)
+ reader.close_on_terminate
+ reader.close
+ assert(f.closed?)
+ end
+
+ def test_Reader_s_new
+ assert_raises(RuntimeError) do
+ CSV::Reader.new(nil)
+ end
+ end
+
+ def test_Reader_s_create
+ reader = CSV::Reader.create("abc")
+ assert_instance_of(CSV::StringReader, reader, "With a String")
+
+ file = File.open(@infile, "rb")
+ reader = CSV::Reader.create(file)
+ assert_instance_of(CSV::IOReader, reader, 'With an IO')
+
+ obj = Object.new
+ def obj.sysread(size)
+ "abc"
+ end
+ def obj.read(size)
+ "abc"
+ end
+ reader = CSV::Reader.create(obj)
+ assert_instance_of(CSV::IOReader, reader, "With not an IO or String")
+
+ # No need to test Tempfile because it's a pseudo IO. I test this here
+ # fors other tests.
+ reader = CSV::Reader.create(Tempfile.new("in.csv"))
+ assert_instance_of(CSV::IOReader, reader, "With an pseudo IO.")
+ file.close
+ end
+
+ def test_IOReader_s_create_binmode
+ file = File.open(@outfile, "wb")
+ file << "\"\r\n\",\"\r\",\"\n\"\r1,2,3"
+ file.close
+
+ file = File.open(@outfile, "rb")
+ begin
+ reader = CSV::IOReader.new(file, ?,, ?\r)
+ assert_equal(["\r\n", "\r", "\n"], reader.shift.to_a)
+ assert_equal(["1", "2", "3"], reader.shift.to_a)
+ reader.close
+ ensure
+ file.close
+ end
+
+ file = File.open(@outfile, "r") # not "rb"
+ begin
+ lfincell = (RSEP == "\n" ? "\r\n" : "\n")
+ reader = CSV::IOReader.new(file, ?,, ?\r)
+ assert_equal([lfincell, "\r", "\n"], reader.shift.to_a)
+ assert_equal(["1", "2", "3"], reader.shift.to_a)
+ reader.close
+ ensure
+ file.close
+ end
+ end
+
+ def test_Reader_s_parse
+ ret = CSV::Reader.parse("a,b,c") { |row|
+ assert_instance_of(Array, row, "Block parameter")
+ }
+ assert_nil(ret, "Return is nil")
+
+ ret = CSV::Reader.parse("a;b;c", ?;) { |row|
+ assert_instance_of(Array, row, "Block parameter")
+ }
+
+ file = Tempfile.new("in.csv")
+ file << "a,b,c"
+ file.open
+ ret = CSV::Reader.parse(file) { |row|
+ assert_instance_of(Array, row, "Block parameter")
+ }
+ assert_nil(ret, "Return is nil")
+
+ file = Tempfile.new("in.csv")
+ file << "a,b,c"
+ file.open
+ ret = CSV::Reader.parse(file, ?,) { |row|
+ assert_instance_of(Array, row, "Block parameter")
+ }
+
+ # Illegal format.
+ assert_raises(CSV::IllegalFormatError) do
+ CSV::Reader.parse("a,b\r\na,b,\"c\"\ra") do |row|
+ end
+ end
+
+ assert_raises(CSV::IllegalFormatError) do
+ CSV::Reader.parse("a,b\r\na,b\"") do |row|
+ end
+ end
+ end
+
+
+ #### CSV::Writer unit test
+
+ def test_Writer_s_new
+ assert_raises(RuntimeError) do
+ CSV::Writer.new(nil)
+ end
+ end
+
+ def test_Writer_s_generate
+ ret = CSV::Writer.generate(STDOUT) { |writer|
+ assert_instance_of(CSV::BasicWriter, writer, "Block parameter")
+ }
+
+ ret = CSV::Writer.generate(STDOUT, ?;) { |writer|
+ assert_instance_of(CSV::BasicWriter, writer, "Block parameter")
+ }
+
+ assert_nil(ret, "Return is nil")
+ end
+
+ def test_Writer_s_create
+ writer = CSV::Writer.create(STDERR)
+ assert_instance_of(CSV::BasicWriter, writer, "String")
+
+ writer = CSV::Writer.create(STDERR, ?;)
+ assert_instance_of(CSV::BasicWriter, writer, "String")
+
+ writer = CSV::Writer.create(Tempfile.new("out.csv"))
+ assert_instance_of(CSV::BasicWriter, writer, "IO")
+ end
+
+ def test_Writer_LSHIFT # '<<'
+ file = Tempfile.new("out.csv")
+ CSV::Writer.generate(file) do |writer|
+ ret = writer << ['a', 'b', 'c']
+ assert_instance_of(CSV::BasicWriter, ret, 'Return is self')
+
+ writer << [nil, 'e', 'f'] << [nil, nil, '']
+ end
+ file.open
+ file.binmode
+ str = file.read
+ assert_equal("a,b,c#{RSEP},e,f#{RSEP},,\"\"#{RSEP}", str, 'Normal')
+
+ file = Tempfile.new("out2.csv")
+ CSV::Writer.generate(file) do |writer|
+ ret = writer << [d('a'), d('b'), d('c')]
+ assert_instance_of(CSV::BasicWriter, ret, 'Return is self')
+
+ writer << [d(nil), d('e'), d('f')] << [d(nil), d(nil), d('')]
+ end
+ file.open
+ file.binmode
+ str = file.read
+ assert_equal("a,b,c#{RSEP},e,f#{RSEP},,\"\"#{RSEP}", str, 'Normal')
+ end
+
+ def test_Writer_add_row
+ file = Tempfile.new("out.csv")
+ CSV::Writer.generate(file) do |writer|
+ ret = writer.add_row(
+ [d('a'), d('b'), d('c')])
+ assert_instance_of(CSV::BasicWriter, ret, 'Return is self')
+
+ writer.add_row(
+ [d(nil), d('e'), d('f')]
+ ).add_row(
+ [d(nil), d(nil), d('')]
+ )
+ end
+ file.open
+ file.binmode
+ str = file.read
+ assert_equal("a,b,c#{RSEP},e,f#{RSEP},,\"\"#{RSEP}", str, 'Normal')
+ end
+
+ def test_Writer_close
+ f = File.open(@outfile, "w")
+ writer = CSV::BasicWriter.create(f)
+ writer.close_on_terminate
+ writer.close
+ assert(f.closed?)
+ end
+
+ def test_BasicWriter_close_on_terminate
+ f = File.open(@outfile, "w")
+ writer = CSV::BasicWriter.create(f)
+ writer.close
+ assert(!f.closed?)
+ f.close
+
+ f = File.open(@outfile, "w")
+ writer = CSV::BasicWriter.new(f)
+ writer.close_on_terminate
+ writer.close
+ assert(f.closed?)
+ end
+
+ def test_BasicWriter_s_create_binmode
+ file = File.open(@outfile, "w") # not "wb"
+ begin
+ writer = CSV::BasicWriter.new(file, ?,, ?\r)
+ writer << ["\r\n", "\r", "\n"]
+ writer << ["1", "2", "3"]
+ writer.close
+ ensure
+ file.close
+ end
+
+ file = File.open(@outfile, "rb")
+ str = file.read
+ file.close
+ assert_equal("\"\r#{RSEP}\",\"\r\",\"#{RSEP}\"\r1,2,3\r", str)
+ end
+
+ #### CSV unit test
+
+ def test_s_open_reader
+ assert_raises(ArgumentError, 'Illegal mode') do
+ CSV.open("temp", "a")
+ end
+
+ assert_raises(ArgumentError, 'Illegal mode') do
+ CSV.open("temp", "a", ?;)
+ end
+
+ reader = CSV.open(@infile, "r")
+ assert_instance_of(CSV::IOReader, reader)
+ reader.close
+
+ reader = CSV.open(@infile, "rb")
+ assert_instance_of(CSV::IOReader, reader)
+ reader.close
+
+ reader = CSV.open(@infile, "r", ?;)
+ assert_instance_of(CSV::IOReader, reader)
+ reader.close
+
+ CSV.open(@infile, "r") do |row|
+ assert_instance_of(Array, row)
+ break
+ end
+
+ CSV.open(@infiletsv, "r", ?\t) do |row|
+ assert_instance_of(Array, row)
+ break
+ end
+
+ assert_raises(Errno::ENOENT) do
+ CSV.open("NoSuchFileOrDirectory", "r")
+ end
+
+ assert_raises(Errno::ENOENT) do
+ CSV.open("NoSuchFileOrDirectory", "r", ?;)
+ end
+
+ # Illegal format.
+ File.open(@outfile, "wb") do |f|
+ f << "a,b\r\na,b,\"c\"\ra"
+ end
+ assert_raises(CSV::IllegalFormatError) do
+ CSV.open(@outfile, "r") do |row|
+ end
+ end
+
+ File.open(@outfile, "wb") do |f|
+ f << "a,b\r\na,b\""
+ end
+ assert_raises(CSV::IllegalFormatError) do
+ CSV.open(@outfile, "r") do |row|
+ end
+ end
+
+ CSV.open(@emptyfile, "r") do |row|
+ assert_fail("Must not reach here")
+ end
+ end
+
+ def test_s_parse
+ result = CSV.parse(File.read(@infile))
+ assert_instance_of(Array, result)
+ assert_instance_of(Array, result[0])
+
+ result = CSV.parse(File.read(@infile))
+ assert_instance_of(Array, result)
+ assert_instance_of(Array, result[0])
+
+ assert_equal([], CSV.parse(""))
+ assert_equal([[nil]], CSV.parse("\n"))
+
+ CSV.parse(File.read(@infile)) do |row|
+ assert_instance_of(Array, row)
+ break
+ end
+
+ CSV.parse(File.read(@infiletsv), ?\t) do |row|
+ assert_instance_of(Array, row)
+ break
+ end
+
+ CSV.parse("") do |row|
+ assert(false)
+ end
+
+ count = 0
+ CSV.parse("\n") do |row|
+ assert_equal([nil], row)
+ count += 1
+ end
+ assert_equal(1, count)
+
+ assert_equal([["a|b-c|d"]], CSV.parse("a|b-c|d"))
+ assert_equal([["a", "b"], ["c", "d"]], CSV.parse("a|b-c|d", "|", "-"))
+ end
+
+ def test_s_open_writer
+ writer = CSV.open(@outfile, "w")
+ assert_instance_of(CSV::BasicWriter, writer)
+ writer.close
+
+ writer = CSV.open(@outfile, "wb")
+ assert_instance_of(CSV::BasicWriter, writer)
+ writer.close
+
+ writer = CSV.open(@outfile, "wb", ?;)
+ assert_instance_of(CSV::BasicWriter, writer)
+ writer.close
+
+ CSV.open(@outfile, "w") do |writer|
+ assert_instance_of(CSV::BasicWriter, writer)
+ end
+
+ CSV.open(@outfile, "w", ?;) do |writer|
+ assert_instance_of(CSV::BasicWriter, writer)
+ end
+
+ begin
+ CSV.open(@tmpdir, "w")
+ assert(false)
+ rescue Exception => ex
+ assert(ex.is_a?(Errno::EEXIST) || ex.is_a?(Errno::EISDIR) || ex.is_a?(Errno::EACCES))
+ end
+ end
+
+ def test_s_generate
+ writer = CSV.generate(@outfile)
+ assert_instance_of(CSV::BasicWriter, writer)
+ writer.close
+
+ writer = CSV.generate(@outfile, ?;)
+ assert_instance_of(CSV::BasicWriter, writer)
+ writer.close
+
+ CSV.generate(@outfile) do |writer|
+ assert_instance_of(CSV::BasicWriter, writer)
+ end
+
+ CSV.generate(@outfile, ?;) do |writer|
+ assert_instance_of(CSV::BasicWriter, writer)
+ end
+
+ begin
+ CSV.generate(@tmpdir)
+ assert(false)
+ rescue Exception => ex
+ assert(ex.is_a?(Errno::EEXIST) || ex.is_a?(Errno::EISDIR) || ex.is_a?(Errno::EACCES))
+ end
+ end
+
+ def test_s_generate_line
+ str = CSV.generate_line([])
+ assert_equal('', str, "Extra boundary check.")
+
+ str = CSV.generate_line([], ?;)
+ assert_equal('', str, "Extra boundary check.")
+
+ @@simpleCSVData.each do |col, str|
+ buf = CSV.generate_line(col)
+ assert_equal(str, buf)
+ end
+
+ @@simpleCSVData.each do |col, str|
+ buf = CSV.generate_line(col, ?;)
+ assert_equal(str + "\n", ssv2csv(buf))
+ end
+
+ @@simpleCSVData.each do |col, str|
+ buf = CSV.generate_line(col, ?\t)
+ assert_equal(str + "\n", tsv2csv(buf))
+ end
+
+ str = CSV.generate_line(['a', 'b'], nil, ?|)
+ assert_equal('a,b', str)
+
+ str = CSV.generate_line(['a', 'b'], nil, "a")
+ assert_equal('"a",b', str)
+ end
+
+ def test_s_generate_row
+ buf = ''
+ cols = CSV.generate_row([], 0, buf)
+ assert_equal(0, cols)
+ assert_equal("\n", buf, "Extra boundary check.")
+
+ buf = ''
+ cols = CSV.generate_row([], 0, buf, ?;)
+ assert_equal(0, cols)
+ assert_equal("\n", buf, "Extra boundary check.")
+
+ buf = ''
+ cols = CSV.generate_row([], 0, buf, ?\t)
+ assert_equal(0, cols)
+ assert_equal("\n", buf, "Extra boundary check.")
+
+ buf = ''
+ cols = CSV.generate_row([], 0, buf, ?\t, ?|)
+ assert_equal(0, cols)
+ assert_equal("|", buf, "Extra boundary check.")
+
+ buf = ''
+ cols = CSV.generate_row([d('1')], 2, buf)
+ assert_equal('1,', buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1')], 2, buf, ?;)
+ assert_equal('1;', buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1')], 2, buf, ?\t)
+ assert_equal("1\t", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1')], 2, buf, ?\t, ?|)
+ assert_equal("1\t", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1'), d('2')], 1, buf)
+ assert_equal("1\n", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1'), d('2')], 1, buf, ?;)
+ assert_equal("1\n", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1'), d('2')], 1, buf, ?\t)
+ assert_equal("1\n", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1'), d('2')], 1, buf, ?\t, ?\n)
+ assert_equal("1\n", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1'), d('2')], 1, buf, ?\t, ?\r)
+ assert_equal("1\r", buf)
+
+ buf = ''
+ cols = CSV.generate_row([d('1'), d('2')], 1, buf, ?\t, ?|)
+ assert_equal("1|", buf)
+
+ @@fullCSVData.each do |col, str|
+ buf = ''
+ cols = CSV.generate_row(col, col.size, buf)
+ assert_equal(col.size, cols)
+ assert_equal(str + "\n", buf)
+ end
+
+ @@fullCSVData.each do |col, str|
+ buf = ''
+ cols = CSV.generate_row(col, col.size, buf, ?;)
+ assert_equal(col.size, cols)
+ assert_equal(str + "\n", ssv2csv(buf))
+ end
+
+ @@fullCSVData.each do |col, str|
+ buf = ''
+ cols = CSV.generate_row(col, col.size, buf, ?\t)
+ assert_equal(col.size, cols)
+ assert_equal(str + "\n", tsv2csv(buf))
+ end
+
+ # row separator
+ @@fullCSVData.each do |col, str|
+ buf = ''
+ cols = CSV.generate_row(col, col.size, buf, ?,, ?|)
+ assert_equal(col.size, cols)
+ assert_equal(str + "|", buf)
+ end
+
+ # col and row separator
+ @@fullCSVData.each do |col, str|
+ buf = ''
+ cols = CSV.generate_row(col, col.size, buf, ?\t, ?|)
+ assert_equal(col.size, cols)
+ assert_equal(str + "|", tsv2csv(buf, ?|))
+ end
+
+ buf = ''
+ toBe = ''
+ cols = 0
+ colsToBe = 0
+ @@fullCSVData.each do |col, str|
+ cols += CSV.generate_row(col, col.size, buf)
+ toBe << str << "\n"
+ colsToBe += col.size
+ end
+ assert_equal(colsToBe, cols)
+ assert_equal(toBe, buf)
+
+ buf = ''
+ toBe = ''
+ cols = 0
+ colsToBe = 0
+ @@fullCSVData.each do |col, str|
+ lineBuf = ''
+ cols += CSV.generate_row(col, col.size, lineBuf, ?;)
+ buf << ssv2csv(lineBuf) << "\n"
+ toBe << ssv2csv(lineBuf) << "\n"
+ colsToBe += col.size
+ end
+ assert_equal(colsToBe, cols)
+ assert_equal(toBe, buf)
+
+ buf = ''
+ toBe = ''
+ cols = 0
+ colsToBe = 0
+ @@fullCSVData.each do |col, str|
+ lineBuf = ''
+ cols += CSV.generate_row(col, col.size, lineBuf, ?\t)
+ buf << tsv2csv(lineBuf) << "\n"
+ toBe << tsv2csv(lineBuf) << "\n"
+ colsToBe += col.size
+ end
+ assert_equal(colsToBe, cols)
+ assert_equal(toBe, buf)
+
+ buf = ''
+ toBe = ''
+ cols = 0
+ colsToBe = 0
+ @@fullCSVData.each do |col, str|
+ lineBuf = ''
+ cols += CSV.generate_row(col, col.size, lineBuf, ?|)
+ buf << tsv2csv(lineBuf, ?|)
+ toBe << tsv2csv(lineBuf, ?|)
+ colsToBe += col.size
+ end
+ assert_equal(colsToBe, cols)
+ assert_equal(toBe, buf)
+ end
+
+ def test_s_parse_line
+ @@simpleCSVData.each do |col, str|
+ row = CSV.parse_line(str)
+ assert_instance_of(Array, row)
+ assert_equal(col.size, row.size)
+ assert_equal(col, row)
+ end
+
+ @@simpleCSVData.each do |col, str|
+ str = csv2ssv(str)
+ row = CSV.parse_line(str, ?;)
+ assert_instance_of(Array, row)
+ assert_equal(col.size, row.size, str.inspect)
+ assert_equal(col, row, str.inspect)
+ end
+
+ @@simpleCSVData.each do |col, str|
+ str = csv2tsv(str)
+ row = CSV.parse_line(str, ?\t)
+ assert_instance_of(Array, row)
+ assert_equal(col.size, row.size)
+ assert_equal(col, row)
+ end
+
+ assert_equal(['a', 'b', 'c'], CSV.parse_line("a,b,c", nil, nil))
+ assert_equal(['a', nil], CSV.parse_line("a,b,c", nil, ?b))
+ assert_equal(['a', 'b', nil], CSV.parse_line("a,b,c", nil, "c"))
+ assert_equal([nil], CSV.parse_line(""))
+ assert_equal([nil], CSV.parse_line("\n"))
+ assert_equal([""], CSV.parse_line("\"\"\n"))
+
+ # Illegal format.
+ buf = []
+ row = CSV.parse_line("a,b,\"c\"\ra")
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ buf = Array.new
+ row = CSV.parse_line("a;b;\"c\"\ra", ?;)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ buf = Array.new
+ row = CSV.parse_line("a\tb\t\"c\"\ra", ?\t)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("a,b\"")
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("a;b\"", ?;)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("a\tb\"", ?\t)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("\"a,b\"\r,")
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("\"a;b\"\r;", ?;)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("\"a\tb\"\r\t", ?\t)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("\"a,b\"\r\"")
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("\"a;b\"\r\"", ?;)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+
+ row = CSV.parse_line("\"a\tb\"\r\"", ?\t)
+ assert_instance_of(Array, row)
+ assert_equal(0, row.size)
+ end
+
+ def test_s_parse_row
+ @@fullCSVData.each do |col, str|
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "\r\n", 0, buf)
+ assert_equal(cols, buf.size, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf, str.inspect)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "\n", 0, buf, ?,, ?\n)
+ assert_equal(cols, buf.size, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf, str.inspect)
+
+ # separator: |
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "|", 0, buf, ?,)
+ assert_not_equal(col, buf)
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "|", 0, buf, ?,, ?|)
+ assert_equal(cols, buf.size, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf, str.inspect)
+ end
+
+ @@fullCSVData.each do |col, str|
+ str = csv2ssv(str)
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "\r\n", 0, buf, ?;)
+ assert_equal(cols, buf.size, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf, str)
+ end
+
+ @@fullCSVData.each do |col, str|
+ str = csv2tsv(str)
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "\r\n", 0, buf, ?\t)
+ assert_equal(cols, buf.size, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf, str)
+ end
+
+ @@fullCSVData.each do |col, str|
+ str = csv2tsv(str, ?|)
+ buf = Array.new
+ cols, idx = CSV.parse_row(str + "|", 0, buf, ?\t, ?|)
+ assert_equal(cols, buf.size, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf, str)
+ end
+
+ buf = []
+ CSV.parse_row("a,b,c", 0, buf, nil, nil)
+ assert_equal(['a', 'b', 'c'], buf)
+
+ buf = []
+ CSV.parse_row("a,b,c", 0, buf, nil, ?b)
+ assert_equal(['a', nil], buf)
+
+ buf = []
+ CSV.parse_row("a,b,c", 0, buf, nil, "c")
+ assert_equal(['a', 'b', nil], buf)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a,b,\"c\r\"", 0, buf)
+ assert_equal(["a", "b", "c\r"], buf.to_a)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a;b;\"c\r\"", 0, buf, ?;)
+ assert_equal(["a", "b", "c\r"], buf.to_a)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\tb\t\"c\r\"", 0, buf, ?\t)
+ assert_equal(["a", "b", "c\r"], buf.to_a)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a,b,c\n", 0, buf, ?,, ?\n)
+ assert_equal(["a", "b", "c"], buf.to_a)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\tb\tc\n", 0, buf, ?\t, ?\n)
+ assert_equal(["a", "b", "c"], buf.to_a)
+
+ # Illegal format.
+ buf = Array.new
+ cols, idx = CSV.parse_row("a,b,c\"", 0, buf)
+ assert_equal(0, cols, "Illegal format; unbalanced double-quote.")
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a;b;c\"", 0, buf, ?;)
+ assert_equal(0, cols, "Illegal format; unbalanced double-quote.")
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a,b,\"c\"\ra", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a,b,\"c\"\ra", 0, buf, ?;)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a,b\"", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a;b\"", 0, buf, ?;)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("\"a,b\"\r,", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\r,", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\r", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\rbc", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\r\"\"", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("a\r\rabc,", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("\"a;b\"\r;", 0, buf, ?;)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("\"a,b\"\r\"", 0, buf)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+
+ buf = Array.new
+ cols, idx = CSV.parse_row("\"a;b\"\r\"", 0, buf, ?;)
+ assert_equal(0, cols)
+ assert_equal(0, idx)
+ end
+
+ def test_s_parse_rowEOF
+ @@fullCSVData.each do |col, str|
+ if str == ''
+ # String "" is not allowed.
+ next
+ end
+ buf = Array.new
+ cols, idx = CSV.parse_row(str, 0, buf)
+ assert_equal(col.size, cols, "Reported size.")
+ assert_equal(col.size, buf.size, "Size.")
+ assert_equal(col, buf)
+ end
+ end
+
+ def test_s_parse_rowConcat
+ buf = ''
+ toBe = []
+ @@fullCSVData.each do |col, str|
+ buf << str << "\r\n"
+ toBe.concat(col)
+ end
+ idx = 0
+ cols = 0
+ parsed = Array.new
+ parsedCols = 0
+ begin
+ cols, idx = CSV.parse_row(buf, idx, parsed)
+ parsedCols += cols
+ end while cols > 0
+ assert_equal(toBe.size, parsedCols)
+ assert_equal(toBe.size, parsed.size)
+ assert_equal(toBe, parsed)
+
+ buf = ''
+ toBe = []
+ @@fullCSVData.each do |col, str|
+ buf << str << "\n"
+ toBe.concat(col)
+ end
+ idx = 0
+ cols = 0
+ parsed = Array.new
+ parsedCols = 0
+ begin
+ cols, idx = CSV.parse_row(buf, idx, parsed, ?,, ?\n)
+ parsedCols += cols
+ end while cols > 0
+ assert_equal(toBe.size, parsedCols)
+ assert_equal(toBe.size, parsed.size)
+ assert_equal(toBe, parsed)
+
+ buf = ''
+ toBe = []
+ @@fullCSVData.sort { |a, b|
+ a[0].length <=> b[0].length
+ }.each do |col, str|
+ buf << str << "\n"
+ toBe.concat(col)
+ end
+ idx = 0
+ cols = 0
+ parsed = Array.new
+ parsedCols = 0
+ begin
+ cols, idx = CSV.parse_row(buf, idx, parsed, ?,, ?\n)
+ parsedCols += cols
+ end while cols > 0
+ assert_equal(toBe.size, parsedCols)
+ assert_equal(toBe.size, parsed.size)
+ assert_equal(toBe, parsed)
+
+ buf = ''
+ toBe = []
+ @@fullCSVData.each do |col, str|
+ buf << str << "|"
+ toBe.concat(col)
+ end
+ idx = 0
+ cols = 0
+ parsed = []
+ parsedCols = 0
+ begin
+ cols, idx = CSV.parse_row(buf, idx, parsed, ?,, ?|)
+ parsedCols += cols
+ end while cols > 0
+ assert_equal(toBe.size, parsedCols)
+ assert_equal(toBe.size, parsed.size)
+ assert_equal(toBe, parsed)
+ end
+
+ def test_utf8
+ rows = []
+ CSV.open(@bomfile, "r") do |row|
+ rows << row.to_a
+ end
+ assert_equal([["foo"], ["bar"]], rows)
+
+ rows = []
+ file = File.open(@bomfile)
+ CSV::Reader.parse(file) do |row|
+ rows << row.to_a
+ end
+ assert_equal([["foo"], ["bar"]], rows)
+ file.close
+ end
+
+ def test_macCR
+ rows = []
+ CSV.open(@macfile, "r", ?,, ?\r) do |row|
+ rows << row.to_a
+ end
+ assert_equal([["Avenches", "aus Umgebung"], ["Bad Hersfeld", "Ausgrabung"]], rows)
+
+ rows = []
+ assert_raises(CSV::IllegalFormatError) do
+ CSV.open(@macfile, "r") do |row|
+ rows << row.to_a
+ end
+ assert_equal([["Avenches", "aus Umgebung\r\"Bad Hersfeld", "Ausgrabung"]], rows)
+ end
+
+ rows = []
+ file = File.open(@macfile)
+ begin
+ CSV::Reader.parse(file, ?,, ?\r) do |row|
+ rows << row.to_a
+ end
+ assert_equal([["Avenches", "aus Umgebung"], ["Bad Hersfeld", "Ausgrabung"]], rows)
+ ensure
+ file.close
+ end
+
+ rows = []
+ file = File.open(@macfile)
+ begin
+ assert_raises(CSV::IllegalFormatError) do
+ CSV::Reader.parse(file, ?,) do |row|
+ rows << row.to_a
+ end
+ assert_equal([["Avenches", "aus Umgebung\r\"Bad Hersfeld", "Ausgrabung"]], rows)
+ end
+ ensure
+ file.close
+ end
+ end
+
+
+ #### CSV unit test
+
+ InputStreamPattern = '0123456789'
+ InputStreamPatternSize = InputStreamPattern.size
+ def expChar(idx)
+ InputStreamPattern[idx % InputStreamPatternSize]
+ end
+
+ def expStr(idx, n)
+ if n > InputStreamPatternSize
+ InputStreamPattern + expStr(0, n - InputStreamPatternSize)
+ else
+ InputStreamPattern[idx % InputStreamPatternSize, n]
+ end
+ end
+
+ def setupInputStream(size, bufSize = nil)
+ setBufSize(bufSize) if bufSize
+ m = ((size / InputStreamPatternSize) + 1).to_i
+ File.open(@outfile, "wb") do |f|
+ f << (InputStreamPattern * m)[0, size]
+ end
+ file = File.open(@outfile, "rb")
+ buf = CSV::IOBuf.new(file)
+ if block_given?
+ yield(buf)
+ file.close
+ nil
+ else
+ buf
+ end
+ end
+
+ def setBufSize(size)
+ CSV::StreamBuf.module_eval('remove_const("BufSize")')
+ CSV::StreamBuf.module_eval("BufSize = #{ size }")
+ end
+
+ class StrBuf < CSV::StreamBuf
+ private
+ def initialize(string)
+ @str = string
+ @idx = 0
+ super()
+ end
+
+ def read(size)
+ str = @str[@idx, size]
+ if str.empty?
+ nil
+ else
+ @idx += str.size
+ str
+ end
+ end
+ end
+
+ class ErrBuf < CSV::StreamBuf
+ class Error < RuntimeError; end
+ private
+ def initialize
+ @first = true
+ super()
+ end
+
+ def read(size)
+ if @first
+ @first = false
+ "a" * size
+ else
+ raise ErrBuf::Error.new
+ end
+ end
+ end
+
+ def test_StreamBuf_MyBuf
+ # At first, check ruby's behaviour.
+ s = "abc"
+ assert_equal(?a, s[0])
+ assert_equal(?b, s[1])
+ assert_equal(?c, s[2])
+ assert_equal(nil, s[3])
+ assert_equal("a", s[0, 1])
+ assert_equal("b", s[1, 1])
+ assert_equal("c", s[2, 1])
+ assert_equal("", s[3, 1])
+ assert_equal(nil, s[4, 1])
+
+ s = StrBuf.new("abc")
+ assert_equal(?a, s[0])
+ assert_equal(?b, s.get(1))
+ assert_equal(?c, s[2])
+ assert_equal(nil, s.get(3))
+ assert_equal("a", s[0, 1])
+ assert_equal("b", s.get(1, 1))
+ assert_equal("c", s[2, 1])
+ assert_equal("", s.get(3, 1))
+ assert_equal(nil, s[4, 1])
+
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(?b, s[0])
+ assert(!s.is_eos?)
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(?c, s[0])
+ assert(!s.is_eos?)
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(nil, s[0])
+ assert(s.is_eos?)
+ dropped = s.drop(1)
+ assert_equal(0, dropped)
+ assert_equal(nil, s[0])
+ assert(s.is_eos?)
+
+ s = StrBuf.new("")
+ assert_equal(nil, s[0])
+
+ s = StrBuf.new("")
+ dropped = s.drop(1)
+ assert_equal(0, dropped)
+
+ assert_raises(TestCSV::ErrBuf::Error) do
+ s = ErrBuf.new
+ s[1024]
+ end
+
+ assert_raises(TestCSV::ErrBuf::Error) do
+ s = ErrBuf.new
+ s.drop(1024)
+ end
+ end
+
+ def test_StreamBuf_AREF # '[idx]'
+ setupInputStream(22, 1024) do |s|
+ [0, 1, 9, 10, 19, 20, 21].each do |idx|
+ assert_equal(expChar(idx), s[idx], idx.to_s)
+ end
+ [22, 23].each do |idx|
+ assert_equal(nil, s[idx], idx.to_s)
+ end
+ assert_equal(nil, s[-1])
+ end
+
+ setupInputStream(22, 1) do |s|
+ [0, 1, 9, 10, 19, 20, 21].each do |idx|
+ assert_equal(expChar(idx), s[idx], idx.to_s)
+ end
+ [22, 23].each do |idx|
+ assert_equal(nil, s[idx], idx.to_s)
+ end
+ end
+
+ setupInputStream(1024, 1) do |s|
+ [1023, 0].each do |idx|
+ assert_equal(expChar(idx), s[idx], idx.to_s)
+ end
+ [1024, 1025].each do |idx|
+ assert_equal(nil, s[idx], idx.to_s)
+ end
+ end
+
+ setupInputStream(1, 1) do |s|
+ [0].each do |idx|
+ assert_equal(expChar(idx), s[idx], idx.to_s)
+ end
+ [1, 2].each do |idx|
+ assert_equal(nil, s[idx], idx.to_s)
+ end
+ end
+ end
+
+ def test_StreamBuf_AREF_n # '[idx, n]'
+ # At first, check ruby's behaviour.
+ assert_equal("", "abc"[3, 1])
+ assert_equal(nil, "abc"[4, 1])
+
+ setupInputStream(22, 1024) do |s|
+ [0, 1, 9, 10, 19, 20, 21].each do |idx|
+ assert_equal(expStr(idx, 1), s[idx, 1], idx.to_s)
+ end
+ assert_equal("", s[22, 1])
+ assert_equal(nil, s[23, 1])
+ end
+
+ setupInputStream(22, 1) do |s|
+ [0, 1, 9, 10, 19, 20, 21].each do |idx|
+ assert_equal(expStr(idx, 1), s[idx, 1], idx.to_s)
+ end
+ assert_equal("", s[22, 1])
+ assert_equal(nil, s[23, 1])
+ end
+
+ setupInputStream(1024, 1) do |s|
+ [1023, 0].each do |idx|
+ assert_equal(expStr(idx, 1), s[idx, 1], idx.to_s)
+ end
+ assert_equal("", s[1024, 1])
+ assert_equal(nil, s[1025, 1])
+ end
+
+ setupInputStream(1, 1) do |s|
+ [0].each do |idx|
+ assert_equal(expStr(idx, 1), s[idx, 1], idx.to_s)
+ end
+ assert_equal("", s[1, 1])
+ assert_equal(nil, s[2, 1])
+ end
+
+ setupInputStream(22, 11) do |s|
+ [0, 1, 10, 11, 20].each do |idx|
+ assert_equal(expStr(idx, 2), s[idx, 2], idx.to_s)
+ end
+ assert_equal(expStr(21, 1), s[21, 2])
+
+ assert_equal(expStr(0, 12), s[0, 12])
+ assert_equal(expStr(10, 12), s[10, 12])
+ assert_equal(expStr(10, 12), s[10, 13])
+ assert_equal(expStr(10, 12), s[10, 14])
+ assert_equal(expStr(10, 12), s[10, 1024])
+
+ assert_equal(nil, s[0, -1])
+ assert_equal(nil, s[21, -1])
+
+ assert_equal(nil, s[-1, 10])
+ assert_equal(nil, s[-1, -1])
+ end
+ end
+
+ def test_StreamBuf_get
+ setupInputStream(22, 1024) do |s|
+ [0, 1, 9, 10, 19, 20, 21].each do |idx|
+ assert_equal(expChar(idx), s.get(idx), idx.to_s)
+ end
+ [22, 23].each do |idx|
+ assert_equal(nil, s.get(idx), idx.to_s)
+ end
+ assert_equal(nil, s.get(-1))
+ end
+ end
+
+ def test_StreamBuf_get_n
+ setupInputStream(22, 1024) do |s|
+ [0, 1, 9, 10, 19, 20, 21].each do |idx|
+ assert_equal(expStr(idx, 1), s.get(idx, 1), idx.to_s)
+ end
+ assert_equal("", s.get(22, 1))
+ assert_equal(nil, s.get(23, 1))
+
+ assert_equal(nil, s.get(-1, 1))
+ assert_equal(nil, s.get(-1, -1))
+ end
+ end
+
+ def test_StreamBuf_drop
+ setupInputStream(22, 1024) do |s|
+ assert_equal(expChar(0), s[0])
+ assert_equal(expChar(21), s[21])
+ assert_equal(nil, s[22])
+
+ dropped = s.drop(-1)
+ assert_equal(0, dropped)
+ assert_equal(expChar(0), s[0])
+
+ dropped = s.drop(0)
+ assert_equal(0, dropped)
+ assert_equal(expChar(0), s[0])
+
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(expChar(1), s[0])
+ assert_equal(expChar(2), s[1])
+
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(expChar(2), s[0])
+ assert_equal(expChar(3), s[1])
+ end
+
+ setupInputStream(4, 2) do |s|
+ dropped = s.drop(2)
+ assert_equal(2, dropped)
+ assert_equal(expChar(2), s[0])
+ assert_equal(expChar(3), s[1])
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(expChar(3), s[0])
+ assert_equal(nil, s[1])
+ dropped = s.drop(1)
+ assert_equal(1, dropped)
+ assert_equal(nil, s[0])
+ assert_equal(nil, s[1])
+ dropped = s.drop(0)
+ assert_equal(0, dropped)
+ assert_equal(nil, s[0])
+ assert_equal(nil, s[1])
+ end
+
+ setupInputStream(6, 3) do |s|
+ dropped = s.drop(2)
+ assert_equal(2, dropped)
+ dropped = s.drop(2)
+ assert_equal(2, dropped)
+ assert_equal(expChar(4), s[0])
+ assert_equal(expChar(5), s[1])
+ dropped = s.drop(3)
+ assert_equal(2, dropped)
+ assert_equal(nil, s[0])
+ assert_equal(nil, s[1])
+ end
+ end
+
+ def test_StreamBuf_is_eos?
+ setupInputStream(3, 1024) do |s|
+ assert(!s.is_eos?)
+ s.drop(1)
+ assert(!s.is_eos?)
+ s.drop(1)
+ assert(!s.is_eos?)
+ s.drop(1)
+ assert(s.is_eos?)
+ s.drop(1)
+ assert(s.is_eos?)
+ end
+
+ setupInputStream(3, 2) do |s|
+ assert(!s.is_eos?)
+ s.drop(1)
+ assert(!s.is_eos?)
+ s.drop(1)
+ assert(!s.is_eos?)
+ s.drop(1)
+ assert(s.is_eos?)
+ s.drop(1)
+ assert(s.is_eos?)
+ end
+ end
+
+ def test_StreamBuf_s_new
+ # NotImplementedError should be raised from StreamBuf#read.
+ assert_raises(NotImplementedError) do
+ CSV::StreamBuf.new
+ end
+ end
+
+ def test_IOBuf_close
+ f = File.open(@outfile, "wb")
+ f << "tst"
+ f.close
+
+ f = File.open(@outfile, "rb")
+ iobuf = CSV::IOBuf.new(f)
+ iobuf.close
+ assert(true) # iobuf.close does not raise any exception.
+ f.close
+ end
+
+ def test_IOBuf_s_new
+ iobuf = CSV::IOBuf.new(Tempfile.new("in.csv"))
+ assert_instance_of(CSV::IOBuf, iobuf)
+ end
+
+
+ #### CSV functional test
+
+ # sample data
+ #
+ # 1 2 3 4 5 6 7 8
+ # +------+-------+---------+-------+--------+------+----+------+
+ # | foo | "foo" | foo,bar | "" |(empty) |(null)| \r | \r\n |
+ # +------+-------+---------+-------+--------+------+----+------+
+ # | NaHi | "Na" | Na,Hi | \r.\n | \r\n\n | " | \n | \r\n |
+ # +------+-------+---------+-------+--------+------+----+------+
+ #
+ def test_s_parseAndCreate
+ colSize = 8
+ csvStr = "foo,!!!foo!!!,!foo,bar!,!!!!!!,!!,,!\r!,!\r\n!\nNaHi,!!!Na!!!,!Na,Hi!,!\r.\n!,!\r\n\n!,!!!!,!\n!,!\r\n!".gsub!('!', '"')
+ csvStrTerminated = csvStr + "\n"
+
+ myStr = csvStr.dup
+ res1 = []; res2 = []
+ idx = 0
+ col, idx = CSV::parse_row(myStr, 0, res1)
+ col, idx = CSV::parse_row(myStr, idx, res2)
+
+ buf = ''
+ col = CSV::generate_row(res1, colSize, buf)
+ col = CSV::generate_row(res2, colSize, buf)
+ assert_equal(csvStrTerminated, buf)
+
+ parsed = []
+ CSV::Reader.parse(csvStrTerminated) do |row|
+ parsed << row
+ end
+
+ buf = ''
+ CSV::Writer.generate(buf) do |writer|
+ parsed.each do |row|
+ writer.add_row(row)
+ end
+ end
+ assert_equal(csvStrTerminated, buf)
+
+ buf = ''
+ CSV::Writer.generate(buf) do |writer|
+ parsed.each do |row|
+ writer << row
+ end
+ end
+ assert_equal(csvStrTerminated, buf)
+ end
+
+ def test_writer_fs_rs_generate
+ buf = ''
+ CSV::Writer.generate(buf, ",,") do |writer|
+ writer << []
+ end
+ assert_equal("\n", buf)
+
+ buf = ''
+ CSV::Writer.generate(buf, ",,") do |writer|
+ writer << [] << []
+ end
+ assert_equal("\n\n", buf)
+
+ buf = ''
+ CSV::Writer.generate(buf, ",,") do |writer|
+ writer << [1]
+ end
+ assert_equal("1\n", buf)
+
+ buf = ''
+ CSV::Writer.generate(buf, ",,") do |writer|
+ writer << [1, 2, 3]
+ writer << [4, ",,", 5]
+ end
+ assert_equal("1,,2,,3\n4,,\",,\",,5\n", buf)
+
+ buf = ''
+ CSV::Writer.generate(buf, ",,:", ",,;") do |writer|
+ writer << [nil, nil, nil]
+ writer << [nil, ",,", nil]
+ end
+ assert_equal(",,:,,:,,;,,:,,,,:,,;", buf)
+
+ buf = ''
+ CSV::Writer.generate(buf, "---") do |writer|
+ writer << [1, 2, 3]
+ writer << [4, "---\"---", 5]
+ end
+ assert_equal("1---2---3\n4---\"---\"\"---\"---5\n", buf)
+
+ buf = ''
+ CSV::Writer.generate(buf, nil) do |writer|
+ writer << [1, 2, 3]
+ writer << [4, ",\",", 5]
+ end
+ assert_equal("1,2,3\n4,\",\"\",\",5\n", buf)
+ end
+
+ def test_writer_fs_rs_parse
+ reader = CSV::Reader.create('a||b--c||d', '||', '--')
+ assert_equal(['a', 'b'], reader.shift)
+ assert_equal(['c', 'd'], reader.shift)
+
+ reader = CSV::Reader.create("a@|b@-c@|d", "@|", "@-")
+ assert_equal(['a', 'b'], reader.shift)
+ assert_equal(['c', 'd'], reader.shift)
+
+ reader = CSV::Reader.create("ababfsababrs", "abfs", "abrs")
+ assert_equal(['ab', 'ab'], reader.shift)
+
+ reader = CSV::Reader.create('"ab"abfsababrs', "abfs", "abrs")
+ assert_equal(['ab', 'ab'], reader.shift)
+
+ reader = CSV::Reader.create('"ab"aabfsababrs', "abfs", "abrs")
+ assert_raises(CSV::IllegalFormatError) do
+ reader.shift
+ end
+
+ # fs match while matching rs progress
+ reader = CSV::Reader.create("ab,ababrs", nil, "abrs")
+ assert_equal(['ab', 'ab'], reader.shift)
+
+ reader = CSV::Reader.create(',ababrs', nil, "abrs")
+ assert_equal([nil, 'ab'], reader.shift)
+
+ reader = CSV::Reader.create('"",ababrs', nil, "abrs")
+ assert_equal(['', 'ab'], reader.shift)
+
+ reader = CSV::Reader.create('ab,"ab"abrs', nil, "abrs")
+ assert_equal(['ab', 'ab'], reader.shift)
+
+ reader = CSV::Reader.create('ab,"ab"aabrs', nil, "abrs")
+ assert_raises(CSV::IllegalFormatError) do
+ reader.shift
+ end
+
+ # rs match while matching fs progress
+ reader = CSV::Reader.create("ab|abc", 'ab-', "ab|")
+ assert_equal([nil], reader.shift)
+ assert_equal(['abc'], reader.shift)
+
+ reader = CSV::Reader.create("ab\ncdabcef", "abc", "\n")
+ assert_equal(['ab'], reader.shift)
+ assert_equal(['cd', "ef"], reader.shift)
+
+ # EOF while fs/rs matching
+ reader = CSV::Reader.create("ab", 'ab-', "xyz")
+ assert_equal(['ab'], reader.shift)
+
+ reader = CSV::Reader.create("ab", 'xyz', "ab|")
+ assert_equal(['ab'], reader.shift)
+
+ reader = CSV::Reader.create("ab", 'ab-', "ab|")
+ assert_equal(['ab'], reader.shift)
+
+ reader = CSV::Reader.create(",,:,,:,,;,,:,,,,:,,;", ",,:", ",,;")
+ assert_equal([nil, nil, nil], reader.shift)
+ assert_equal([nil, ",,", nil], reader.shift)
+ end
+
+ def test_s_foreach
+ File.open(@outfile, "w") do |f|
+ f << "1,2,3\n4,5,6"
+ end
+ row = []
+ CSV.foreach(@outfile) { |line|
+ row << line
+ }
+ assert_equal([['1', '2', '3'], ['4', '5', '6']], row)
+
+ File.open(@outfile, "w") do |f|
+ f << "1,2,3\r4,5,6"
+ end
+ row = []
+ CSV.foreach(@outfile, "\r") { |line|
+ row << line
+ }
+ assert_equal([['1', '2', '3'], ['4', '5', '6']], row)
+ end
+
+ def test_s_readlines
+ File.open(@outfile, "w") do |f|
+ f << "1,2,3\n4,5,6"
+ end
+ assert_equal([["1", "2", "3"], ["4", "5", "6"]], CSV.readlines(@outfile))
+ assert_equal([["1", "2", nil], [nil, "5", "6"]], CSV.readlines(@outfile, "3\n4"))
+ end
+
+ def test_s_read
+ File.open(@outfile, "w") do |f|
+ f << "1,2,3\n4,5,6"
+ end
+ assert_equal([["1", "2", "3"], ["4", "5", "6"]], CSV.read(@outfile))
+ assert_equal([["1", "2"]], CSV.read(@outfile, 3))
+ assert_equal([[nil], ["4", nil]], CSV.read(@outfile, 3, 5))
+ end
+end
diff --git a/ruby_1_8_6/test/dbm/test_dbm.rb b/ruby_1_8_6/test/dbm/test_dbm.rb
new file mode 100644
index 0000000000..941e139946
--- /dev/null
+++ b/ruby_1_8_6/test/dbm/test_dbm.rb
@@ -0,0 +1,545 @@
+require 'test/unit'
+
+begin
+ require 'dbm'
+rescue LoadError
+end
+
+if defined? DBM
+ require 'tmpdir'
+ require 'fileutils'
+
+ class TestDBM < Test::Unit::TestCase
+ def TestDBM.uname_s
+ require 'rbconfig'
+ case Config::CONFIG['target_os']
+ when 'cygwin'
+ require 'Win32API'
+ uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
+ utsname = ' ' * 100
+ raise 'cannot get system name' if uname.call(utsname) == -1
+
+ utsname.unpack('A20' * 5)[0]
+ else
+ Config::CONFIG['target_os']
+ end
+ end
+ SYSTEM = uname_s
+
+ def setup
+ @path = "tmptest_dbm_"
+ assert_instance_of(DBM, @dbm = DBM.new(@path))
+
+ # prepare to make readonly DBM file
+ DBM.open("tmptest_dbm_rdonly") {|dbm|
+ dbm['foo'] = 'FOO'
+ }
+
+ File.chmod(0400, *Dir.glob("tmptest_dbm_rdonly.*"))
+
+ assert_instance_of(DBM, @dbm_rdonly = DBM.new("tmptest_dbm_rdonly", nil))
+ end
+ def teardown
+ assert_nil(@dbm.close)
+ assert_nil(@dbm_rdonly.close)
+ ObjectSpace.each_object(DBM) do |obj|
+ obj.close unless obj.closed?
+ end
+ File.delete *Dir.glob("tmptest_dbm*").to_a
+ p Dir.glob("tmptest_dbm*") if $DEBUG
+ end
+
+ def check_size(expect, dbm=@dbm)
+ assert_equal(expect, dbm.size)
+ n = 0
+ dbm.each { n+=1 }
+ assert_equal(expect, n)
+ if expect == 0
+ assert_equal(true, dbm.empty?)
+ else
+ assert_equal(false, dbm.empty?)
+ end
+ end
+
+ def have_fork?
+ begin
+ fork{}
+ true
+ rescue NotImplementedError
+ false
+ end
+ end
+
+ def test_s_new_has_no_block
+ # DBM.new ignore the block
+ foo = true
+ assert_instance_of(DBM, dbm = DBM.new("tmptest_dbm") { foo = false })
+ assert_equal(foo, true)
+ assert_nil(dbm.close)
+ end
+ def test_s_open_no_create
+ assert_nil(dbm = DBM.open("tmptest_dbm", nil))
+ ensure
+ dbm.close if dbm
+ end
+ def test_s_open_with_block
+ assert_equal(DBM.open("tmptest_dbm") { :foo }, :foo)
+ end
+
+ def test_close
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm"))
+ assert_nil(dbm.close)
+
+ # closed DBM file
+ assert_raise(DBMError) { dbm.close }
+ end
+
+ def test_aref
+ assert_equal('bar', @dbm['foo'] = 'bar')
+ assert_equal('bar', @dbm['foo'])
+
+ assert_nil(@dbm['bar'])
+ end
+
+ def test_fetch
+ assert_equal('bar', @dbm['foo']='bar')
+ assert_equal('bar', @dbm.fetch('foo'))
+
+ # key not found
+ assert_raise(IndexError) {
+ @dbm.fetch('bar')
+ }
+
+ # test for `ifnone' arg
+ assert_equal('baz', @dbm.fetch('bar', 'baz'))
+
+ # test for `ifnone' block
+ assert_equal('foobar', @dbm.fetch('bar') {|key| 'foo' + key })
+ end
+
+ def test_aset
+ num = 0
+ 2.times {|i|
+ assert_equal('foo', @dbm['foo'] = 'foo')
+ assert_equal('foo', @dbm['foo'])
+ assert_equal('bar', @dbm['foo'] = 'bar')
+ assert_equal('bar', @dbm['foo'])
+
+ num += 1 if i == 0
+ assert_equal(num, @dbm.size)
+
+ # assign nil
+ assert_equal('', @dbm['bar'] = '')
+ assert_equal('', @dbm['bar'])
+
+ num += 1 if i == 0
+ assert_equal(num, @dbm.size)
+
+ # empty string
+ assert_equal('', @dbm[''] = '')
+ assert_equal('', @dbm[''])
+
+ num += 1 if i == 0
+ assert_equal(num, @dbm.size)
+
+ # Fixnum
+ assert_equal('200', @dbm['100'] = '200')
+ assert_equal('200', @dbm['100'])
+
+ num += 1 if i == 0
+ assert_equal(num, @dbm.size)
+
+ # Big key and value
+ assert_equal('y' * 100, @dbm['x' * 100] = 'y' * 100)
+ assert_equal('y' * 100, @dbm['x' * 100])
+
+ num += 1 if i == 0
+ assert_equal(num, @dbm.size)
+ }
+ end
+
+ def test_index
+ assert_equal('bar', @dbm['foo'] = 'bar')
+ assert_equal('foo', @dbm.index('bar'))
+ assert_nil(@dbm['bar'])
+ end
+
+ def test_indexes
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+ assert_equal(values.reverse, @dbm.indexes(*keys.reverse))
+ end
+
+ def test_values_at
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+ assert_equal(values.reverse, @dbm.values_at(*keys.reverse))
+ end
+
+ def test_select_with_block
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+ ret = @dbm.select {|k,v|
+ assert_equal(k.upcase, v)
+ k != "bar"
+ }
+ assert_equal([['baz', 'BAZ'], ['foo', 'FOO']],
+ ret.sort)
+ end
+
+ def test_length
+ num = 10
+ assert_equal(0, @dbm.size)
+ num.times {|i|
+ i = i.to_s
+ @dbm[i] = i
+ }
+ assert_equal(num, @dbm.size)
+
+ @dbm.shift
+
+ assert_equal(num - 1, @dbm.size)
+ end
+
+ def test_empty?
+ assert_equal(true, @dbm.empty?)
+ @dbm['foo'] = 'FOO'
+ assert_equal(false, @dbm.empty?)
+ end
+
+ def test_each_pair
+ n = 0
+ @dbm.each_pair { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ n = 0
+ ret = @dbm.each_pair {|key, val|
+ assert_not_nil(i = keys.index(key))
+ assert_equal(val, values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@dbm, ret)
+ end
+
+ def test_each_value
+ n = 0
+ @dbm.each_value { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ n = 0
+ ret = @dbm.each_value {|val|
+ assert_not_nil(key = @dbm.index(val))
+ assert_not_nil(i = keys.index(key))
+ assert_equal(val, values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@dbm, ret)
+ end
+
+ def test_each_key
+ n = 0
+ @dbm.each_key { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ n = 0
+ ret = @dbm.each_key {|key|
+ assert_not_nil(i = keys.index(key))
+ assert_equal(@dbm[key], values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@dbm, ret)
+ end
+
+ def test_keys
+ assert_equal([], @dbm.keys)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ assert_equal(keys.sort, @dbm.keys.sort)
+ assert_equal(values.sort, @dbm.values.sort)
+ end
+
+ def test_values
+ test_keys
+ end
+
+ def test_shift
+ assert_nil(@dbm.shift)
+ assert_equal(0, @dbm.size)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ ret_keys = []
+ ret_values = []
+ while ret = @dbm.shift
+ ret_keys.push ret[0]
+ ret_values.push ret[1]
+
+ assert_equal(keys.size - ret_keys.size, @dbm.size)
+ end
+
+ assert_equal(keys.sort, ret_keys.sort)
+ assert_equal(values.sort, ret_values.sort)
+ end
+
+ def test_delete
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ key = keys[1]
+
+ assert_nil(@dbm.delete(key))
+ assert_equal(0, @dbm.size)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ assert_equal('BAR', @dbm.delete(key))
+ assert_nil(@dbm[key])
+ assert_equal(2, @dbm.size)
+
+ assert_nil(@dbm.delete(key))
+
+ if /^CYGWIN_9/ !~ SYSTEM
+ assert_raise(DBMError) {
+ @dbm_rdonly.delete("foo")
+ }
+
+ assert_nil(@dbm_rdonly.delete("bar"))
+ end
+ end
+ def test_delete_with_block
+ key = 'no called block'
+ @dbm[key] = 'foo'
+ assert_equal('foo', @dbm.delete(key) {|k| k.replace 'called block'})
+ assert_equal('no called block', key)
+ assert_equal(0, @dbm.size)
+
+ key = 'no called block'
+ assert_equal(:blockval,
+ @dbm.delete(key) {|k| k.replace 'called block'; :blockval})
+ assert_equal('called block', key)
+ assert_equal(0, @dbm.size)
+ end
+
+ def test_delete_if
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+
+ ret = @dbm.delete_if {|key, val| key.to_i < 50}
+ assert_equal(@dbm, ret)
+ check_size(50, @dbm)
+
+ ret = @dbm.delete_if {|key, val| key.to_i >= 50}
+ assert_equal(@dbm, ret)
+ check_size(0, @dbm)
+
+ # break
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+ check_size(100, @dbm)
+ n = 0;
+ @dbm.delete_if {|key, val|
+ break if n > 50
+ n+=1
+ true
+ }
+ assert_equal(51, n)
+ check_size(49, @dbm)
+
+ @dbm.clear
+
+ # raise
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+ check_size(100, @dbm)
+ n = 0;
+ begin
+ @dbm.delete_if {|key, val|
+ raise "runtime error" if n > 50
+ n+=1
+ true
+ }
+ rescue
+ end
+ assert_equal(51, n)
+ check_size(49, @dbm)
+ end
+
+ def test_reject
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+
+ hash = @dbm.reject {|key, val| key.to_i < 50}
+ assert_instance_of(Hash, hash)
+ assert_equal(100, @dbm.size)
+
+ assert_equal(50, hash.size)
+ hash.each_pair {|key,val|
+ assert_equal(false, key.to_i < 50)
+ assert_equal(key, val)
+ }
+
+ hash = @dbm.reject {|key, val| key.to_i < 100}
+ assert_instance_of(Hash, hash)
+ assert_equal(true, hash.empty?)
+ end
+
+ def test_clear
+ v = "1"
+ 100.times {v = v.next; @dbm[v] = v}
+
+ assert_equal(@dbm, @dbm.clear)
+
+ # validate DBM#size
+ i = 0
+ @dbm.each { i += 1 }
+ assert_equal(@dbm.size, i)
+ assert_equal(0, i)
+ end
+
+ def test_invert
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+
+ hash = @dbm.invert
+ assert_instance_of(Hash, hash)
+ assert_equal(100, hash.size)
+ hash.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_update
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @dbm["101"] = "101"
+ @dbm.update hash
+ assert_equal(101, @dbm.size)
+ @dbm.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_replace
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @dbm["101"] = "101"
+ @dbm.replace hash
+ assert_equal(100, @dbm.size)
+ @dbm.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_haskey?
+ assert_equal('bar', @dbm['foo']='bar')
+ assert_equal(true, @dbm.has_key?('foo'))
+ assert_equal(false, @dbm.has_key?('bar'))
+ end
+
+ def test_has_value?
+ assert_equal('bar', @dbm['foo']='bar')
+ assert_equal(true, @dbm.has_value?('bar'))
+ assert_equal(false, @dbm.has_value?('foo'))
+ end
+
+ def test_to_a
+ v = "0"
+ 100.times {v = v.next; @dbm[v] = v}
+
+ ary = @dbm.to_a
+ assert_instance_of(Array, ary)
+ assert_equal(100, ary.size)
+ ary.each {|key,val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_to_hash
+ v = "0"
+ 100.times {v = v.next; @dbm[v] = v}
+
+ hash = @dbm.to_hash
+ assert_instance_of(Hash, hash)
+ assert_equal(100, hash.size)
+ hash.each {|key,val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+ end
+
+ class TestDBM2 < Test::Unit::TestCase
+ TMPROOT = "#{Dir.tmpdir}/ruby-dbm.#{$$}"
+
+ def setup
+ Dir.mkdir TMPROOT
+ end
+
+ def teardown
+ FileUtils.rm_rf TMPROOT if File.directory?(TMPROOT)
+ end
+
+ def test_reader_open
+ DBM.open("#{TMPROOT}/a") {}
+ v = DBM.open("#{TMPROOT}/a", nil, DBM::READER) {|d|
+ # Errno::EPERM is raised on Solaris which use ndbm.
+ # DBMError is raised on Debian which use gdbm.
+ assert_raises(Errno::EPERM, DBMError) { d["k"] = "v" }
+ true
+ }
+ assert(v)
+ end
+
+ def test_newdb_open
+ DBM.open("#{TMPROOT}/a") {|dbm|
+ dbm["k"] = "v"
+ }
+ v = DBM.open("#{TMPROOT}/a", nil, DBM::NEWDB) {|d|
+ assert_equal(0, d.length)
+ assert_nil(d["k"])
+ true
+ }
+ assert(v)
+ end
+
+ def test_freeze
+ DBM.open("#{TMPROOT}/a") {|d|
+ d.freeze
+ assert_raises(TypeError) { d["k"] = "v" }
+ }
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/digest/test_digest.rb b/ruby_1_8_6/test/digest/test_digest.rb
new file mode 100644
index 0000000000..fa12086300
--- /dev/null
+++ b/ruby_1_8_6/test/digest/test_digest.rb
@@ -0,0 +1,120 @@
+#!/usr/bin/env ruby
+#
+# $RoughId: test.rb,v 1.4 2001/07/13 15:38:27 knu Exp $
+# $Id$
+
+require 'test/unit'
+
+require 'digest'
+%w[digest/md5 digest/rmd160 digest/sha1 digest/sha2].each do |lib|
+ begin
+ require lib
+ rescue LoadError
+ end
+end
+
+module TestDigest
+ Data1 = "abc"
+ Data2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+
+ def test_s_hexdigest
+ self.class::DATA.each do |str, digest|
+ assert_equal(digest, self.class::ALGO.hexdigest(str))
+ end
+ end
+
+ def test_s_digest
+ self.class::DATA.each do |str, digest|
+ assert_equal([digest].pack("H*"), self.class::ALGO.digest(str))
+ end
+ end
+
+ def test_update
+ # This test is also for digest() and hexdigest()
+
+ str = "ABC"
+
+ md = self.class::ALGO.new
+ md.update str
+ assert_equal(self.class::ALGO.hexdigest(str), md.hexdigest)
+ assert_equal(self.class::ALGO.digest(str), md.digest)
+ end
+
+ def test_eq
+ # This test is also for clone()
+
+ md1 = self.class::ALGO.new
+ md1 << "ABC"
+
+ assert_equal(md1, md1.clone, self.class::ALGO)
+
+ md2 = self.class::ALGO.new
+ md2 << "A"
+
+ assert(md1 != md2, self.class::ALGO)
+
+ md2 << "BC"
+
+ assert_equal(md1, md2, self.class::ALGO)
+ end
+
+ def test_instance_eval
+ assert_nothing_raised {
+ self.class::ALGO.new.instance_eval { update "a" }
+ }
+ end
+
+ class TestMD5 < Test::Unit::TestCase
+ include TestDigest
+ ALGO = Digest::MD5
+ DATA = {
+ Data1 => "900150983cd24fb0d6963f7d28e17f72",
+ Data2 => "8215ef0796a20bcaaae116d3876c664a",
+ }
+ end if defined?(Digest::MD5)
+
+ class TestSHA1 < Test::Unit::TestCase
+ include TestDigest
+ ALGO = Digest::SHA1
+ DATA = {
+ Data1 => "a9993e364706816aba3e25717850c26c9cd0d89d",
+ Data2 => "84983e441c3bd26ebaae4aa1f95129e5e54670f1",
+ }
+ end if defined?(Digest::SHA1)
+
+ class TestSHA256 < Test::Unit::TestCase
+ include TestDigest
+ ALGO = Digest::SHA256
+ DATA = {
+ Data1 => "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
+ Data2 => "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
+ }
+ end if defined?(Digest::SHA256)
+
+ class TestSHA384 < Test::Unit::TestCase
+ include TestDigest
+ ALGO = Digest::SHA384
+ DATA = {
+ Data1 => "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7",
+ Data2 => "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b",
+ }
+ end if defined?(Digest::SHA384)
+
+ class TestSHA512 < Test::Unit::TestCase
+ include TestDigest
+ ALGO = Digest::SHA512
+ DATA = {
+ Data1 => "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
+ Data2 => "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445",
+ }
+ end if defined?(Digest::SHA512)
+
+ class TestRMD160 < Test::Unit::TestCase
+ include TestDigest
+ ALGO = Digest::RMD160
+ DATA = {
+ Data1 => "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc",
+ Data2 => "12a053384a9c0c88e405a06c27dcf49ada62eb2b",
+ }
+ end if defined?(Digest::RMD160)
+end
diff --git a/ruby_1_8_6/test/drb/drbtest.rb b/ruby_1_8_6/test/drb/drbtest.rb
new file mode 100644
index 0000000000..faf6c059d9
--- /dev/null
+++ b/ruby_1_8_6/test/drb/drbtest.rb
@@ -0,0 +1,351 @@
+require 'test/unit'
+require 'drb/drb'
+require 'drb/extservm'
+require 'timeout'
+begin
+ loadpath = $:.dup
+ $:.replace($: | [File.expand_path("../ruby", File.dirname(__FILE__))])
+ require 'envutil'
+ensure
+ $:.replace(loadpath)
+end
+
+class DRbService
+ @@manager = DRb::ExtServManager.new
+ @@ruby = EnvUtil.rubybin
+ @@ruby += " -d" if $DEBUG
+ def self.add_service_command(nm)
+ dir = File.dirname(File.expand_path(__FILE__))
+ DRb::ExtServManager.command[nm] = "\"#{@@ruby}\" \"#{dir}/#{nm}\""
+ end
+
+ %w(ut_drb.rb ut_array.rb ut_port.rb ut_large.rb ut_safe1.rb ut_eval.rb).each do |nm|
+ add_service_command(nm)
+ end
+ @server = @@server = DRb::DRbServer.new(nil, @@manager, {})
+ @@manager.uri = @@server.uri
+ def self.manager
+ @@manager
+ end
+ def self.server
+ @server || @@server
+ end
+ def self.ext_service(name)
+ timeout(100, RuntimeError) do
+ manager.service(name)
+ end
+ end
+end
+
+class Onecky
+ include DRbUndumped
+ def initialize(n)
+ @num = n
+ end
+
+ def to_i
+ @num.to_i
+ end
+
+ def sleep(n)
+ Kernel.sleep(n)
+ to_i
+ end
+end
+
+class FailOnecky < Onecky
+ class OneckyError < RuntimeError; end
+ def to_i
+ raise(OneckyError, @num.to_s)
+ end
+end
+
+class XArray < Array
+ def initialize(ary)
+ ary.each do |x|
+ self.push(x)
+ end
+ end
+end
+
+module DRbCore
+ def setup
+ @ext = DRbService.ext_service('ut_drb.rb')
+ @there = @ext.front
+ end
+
+ def teardown
+ @ext.stop_service if @ext
+ end
+
+ def test_00_DRbObject
+ ro = DRbObject.new(nil, 'druby://localhost:12345')
+ assert_equal('druby://localhost:12345', ro.__drburi)
+ assert_equal(nil, ro.__drbref)
+
+ ro = DRbObject.new_with_uri('druby://localhost:12345')
+ assert_equal('druby://localhost:12345', ro.__drburi)
+ assert_equal(nil, ro.__drbref)
+
+ ro = DRbObject.new_with_uri('druby://localhost:12345?foobar')
+ assert_equal('druby://localhost:12345', ro.__drburi)
+ assert_equal(DRb::DRbURIOption.new('foobar'), ro.__drbref)
+ end
+
+ def test_01
+ assert_equal("hello", @there.hello)
+ onecky = Onecky.new('3')
+ assert_equal(6, @there.sample(onecky, 1, 2))
+ ary = @there.to_a
+ assert_kind_of(DRb::DRbObject, ary)
+
+ assert(@there.respond_to?(:to_a, true))
+ assert(@there.respond_to?(:eval, true))
+ assert(! @there.respond_to?(:eval, false))
+ assert(! @there.respond_to?(:eval))
+ end
+
+ def test_01_02_loop
+ onecky = Onecky.new('3')
+ 50.times do
+ assert_equal(6, @there.sample(onecky, 1, 2))
+ ary = @there.to_a
+ assert_kind_of(DRb::DRbObject, ary)
+ end
+ end
+
+ def test_02_unknown
+ obj = @there.unknown_class
+ assert_kind_of(DRb::DRbUnknown, obj)
+ assert_equal('Unknown2', obj.name)
+
+ obj = @there.unknown_module
+ assert_kind_of(DRb::DRbUnknown, obj)
+ if RUBY_VERSION >= '1.8'
+ assert_equal('DRbEx::', obj.name)
+ else
+ assert_equal('DRbEx', obj.name)
+ end
+
+ assert_raises(DRb::DRbUnknownError) do
+ @there.unknown_error
+ end
+
+ onecky = FailOnecky.new('3')
+
+ assert_raises(FailOnecky::OneckyError) do
+ @there.sample(onecky, 1, 2)
+ end
+ end
+
+ def test_03
+ assert_equal(8, @there.sum(1, 1, 1, 1, 1, 1, 1, 1))
+ assert_raises(ArgumentError) do
+ @there.sum(1, 1, 1, 1, 1, 1, 1, 1, 1)
+ end
+ assert_raises(DRb::DRbConnError) do
+ @there.sum('1' * 4096)
+ end
+ end
+
+ def test_04
+ assert_respond_to(@there, 'sum')
+ assert(!(@there.respond_to? "foobar"))
+ end
+
+ def test_05_eq
+ a = @there.to_a[0]
+ b = @there.to_a[0]
+ assert(a.object_id != b.object_id)
+ assert(a == b)
+ assert_equal(a, b)
+ assert(a == @there)
+ assert_equal(a.hash, b.hash)
+ assert_equal(a.hash, @there.hash)
+ assert(a.eql?(b))
+ assert(a.eql?(@there))
+ end
+
+ def test_06_timeout
+ ten = Onecky.new(10)
+ assert_raises(TimeoutError) do
+ @there.do_timeout(ten)
+ end
+ assert_raises(TimeoutError) do
+ @there.do_timeout(ten)
+ end
+ end
+
+ def test_07_public_private_protected_missing
+ assert_nothing_raised() {
+ begin
+ @there.method_missing(:eval)
+ rescue NoMethodError
+ assert_match(/^private method \`eval\'/, $!.message)
+ end
+ }
+ assert_nothing_raised() {
+ begin
+ @there.call_private_method
+ rescue NoMethodError
+ assert_equal(NoMethodError, $!.class)
+ assert_match(/^private method \`call_private_method\'/, $!.message)
+ end
+ }
+ assert_nothing_raised() {
+ begin
+ @there.call_protected_method
+ rescue NoMethodError
+ assert_equal(NoMethodError, $!.class)
+ assert_match(/^protected method \`call_protected_method\'/, $!.message)
+ end
+ }
+ assert_nothing_raised() {
+ begin
+ @there.method_missing(:undefined_method_test)
+ rescue NoMethodError
+ assert_equal(NoMethodError, $!.class)
+ assert_match(/^undefined method \`undefined_method_test\'/, $!.message)
+ end
+ }
+ assert_raises(SecurityError) do
+ @there.method_missing(:__send__, :to_s)
+ end
+ assert_equal(true, @there.missing)
+ end
+
+ def test_08_here
+ ro = DRbObject.new(nil, DRb.uri)
+ assert_kind_of(String, ro.to_s)
+
+ ro = DRbObject.new_with_uri(DRb.uri)
+ assert_kind_of(String, ro.to_s)
+ end
+
+ def uri_concat_option(uri, opt)
+ "#{uri}?#{opt}"
+ end
+
+ def test_09_option
+ uri = uri_concat_option(@there.__drburi, "foo")
+ ro = DRbObject.new_with_uri(uri)
+ assert_equal(ro.__drburi, @there.__drburi)
+ assert_equal(3, ro.size)
+
+ uri = uri_concat_option(@there.__drburi, "")
+ ro = DRbObject.new_with_uri(uri)
+ assert_equal(ro.__drburi, @there.__drburi)
+ assert_equal(DRb::DRbURIOption.new(''), ro.__drbref)
+
+ uri = uri_concat_option(@there.__drburi, "hello?world")
+ ro = DRbObject.new_with_uri(uri)
+ assert_equal(DRb::DRbURIOption.new('hello?world'), ro.__drbref)
+
+ uri = uri_concat_option(@there.__drburi, "?hello?world")
+ ro = DRbObject.new_with_uri(uri)
+ assert_equal(DRb::DRbURIOption.new('?hello?world'), ro.__drbref)
+ end
+
+ def test_10_yield
+ @there.simple_hash.each do |k, v|
+ assert_kind_of(String, k)
+ assert_kind_of(Symbol, v)
+ end
+ end
+
+ def test_10_yield_undumped
+ @there.xarray2_hash.each do |k, v|
+ assert_kind_of(String, k)
+ assert_kind_of(DRbObject, v)
+ end
+ end
+
+ def test_11_remote_no_method_error
+ assert_raises(DRb::DRbRemoteError) do
+ @there.remote_no_method_error
+ end
+ begin
+ @there.remote_no_method_error
+ rescue
+ error = $!
+ assert_match(/^undefined method .*\(NoMethodError\)/, error.message)
+ assert_equal('NoMethodError', error.reason)
+ end
+ end
+end
+
+module DRbAry
+ def setup
+ @ext = DRbService.ext_service('ut_array.rb')
+ @there = @ext.front
+ end
+
+ def teardown
+ @ext.stop_service if @ext
+ end
+
+ def test_01
+ assert_kind_of(DRb::DRbObject, @there)
+ end
+
+ def test_02_collect
+ ary = @there.collect do |x| x + x end
+ assert_kind_of(Array, ary)
+ assert_equal([2, 4, 'IIIIII', 8, 'fivefive', 12], ary)
+ end
+
+ def test_03_redo
+ ary = []
+ count = 0
+ @there.each do |x|
+ count += 1
+ ary.push x
+ redo if count == 3
+ end
+ assert_equal([1, 2, 'III', 'III', 4, 'five', 6], ary)
+ end
+
+ def test_04_retry
+ retried = false
+ ary = []
+ @there.each do |x|
+ ary.push x
+ if x == 4 && !retried
+ retried = true
+ retry
+ end
+ end
+ assert_equal([1, 2, 'III', 4, 1, 2, 'III', 4, 'five', 6], ary)
+ end
+
+ def test_05_break
+ ary = []
+ @there.each do |x|
+ ary.push x
+ break if x == 4
+ end
+ assert_equal([1, 2, 'III', 4], ary)
+ end
+
+ def test_06_next
+ ary = []
+ @there.each do |x|
+ next if String === x
+ ary.push x
+ end
+ assert_equal([1, 2, 4, 6], ary)
+ end
+
+ class_eval <<EOS
+ def test_07_break_18
+ ary = []
+ result = @there.each do |x|
+ ary.push x
+ break(:done) if x == 4
+ end
+ assert_equal([1, 2, 'III', 4], ary)
+ assert_equal(:done, result)
+ end
+EOS
+
+end
diff --git a/ruby_1_8_6/test/drb/ignore_test_drb.rb b/ruby_1_8_6/test/drb/ignore_test_drb.rb
new file mode 100644
index 0000000000..d0bb1f49b0
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ignore_test_drb.rb
@@ -0,0 +1,24 @@
+require 'drbtest'
+
+class TestDRbReusePort < Test::Unit::TestCase
+ include DRbAry
+
+ def setup
+ @ext = DRbService.ext_service('ut_port.rb')
+ @there = @ext.front
+ end
+
+ def teardown
+ return unless @ext
+ @ext.stop_service
+ while true
+ sleep 0.1
+ begin
+ @ext.alive?
+ rescue DRb::DRbConnError
+ break
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/drb/test_acl.rb b/ruby_1_8_6/test/drb/test_acl.rb
new file mode 100644
index 0000000000..d8955e0e75
--- /dev/null
+++ b/ruby_1_8_6/test/drb/test_acl.rb
@@ -0,0 +1,195 @@
+# acltest.rb - ACL unit test
+# Copyright (c) 2000 Masatoshi SEKI
+#
+# acltest.rb is copyrighted free software by Masatoshi SEKI.
+# You can redistribute it and/or modify it under the same terms as Ruby.
+
+require 'test/unit'
+require 'drb/acl'
+
+class SampleHosts
+ def initialize
+ list = %w(127.0.0.1 localhost
+ 192.168.1.1 x68k.linux.or.jp
+ 192.168.1.2 lc630.macos.or.jp
+ 192.168.1.3 lib30.win32.or.jp
+ 192.168.1.4 ns00.linux.or.jp
+ 192.168.1.5 yum.macos.or.jp
+ ::ffff:192.168.1.5 ipv6.macos.or.jp
+ ::192.168.1.5 too.yumipv6.macos.or.jp
+ 192.168.1.254 comstarz.foo.or.jp)
+
+ @hostlist = Array.new(list.size / 2)
+ @hostlist.each_index do |idx|
+ @hostlist[idx] = ["AF_INET", 10000, list[idx * 2 + 1], list[idx * 2]]
+ end
+
+ @hosts = Hash.new
+ @hostlist.each do |h|
+ @hosts[h[2].split('.')[0]] = h
+ end
+ end
+ attr_reader(:hostlist, :hosts)
+end
+
+
+class ACLEntryTest < Test::Unit::TestCase
+ HOSTS = SampleHosts.new
+
+ def setup
+ @hostlist = HOSTS.hostlist
+ @hosts = HOSTS.hosts
+ end
+
+ def test_all
+ a = ACL::ACLEntry.new("*")
+ b = ACL::ACLEntry.new("all")
+ @hostlist.each do |h|
+ assert(a.match(h))
+ assert(b.match(h))
+ end
+ end
+
+ def test_ip_v6
+ a = ACL::ACLEntry.new('::ffff:192.0.0.0/104')
+ assert(! a.match(@hosts['localhost']))
+ assert(a.match(@hosts['yum']))
+ assert(a.match(@hosts['ipv6']))
+ assert(! a.match(@hosts['too']))
+ end
+
+ def test_ip
+ a = ACL::ACLEntry.new('192.0.0.0/8')
+ assert(! a.match(@hosts['localhost']))
+ assert(a.match(@hosts['yum']))
+
+ a = ACL::ACLEntry.new('192.168.0.1/255.255.0.255')
+ assert(! a.match(@hosts['localhost']))
+ assert(! a.match(@hosts['yum']))
+ assert(a.match(@hosts['x68k']))
+
+ a = ACL::ACLEntry.new('192.168.1.0/24')
+ assert(! a.match(@hosts['localhost']))
+ assert(a.match(@hosts['yum']))
+ assert(a.match(@hosts['x68k']))
+
+ a = ACL::ACLEntry.new('92.0.0.0/8')
+ assert(! a.match(@hosts['localhost']))
+ assert(! a.match(@hosts['yum']))
+ assert(! a.match(@hosts['x68k']))
+
+ a = ACL::ACLEntry.new('127.0.0.1/255.0.0.255')
+ assert(a.match(@hosts['localhost']))
+ assert(! a.match(@hosts['yum']))
+ assert(! a.match(@hosts['x68k']))
+ end
+
+ def test_name
+ a = ACL::ACLEntry.new('*.jp')
+ assert(! a.match(@hosts['localhost']))
+ assert(a.match(@hosts['yum']))
+
+ a = ACL::ACLEntry.new('yum.*.jp')
+ assert(a.match(@hosts['yum']))
+ assert(! a.match(@hosts['lc630']))
+
+ a = ACL::ACLEntry.new('*.macos.or.jp')
+ assert(a.match(@hosts['yum']))
+ assert(a.match(@hosts['lc630']))
+ assert(! a.match(@hosts['lib30']))
+ end
+end
+
+class ACLListTest < Test::Unit::TestCase
+ HOSTS = SampleHosts.new
+
+ def setup
+ @hostlist = HOSTS.hostlist
+ @hosts = HOSTS.hosts
+ end
+
+ private
+ def build(list)
+ acl= ACL::ACLList.new
+ list.each do |s|
+ acl.add s
+ end
+ acl
+ end
+
+ public
+ def test_all_1
+ a = build(%w(all))
+ @hostlist.each do |h|
+ assert(a.match(h))
+ end
+ end
+
+ def test_all_2
+ a = build(%w(localhost 127.0.0.0/8 yum.* *))
+ @hostlist.each do |h|
+ assert(a.match(h))
+ end
+ end
+
+ def test_1
+ a = build(%w(192.0.0.1/255.0.0.255 yum.*.jp))
+ assert(a.match(@hosts['yum']))
+ assert(a.match(@hosts['x68k']))
+ assert(! a.match(@hosts['lc630']))
+ end
+
+ def test_2
+ a = build(%w(*.linux.or.jp))
+ assert(!a.match(@hosts['yum']))
+ assert(a.match(@hosts['x68k']))
+ assert(!a.match(@hosts['lc630']))
+ end
+end
+
+class ACLTest < Test::Unit::TestCase
+ HOSTS = SampleHosts.new
+
+ def setup
+ @hostlist = HOSTS.hostlist
+ @hosts = HOSTS.hosts
+ end
+
+ def test_0
+ a = ACL.new
+ @hostlist.each do |h|
+ assert(a.allow_addr?(h))
+ end
+ end
+
+ def test_not_0
+ a = ACL.new([], ACL::ALLOW_DENY)
+ @hostlist.each do |h|
+ assert(! a.allow_addr?(h))
+ end
+ end
+
+ def test_1
+ data = %w(deny all
+ allow localhost
+ allow x68k.*)
+
+ a = ACL.new(data)
+ assert(a.allow_addr?(@hosts['x68k']))
+ assert(a.allow_addr?(@hosts['localhost']))
+ assert(! a.allow_addr?(@hosts['lc630']))
+ end
+
+ def test_not_1
+ data = %w(deny 192.0.0.0/8
+ allow localhost
+ allow x68k.*)
+
+ a = ACL.new(data, ACL::ALLOW_DENY)
+ assert(!a.allow_addr?(@hosts['x68k']))
+ assert(a.allow_addr?(@hosts['localhost']))
+ assert(! a.allow_addr?(@hosts['lc630']))
+ end
+end
+
+
diff --git a/ruby_1_8_6/test/drb/test_drb.rb b/ruby_1_8_6/test/drb/test_drb.rb
new file mode 100644
index 0000000000..5719f60b80
--- /dev/null
+++ b/ruby_1_8_6/test/drb/test_drb.rb
@@ -0,0 +1,301 @@
+require 'drbtest'
+
+class TestDRbCore < Test::Unit::TestCase
+ include DRbCore
+end
+
+class TestDRbYield < Test::Unit::TestCase
+ def setup
+ @ext = DRbService.ext_service('ut_drb.rb')
+ @there = @ext.front
+ end
+
+ def teardown
+ @ext.stop_service if @ext
+ end
+
+ def test_01_one
+ @there.echo_yield_1([]) {|one|
+ assert_equal([], one)
+ }
+
+ @there.echo_yield_1(1) {|one|
+ assert_equal(1, one)
+ }
+
+ @there.echo_yield_1(nil) {|one|
+ assert_equal(nil, one)
+ }
+ end
+
+ def test_02_two
+ @there.echo_yield_2([], []) {|one, two|
+ assert_equal([], one)
+ assert_equal([], two)
+ }
+
+ @there.echo_yield_2(1, 2) {|one, two|
+ assert_equal(1, one)
+ assert_equal(2, two)
+ }
+
+ @there.echo_yield_2(3, nil) {|one, two|
+ assert_equal(3, one)
+ assert_equal(nil, two)
+ }
+
+ @there.echo_yield_1([:key, :value]) {|one, two|
+ assert_equal(:key, one)
+ assert_equal(:value, two)
+ }
+ end
+
+ def test_03_many
+ @there.echo_yield_0 {|*s|
+ assert_equal([], s)
+ }
+ @there.echo_yield(nil) {|*s|
+ assert_equal([nil], s)
+ }
+ @there.echo_yield(1) {|*s|
+ assert_equal([1], s)
+ }
+ @there.echo_yield(1, 2) {|*s|
+ assert_equal([1, 2], s)
+ }
+ @there.echo_yield(1, 2, 3) {|*s|
+ assert_equal([1, 2, 3], s)
+ }
+ @there.echo_yield([], []) {|*s|
+ assert_equal([[], []], s)
+ }
+ @there.echo_yield([]) {|*s|
+ assert_equal([[]], s) # !
+ }
+ end
+
+ def test_04_many_to_one
+ @there.echo_yield_0 {|*s|
+ assert_equal([], s)
+ }
+ @there.echo_yield(nil) {|*s|
+ assert_equal([nil], s)
+ }
+ @there.echo_yield(1) {|*s|
+ assert_equal([1], s)
+ }
+ @there.echo_yield(1, 2) {|*s|
+ assert_equal([1, 2], s)
+ }
+ @there.echo_yield(1, 2, 3) {|*s|
+ assert_equal([1, 2, 3], s)
+ }
+ @there.echo_yield([], []) {|*s|
+ assert_equal([[], []], s)
+ }
+ @there.echo_yield([]) {|*s|
+ assert_equal([[]], s)
+ }
+ end
+
+ def test_05_array_subclass
+ @there.xarray_each {|x| assert_kind_of(XArray, x)}
+ @there.xarray_each {|*x| assert_kind_of(XArray, x[0])}
+ end
+
+ def test_06_taint
+ x = proc {}
+ assert(! x.tainted?)
+ @there.echo_yield(x) {|o|
+ assert_equal(x, o)
+ assert(! x.tainted?)
+ }
+ end
+end
+
+class TestRubyYield < TestDRbYield
+ def echo_yield(*arg)
+ yield(*arg)
+ end
+
+ def echo_yield_0
+ yield
+ end
+
+ def echo_yield_1(a)
+ yield(a)
+ end
+
+ def echo_yield_2(a, b)
+ yield(a, b)
+ end
+
+ def xarray_each
+ xary = [XArray.new([0])]
+ xary.each do |x|
+ yield(x)
+ end
+ end
+
+ def setup
+ @there = self
+ end
+
+ def teardown
+ end
+end
+
+class TestRuby18Yield < TestRubyYield
+ class YieldTest18
+ def echo_yield(*arg, &proc)
+ proc.call(*arg)
+ end
+
+ def echo_yield_0(&proc)
+ proc.call
+ end
+
+ def echo_yield_1(a, &proc)
+ proc.call(a)
+ end
+
+ def echo_yield_2(a, b, &proc)
+ proc.call(a, b)
+ end
+
+ def xarray_each(&proc)
+ xary = [XArray.new([0])]
+ xary.each(&proc)
+ end
+
+ end
+
+ def setup
+ @there = YieldTest18.new
+ end
+end
+
+class TestDRbAry < Test::Unit::TestCase
+ include DRbAry
+end
+
+class TestDRbMServer < Test::Unit::TestCase
+ def setup
+ @ext = DRbService.ext_service('ut_drb.rb')
+ @there = @ext.front
+ @server = (1..3).collect do |n|
+ DRb::DRbServer.new(nil, Onecky.new(n.to_s))
+ end
+ end
+
+ def teardown
+ @server.each do |s|
+ s.stop_service
+ end
+ @ext.stop_service if @ext
+ end
+
+ def test_01
+ assert_equal(6, @there.sample(@server[0].front, @server[1].front, @server[2].front))
+ end
+end
+
+class TestDRbSafe1 < TestDRbAry
+ def setup
+ @ext = DRbService.ext_service('ut_safe1.rb')
+ @there = @ext.front
+ end
+end
+
+class TestDRbEval < Test::Unit::TestCase
+ def setup
+ super
+ @ext = DRbService.ext_service('ut_eval.rb')
+ @there = @ext.front
+ end
+
+ def teardown
+ @ext.stop_service if @ext
+ end
+
+ def test_01_safe1_safe4_eval
+ assert_raises(SecurityError) do
+ @there.method_missing(:instance_eval, 'ENV.inspect')
+ end
+
+ assert_raises(SecurityError) do
+ @there.method_missing(:send, :eval, 'ENV.inspect')
+ end
+
+ remote_class = @there.remote_class
+
+ assert_raises(SecurityError) do
+ remote_class.class_eval('ENV.inspect')
+ end
+
+ assert_raises(SecurityError) do
+ remote_class.module_eval('ENV.inspect')
+ end
+
+ four = @there.four
+ assert_equal(1, four.method_missing(:send, :eval, '1'))
+
+ remote_class = four.remote_class
+
+ assert_equal(1, remote_class.class_eval('1'))
+
+ assert_equal(1, remote_class.module_eval('1'))
+
+ assert_raises(SecurityError) do
+ remote_class.class_eval('ENV = {}')
+ end
+
+ assert_raises(SecurityError) do
+ remote_class.module_eval('ENV = {}')
+ end
+ end
+end
+
+class TestDRbLarge < Test::Unit::TestCase
+ def setup
+ @ext = DRbService.ext_service('ut_large.rb')
+ @there = @ext.front
+ end
+
+ def teardown
+ @ext.stop_service if @ext
+ end
+
+ def test_01_large_ary
+ ary = [2] * 10240
+ assert_equal(10240, @there.size(ary))
+ assert_equal(20480, @there.sum(ary))
+ end
+
+ def test_02_large_ary
+ ary = ["Hello, World"] * 10240
+ assert_equal(10240, @there.size(ary))
+ end
+
+ def test_03_large_ary
+ ary = [Thread.current] * 10240
+ assert_equal(10240, @there.size(ary))
+ end
+
+ def test_04_many_arg
+ assert_raises(ArgumentError) {
+ @there.arg_test(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
+ }
+ end
+
+ def test_05_too_large_ary
+ ary = ["Hello, World"] * 102400
+ exception = nil
+ begin
+ @there.size(ary)
+ rescue StandardError
+ exception = $!
+ end
+ assert_kind_of(StandardError, exception)
+ end
+end
diff --git a/ruby_1_8_6/test/drb/test_drbssl.rb b/ruby_1_8_6/test/drb/test_drbssl.rb
new file mode 100644
index 0000000000..cfb3bc36a4
--- /dev/null
+++ b/ruby_1_8_6/test/drb/test_drbssl.rb
@@ -0,0 +1,62 @@
+require 'drbtest'
+
+begin
+ require 'drb/ssl'
+rescue LoadError
+end
+
+if Object.const_defined?("OpenSSL")
+
+
+class DRbSSLService < DRbService
+ %w(ut_drb_drbssl.rb ut_array_drbssl.rb).each do |nm|
+ add_service_command(nm)
+ end
+ config = Hash.new
+
+ config[:SSLVerifyMode] = OpenSSL::SSL::VERIFY_PEER
+ config[:SSLVerifyCallback] = lambda{ |ok,x509_store|
+ true
+ }
+ begin
+ data = open("sample.key"){|io| io.read }
+ config[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(data)
+ data = open("sample.crt"){|io| io.read }
+ config[:SSLCertificate] = OpenSSL::X509::Certificate.new(data)
+ rescue
+ # $stderr.puts "Switching to use self-signed certificate"
+ config[:SSLCertName] =
+ [ ["C","JP"], ["O","Foo.DRuby.Org"], ["CN", "Sample"] ]
+ end
+
+ uri = ARGV.shift if $0 == __FILE__
+ @server = DRb::DRbServer.new(uri || 'drbssl://:0', self.manager, config)
+end
+
+class TestDRbSSLCore < Test::Unit::TestCase
+ include DRbCore
+ def setup
+ @ext = DRbSSLService.ext_service('ut_drb_drbssl.rb')
+ @there = @ext.front
+ end
+
+ def test_02_unknown
+ end
+
+ def test_01_02_loop
+ end
+
+ def test_05_eq
+ end
+end
+
+class TestDRbSSLAry < Test::Unit::TestCase
+ include DRbAry
+ def setup
+ @ext = DRbSSLService.ext_service('ut_array_drbssl.rb')
+ @there = @ext.front
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/drb/test_drbunix.rb b/ruby_1_8_6/test/drb/test_drbunix.rb
new file mode 100644
index 0000000000..e1a17edd3d
--- /dev/null
+++ b/ruby_1_8_6/test/drb/test_drbunix.rb
@@ -0,0 +1,46 @@
+require 'drbtest'
+
+begin
+ require 'drb/unix'
+rescue LoadError
+end
+
+if Object.const_defined?("UNIXServer")
+
+
+class DRbUNIXService < DRbService
+ %w(ut_drb_drbunix.rb ut_array_drbunix.rb).each do |nm|
+ add_service_command(nm)
+ end
+
+ uri = ARGV.shift if $0 == __FILE__
+ @server = DRb::DRbServer.new(uri || 'drbunix:', self.manager, {})
+end
+
+class TestDRbUNIXCore < Test::Unit::TestCase
+ include DRbCore
+ def setup
+ @ext = DRbUNIXService.ext_service('ut_drb_drbunix.rb')
+ @there = @ext.front
+ end
+
+ def test_02_unknown
+ end
+
+ def test_01_02_loop
+ end
+
+ def test_05_eq
+ end
+end
+
+class TestDRbUNIXAry < Test::Unit::TestCase
+ include DRbAry
+ def setup
+ @ext = DRbUNIXService.ext_service('ut_array_drbunix.rb')
+ @there = @ext.front
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/drb/ut_array.rb b/ruby_1_8_6/test/drb/ut_array.rb
new file mode 100644
index 0000000000..6d9778ffbc
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_array.rb
@@ -0,0 +1,15 @@
+require 'drb/drb'
+require 'drb/extserv'
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <uri> <name>" unless it
+ it
+ end
+
+ DRb.start_service(nil, [1, 2, 'III', 4, "five", 6])
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
+
diff --git a/ruby_1_8_6/test/drb/ut_array_drbssl.rb b/ruby_1_8_6/test/drb/ut_array_drbssl.rb
new file mode 100644
index 0000000000..5644af5600
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_array_drbssl.rb
@@ -0,0 +1,24 @@
+require 'drb/drb'
+require 'drb/extserv'
+require 'drb/ssl'
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <uri> <name>" unless it
+ it
+ end
+
+ config = Hash.new
+ config[:SSLVerifyMode] = OpenSSL::SSL::VERIFY_PEER
+ config[:SSLVerifyCallback] = lambda{|ok,x509_store|
+ true
+ }
+ config[:SSLCertName] =
+ [ ["C","JP"], ["O","Foo.DRuby.Org"], ["CN", "Sample"] ]
+
+ DRb.start_service('drbssl://:0', [1, 2, 'III', 4, "five", 6], config)
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
+
diff --git a/ruby_1_8_6/test/drb/ut_array_drbunix.rb b/ruby_1_8_6/test/drb/ut_array_drbunix.rb
new file mode 100644
index 0000000000..76d2a610af
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_array_drbunix.rb
@@ -0,0 +1,15 @@
+require 'drb/drb'
+require 'drb/extserv'
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <uri> <name>" unless it
+ it
+ end
+
+ DRb.start_service('drbunix:', [1, 2, 'III', 4, "five", 6])
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
+
diff --git a/ruby_1_8_6/test/drb/ut_drb.rb b/ruby_1_8_6/test/drb/ut_drb.rb
new file mode 100644
index 0000000000..f5720cfca2
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_drb.rb
@@ -0,0 +1,160 @@
+require 'drb/drb'
+require 'drb/extserv'
+require 'timeout'
+
+class XArray < Array
+ def initialize(ary)
+ ary.each do |x|
+ self.push(x)
+ end
+ end
+end
+
+class XArray2 < XArray
+ include DRbUndumped
+end
+
+class Unknown2
+ def initialize
+ @foo = 'unknown2'
+ end
+end
+
+class DRbEx
+ include DRbUndumped
+
+ class FooBar
+ def initialize
+ @foo = 'bar'
+ end
+ end
+
+ class UError < RuntimeError; end
+
+ def initialize
+ @hello = 'hello'
+ end
+ attr_reader :hello
+
+ def sample(a, b, c)
+ a.to_i + b.to_i + c.to_i
+ end
+
+ def sum(*a)
+ s = 0
+ a.each do |e|
+ s += e.to_i
+ end
+ s
+ end
+
+ def do_timeout(n)
+ timeout(0.1) do
+ n.sleep(2)
+ end
+ end
+
+ def unknown_module
+ FooBar.new
+ end
+
+ def unknown_class
+ Unknown2.new
+ end
+
+ def unknown_error
+ raise UError
+ end
+
+ def remote_no_method_error
+ invoke_no_method(self)
+ end
+
+ def test_yield
+ yield
+ yield([])
+ yield(*[])
+ end
+
+ def echo_yield(*arg)
+ yield(*arg)
+ nil
+ end
+
+ def echo_yield_0
+ yield
+ nil
+ end
+
+ def echo_yield_1(one)
+ yield(one)
+ nil
+ end
+
+ def echo_yield_2(one, two)
+ yield(one, two)
+ nil
+ end
+
+ def xarray_each
+ xary = [XArray.new([0])]
+ xary.each do |x|
+ yield(x)
+ end
+ nil
+ end
+
+ def xarray2_hash
+ unless @xary2_hash
+ @xary2_hash = { "a" => XArray2.new([0]), "b" => XArray2.new([1]) }
+ end
+ DRbObject.new(@xary2_hash)
+ end
+
+ def simple_hash
+ unless @hash
+ @hash = { 'a'=>:a, 'b'=>:b }
+ end
+ DRbObject.new(@hash)
+ end
+
+ def [](key)
+ key.to_s
+ end
+
+ def to_a
+ [self]
+ end
+
+ def method_missing(msg, *a, &b)
+ if msg == :missing
+ return true
+ else
+ super(msg, *a, &b)
+ end
+ end
+
+ private
+ def call_private_method
+ true
+ end
+
+ protected
+ def call_protected_method
+ true
+ end
+end
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <manager-uri> <name>" unless it
+ it
+ end
+
+ DRb::DRbServer.default_argc_limit(8)
+ DRb::DRbServer.default_load_limit(4096)
+ DRb.start_service('druby://localhost:0', DRbEx.new)
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
diff --git a/ruby_1_8_6/test/drb/ut_drb_drbssl.rb b/ruby_1_8_6/test/drb/ut_drb_drbssl.rb
new file mode 100644
index 0000000000..0a2191e71a
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_drb_drbssl.rb
@@ -0,0 +1,25 @@
+require "#{File.dirname(File.expand_path(__FILE__))}/ut_drb"
+require 'drb/ssl'
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <manager-uri> <name>" unless it
+ it
+ end
+
+ config = Hash.new
+ config[:SSLVerifyMode] = OpenSSL::SSL::VERIFY_PEER
+ config[:SSLVerifyCallback] = lambda{|ok,x509_store|
+ true
+ }
+ config[:SSLCertName] =
+ [ ["C","JP"], ["O","Foo.DRuby.Org"], ["CN", "Sample"] ]
+
+ DRb::DRbServer.default_argc_limit(8)
+ DRb::DRbServer.default_load_limit(4096)
+ DRb.start_service('drbssl://localhost:0', DRbEx.new, config)
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
+
diff --git a/ruby_1_8_6/test/drb/ut_drb_drbunix.rb b/ruby_1_8_6/test/drb/ut_drb_drbunix.rb
new file mode 100644
index 0000000000..8b9484cf9c
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_drb_drbunix.rb
@@ -0,0 +1,16 @@
+require "#{File.dirname(File.expand_path(__FILE__))}/ut_drb"
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <manager-uri> <name>" unless it
+ it
+ end
+
+ DRb::DRbServer.default_argc_limit(8)
+ DRb::DRbServer.default_load_limit(4096)
+ DRb.start_service('drbunix:', DRbEx.new)
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
+
diff --git a/ruby_1_8_6/test/drb/ut_eval.rb b/ruby_1_8_6/test/drb/ut_eval.rb
new file mode 100644
index 0000000000..4df963e7cd
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_eval.rb
@@ -0,0 +1,31 @@
+require 'drb/drb'
+require 'drb/extserv'
+
+class EvalAttack
+ def initialize
+ @four = DRb::DRbServer.new('druby://localhost:0', self, {:safe_level => 4})
+ end
+
+ def four
+ DRbObject.new_with_uri(@four.uri)
+ end
+
+ def remote_class
+ DRbObject.new(self.class)
+ end
+end
+
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <uri> <name>" unless it
+ it
+ end
+
+ $SAFE = 1
+
+ DRb.start_service('druby://localhost:0', EvalAttack.new, {:safe_level => 2})
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
diff --git a/ruby_1_8_6/test/drb/ut_large.rb b/ruby_1_8_6/test/drb/ut_large.rb
new file mode 100644
index 0000000000..d6717c5589
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_large.rb
@@ -0,0 +1,38 @@
+require 'drb/drb'
+require 'drb/extserv'
+require 'timeout'
+
+class DRbLarge
+ include DRbUndumped
+
+ def size(ary)
+ ary.size
+ end
+
+ def sum(ary)
+ sum = 0
+ ary.each do |e|
+ sum += e.to_i
+ end
+ sum
+ end
+
+ def arg_test(*arg)
+ # nop
+ end
+end
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <manager-uri> <name>" unless it
+ it
+ end
+
+ DRb::DRbServer.default_argc_limit(3)
+ DRb::DRbServer.default_load_limit(100000)
+ DRb.start_service('druby://localhost:0', DRbLarge.new)
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
+
diff --git a/ruby_1_8_6/test/drb/ut_port.rb b/ruby_1_8_6/test/drb/ut_port.rb
new file mode 100644
index 0000000000..337e0eda86
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_port.rb
@@ -0,0 +1,14 @@
+require 'drb/drb'
+require 'drb/extserv'
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <uri> <name>" unless it
+ it
+ end
+
+ DRb.start_service('druby://:8473', [1, 2, 'III', 4, "five", 6])
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
diff --git a/ruby_1_8_6/test/drb/ut_safe1.rb b/ruby_1_8_6/test/drb/ut_safe1.rb
new file mode 100644
index 0000000000..4df8e1e5a1
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_safe1.rb
@@ -0,0 +1,15 @@
+require 'drb/drb'
+require 'drb/extserv'
+
+if __FILE__ == $0
+ def ARGV.shift
+ it = super()
+ raise "usage: #{$0} <uri> <name>" unless it
+ it
+ end
+
+ DRb.start_service('druby://localhost:0', [1, 2, 'III', 4, "five", 6],
+ {:safe_level => 1})
+ es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
+ DRb.thread.join
+end
diff --git a/ruby_1_8_6/test/drb/ut_timerholder.rb b/ruby_1_8_6/test/drb/ut_timerholder.rb
new file mode 100644
index 0000000000..141cb73302
--- /dev/null
+++ b/ruby_1_8_6/test/drb/ut_timerholder.rb
@@ -0,0 +1,49 @@
+require 'runit/testcase'
+require 'runit/cui/testrunner'
+require 'timerholder'
+
+class TimerHolderTest < RUNIT::TestCase
+ def do_test(timeout, keeper_sleep = nil)
+ holder = TimerHolder.new(timeout)
+ holder.keeper_sleep = keeper_sleep if keeper_sleep
+ key = holder.add(self)
+ sleep(timeout * 0.5)
+ assert_equal(holder.peek(key), self)
+ holder.delete(key)
+ assert(!holder.include?(key))
+ key = holder.add(self)
+ sleep(timeout+0.5)
+ assert_equal(holder.fetch(key), nil)
+ key = holder.add(self)
+ assert_equal(holder.fetch(key), self)
+ holder.store(key, true)
+ assert_equal(holder.fetch(key), true)
+ assert_equal(holder.include?(key), true)
+ sleep(timeout+0.5)
+ assert_exception(TimerHolder::InvalidIndexError) do
+ holder.store(key, 1)
+ end
+ assert_equal(holder.include?(key), false)
+ key = holder.add(self)
+ sleep(timeout * 0.5)
+ assert(holder.include?(key))
+ holder.extend(key, timeout)
+ sleep(timeout * 0.5)
+ assert(holder.include?(key))
+ sleep(timeout * 0.6)
+ assert(!holder.include?(key))
+ holder.delete(key)
+ end
+
+ def test_00
+ do_test(0.5)
+ end
+
+ def test_01
+ do_test(1, 0.5)
+ end
+end
+
+if __FILE__ == $0
+ RUNIT::CUI::TestRunner.run(TimerHolderTest.suite)
+end
diff --git a/ruby_1_8_6/test/erb/test_erb.rb b/ruby_1_8_6/test/erb/test_erb.rb
new file mode 100644
index 0000000000..8641197414
--- /dev/null
+++ b/ruby_1_8_6/test/erb/test_erb.rb
@@ -0,0 +1,40 @@
+require 'test/unit'
+require 'erb'
+
+class TestERB < Test::Unit::TestCase
+ class MyError < RuntimeError ; end
+
+ def test_without_filename
+ erb = ERB.new("<% raise ::TestERB::MyError %>")
+ e = assert_raise(MyError) {
+ erb.result
+ }
+ assert_equal("(erb):1", e.backtrace[0])
+ end
+
+ def test_with_filename
+ erb = ERB.new("<% raise ::TestERB::MyError %>")
+ erb.filename = "test filename"
+ e = assert_raise(MyError) {
+ erb.result
+ }
+ assert_equal("test filename:1", e.backtrace[0])
+ end
+
+ def test_without_filename_with_safe_level
+ erb = ERB.new("<% raise ::TestERB::MyError %>", 1)
+ e = assert_raise(MyError) {
+ erb.result
+ }
+ assert_equal("(erb):1", e.backtrace[0])
+ end
+
+ def test_with_filename_and_safe_level
+ erb = ERB.new("<% raise ::TestERB::MyError %>", 1)
+ erb.filename = "test filename"
+ e = assert_raise(MyError) {
+ erb.result
+ }
+ assert_equal("test filename:1", e.backtrace[0])
+ end
+end
diff --git a/ruby_1_8_6/test/fileutils/fileasserts.rb b/ruby_1_8_6/test/fileutils/fileasserts.rb
new file mode 100644
index 0000000000..c2e9244a96
--- /dev/null
+++ b/ruby_1_8_6/test/fileutils/fileasserts.rb
@@ -0,0 +1,67 @@
+# $Id$
+
+module Test
+ module Unit
+ module Assertions # redefine
+
+ def assert_same_file(from, to)
+ _wrap_assertion {
+ assert_block("file #{from} != #{to}") {
+ File.read(from) == File.read(to)
+ }
+ }
+ end
+
+ def assert_same_entry(from, to)
+ a = File.stat(from)
+ b = File.stat(to)
+ assert_equal a.mode, b.mode, "mode #{a.mode} != #{b.mode}"
+ #assert_equal a.atime, b.atime
+ assert_equal a.mtime, b.mtime, "mtime #{a.mtime} != #{b.mtime}"
+ assert_equal a.uid, b.uid, "uid #{a.uid} != #{b.uid}"
+ assert_equal a.gid, b.gid, "gid #{a.gid} != #{b.gid}"
+ end
+
+ def assert_file_exist(path)
+ _wrap_assertion {
+ assert_block("file not exist: #{path}") {
+ File.exist?(path)
+ }
+ }
+ end
+
+ def assert_file_not_exist(path)
+ _wrap_assertion {
+ assert_block("file not exist: #{path}") {
+ not File.exist?(path)
+ }
+ }
+ end
+
+ def assert_directory(path)
+ _wrap_assertion {
+ assert_block("is not directory: #{path}") {
+ File.directory?(path)
+ }
+ }
+ end
+
+ def assert_symlink(path)
+ _wrap_assertion {
+ assert_block("is not a symlink: #{path}") {
+ File.symlink?(path)
+ }
+ }
+ end
+
+ def assert_not_symlink(path)
+ _wrap_assertion {
+ assert_block("is a symlink: #{path}") {
+ not File.symlink?(path)
+ }
+ }
+ end
+
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/fileutils/test_dryrun.rb b/ruby_1_8_6/test/fileutils/test_dryrun.rb
new file mode 100644
index 0000000000..2fdd65d2f6
--- /dev/null
+++ b/ruby_1_8_6/test/fileutils/test_dryrun.rb
@@ -0,0 +1,25 @@
+# $Id$
+
+require 'test/unit'
+require 'fileutils'
+
+class TestFileUtilsDryRun < Test::Unit::TestCase
+
+ include FileUtils::DryRun
+
+ def test_visibility
+ FileUtils::METHODS.each do |m|
+ assert_equal true, FileUtils::DryRun.respond_to?(m, true),
+ "FileUtils::DryRun.#{m} not defined"
+ assert_equal true, FileUtils::DryRun.respond_to?(m, false),
+ "FileUtils::DryRun.#{m} not public"
+ end
+ FileUtils::METHODS.each do |m|
+ assert_equal true, respond_to?(m, true)
+ "FileUtils::DryRun\##{m} is not defined"
+ assert_equal true, FileUtils::DryRun.private_method_defined?(m),
+ "FileUtils::DryRun\##{m} is not private"
+ end
+ end
+
+end
diff --git a/ruby_1_8_6/test/fileutils/test_fileutils.rb b/ruby_1_8_6/test/fileutils/test_fileutils.rb
new file mode 100644
index 0000000000..cab51c9e8c
--- /dev/null
+++ b/ruby_1_8_6/test/fileutils/test_fileutils.rb
@@ -0,0 +1,1085 @@
+# $Id$
+
+require 'fileutils'
+require 'fileasserts'
+require 'pathname'
+require 'tmpdir'
+require 'test/unit'
+
+class TestFileUtils < Test::Unit::TestCase
+ TMPROOT = "#{Dir.tmpdir}/fileutils.rb.#{$$}"
+end
+
+prevdir = Dir.pwd
+tmproot = TestFileUtils::TMPROOT
+Dir.mkdir tmproot unless File.directory?(tmproot)
+Dir.chdir tmproot
+
+def have_drive_letter?
+ /djgpp|mswin(?!ce)|mingw|bcc|emx/ =~ RUBY_PLATFORM
+end
+
+def have_file_perm?
+ /djgpp|mswin|mingw|bcc|wince|emx/ !~ RUBY_PLATFORM
+end
+
+$fileutils_rb_have_symlink = nil
+
+def have_symlink?
+ if $fileutils_rb_have_symlink == nil
+ $fileutils_rb_have_symlink = check_have_symlink?
+ end
+ $fileutils_rb_have_symlink
+end
+
+def check_have_symlink?
+ File.symlink nil, nil
+rescue NotImplementedError
+ return false
+rescue
+ return true
+end
+
+$fileutils_rb_have_hardlink = nil
+
+def have_hardlink?
+ if $fileutils_rb_have_hardlink == nil
+ $fileutils_rb_have_hardlink = check_have_hardlink?
+ end
+ $fileutils_rb_have_hardlink
+end
+
+def check_have_hardlink?
+ File.link nil, nil
+rescue NotImplementedError
+ return false
+rescue
+ return true
+end
+
+begin
+ Dir.mkdir("\n")
+ Dir.rmdir("\n")
+ def lf_in_path_allowed?
+ true
+ end
+rescue
+ def lf_in_path_allowed?
+ false
+ end
+end
+
+Dir.chdir prevdir
+Dir.rmdir tmproot
+
+class TestFileUtils
+
+ include FileUtils
+
+ def check_singleton(name)
+ assert_equal true, ::FileUtils.public_methods.include?(name.to_s)
+ end
+
+ def my_rm_rf(path)
+ if File.exist?('/bin/rm')
+ system %Q[/bin/rm -rf "#{path}"]
+ else
+ FileUtils.rm_rf path
+ end
+ end
+
+ def mymkdir(path)
+ Dir.mkdir path
+ File.chown nil, Process.gid, path if have_file_perm?
+ end
+
+ def setup
+ @prevdir = Dir.pwd
+ tmproot = TMPROOT
+ mymkdir tmproot unless File.directory?(tmproot)
+ Dir.chdir tmproot
+ my_rm_rf 'data'; mymkdir 'data'
+ my_rm_rf 'tmp'; mymkdir 'tmp'
+ prepare_data_file
+ end
+
+ def teardown
+ tmproot = Dir.pwd
+ Dir.chdir @prevdir
+ my_rm_rf tmproot
+ end
+
+
+ TARGETS = %w( data/a data/all data/random data/zero )
+
+ def prepare_data_file
+ File.open('data/a', 'w') {|f|
+ 32.times do
+ f.puts 'a' * 50
+ end
+ }
+
+ all_chars = (0..255).map {|n| n.chr }.join('')
+ File.open('data/all', 'w') {|f|
+ 32.times do
+ f.puts all_chars
+ end
+ }
+
+ random_chars = (0...50).map { rand(256).chr }.join('')
+ File.open('data/random', 'w') {|f|
+ 32.times do
+ f.puts random_chars
+ end
+ }
+
+ File.open('data/zero', 'w') {|f|
+ ;
+ }
+ end
+
+ BIGFILE = 'data/big'
+
+ def prepare_big_file
+ File.open('data/big', 'w') {|f|
+ (4 * 1024 * 1024 / 256).times do # 4MB
+ f.print "aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa\n"
+ end
+ }
+ end
+
+ def prepare_time_data
+ File.open('data/old', 'w') {|f| f.puts 'dummy' }
+ File.open('data/newer', 'w') {|f| f.puts 'dummy' }
+ File.open('data/newest', 'w') {|f| f.puts 'dummy' }
+ t = Time.now
+ File.utime t-8, t-8, 'data/old'
+ File.utime t-4, t-4, 'data/newer'
+ end
+
+ def each_srcdest
+ TARGETS.each do |path|
+ yield path, "tmp/#{File.basename(path)}"
+ end
+ end
+
+ #
+ # Test Cases
+ #
+
+ def test_pwd
+ check_singleton :pwd
+
+ assert_equal Dir.pwd, pwd()
+
+ cwd = Dir.pwd
+if have_drive_letter?
+ cd('C:/') {
+ assert_equal 'C:/', pwd()
+ }
+ assert_equal cwd, pwd()
+else
+ cd('/') {
+ assert_equal '/', pwd()
+ }
+ assert_equal cwd, pwd()
+end
+ end
+
+ def test_cmp
+ check_singleton :cmp
+
+ TARGETS.each do |fname|
+ assert cmp(fname, fname), 'not same?'
+ end
+ assert_raises(ArgumentError) {
+ cmp TARGETS[0], TARGETS[0], :undefinedoption => true
+ }
+
+ # pathname
+ touch 'tmp/cmptmp'
+ assert_nothing_raised {
+ cmp Pathname.new('tmp/cmptmp'), 'tmp/cmptmp'
+ cmp 'tmp/cmptmp', Pathname.new('tmp/cmptmp')
+ cmp Pathname.new('tmp/cmptmp'), Pathname.new('tmp/cmptmp')
+ }
+ end
+
+ def test_cp
+ check_singleton :cp
+
+ each_srcdest do |srcpath, destpath|
+ cp srcpath, destpath
+ assert_same_file srcpath, destpath
+
+ cp srcpath, File.dirname(destpath)
+ assert_same_file srcpath, destpath
+
+ cp srcpath, File.dirname(destpath) + '/'
+ assert_same_file srcpath, destpath
+
+ cp srcpath, destpath, :preserve => true
+ assert_same_file srcpath, destpath
+ assert_same_entry srcpath, destpath
+ end
+
+ # src==dest (1) same path
+ touch 'tmp/cptmp'
+ assert_raises(ArgumentError) {
+ cp 'tmp/cptmp', 'tmp/cptmp'
+ }
+if have_symlink?
+ # src==dest (2) symlink and its target
+ File.symlink 'cptmp', 'tmp/cptmp_symlink'
+ assert_raises(ArgumentError) {
+ cp 'tmp/cptmp', 'tmp/cptmp_symlink'
+ }
+ assert_raises(ArgumentError) {
+ cp 'tmp/cptmp_symlink', 'tmp/cptmp'
+ }
+ # src==dest (3) looped symlink
+ File.symlink 'symlink', 'tmp/symlink'
+ assert_raises(Errno::ELOOP) {
+ cp 'tmp/symlink', 'tmp/symlink'
+ }
+end
+
+ # pathname
+ assert_nothing_raised {
+ cp 'tmp/cptmp', Pathname.new('tmp/tmpdest')
+ cp Pathname.new('tmp/cptmp'), 'tmp/tmpdest'
+ cp Pathname.new('tmp/cptmp'), Pathname.new('tmp/tmpdest')
+ mkdir 'tmp/tmpdir'
+ cp ['tmp/cptmp', 'tmp/tmpdest'], Pathname.new('tmp/tmpdir')
+ }
+ end
+
+ def test_cp_r
+ check_singleton :cp_r
+
+ cp_r 'data', 'tmp'
+ TARGETS.each do |fname|
+ assert_same_file fname, "tmp/#{fname}"
+ end
+
+ cp_r 'data', 'tmp2', :preserve => true
+ TARGETS.each do |fname|
+ assert_same_entry fname, "tmp2/#{File.basename(fname)}"
+ assert_same_file fname, "tmp2/#{File.basename(fname)}"
+ end
+
+ # a/* -> b/*
+ mkdir 'tmp/cpr_src'
+ mkdir 'tmp/cpr_dest'
+ File.open('tmp/cpr_src/a', 'w') {|f| f.puts 'a' }
+ File.open('tmp/cpr_src/b', 'w') {|f| f.puts 'b' }
+ File.open('tmp/cpr_src/c', 'w') {|f| f.puts 'c' }
+ mkdir 'tmp/cpr_src/d'
+ cp_r 'tmp/cpr_src/.', 'tmp/cpr_dest'
+ assert_same_file 'tmp/cpr_src/a', 'tmp/cpr_dest/a'
+ assert_same_file 'tmp/cpr_src/b', 'tmp/cpr_dest/b'
+ assert_same_file 'tmp/cpr_src/c', 'tmp/cpr_dest/c'
+ assert_directory 'tmp/cpr_dest/d'
+ my_rm_rf 'tmp/cpr_src'
+ my_rm_rf 'tmp/cpr_dest'
+
+if have_symlink?
+ # symlink in a directory
+ mkdir 'tmp/cpr_src'
+ ln_s 'SLdest', 'tmp/cpr_src/symlink'
+ cp_r 'tmp/cpr_src', 'tmp/cpr_dest'
+ assert_symlink 'tmp/cpr_dest/symlink'
+ assert_equal 'SLdest', File.readlink('tmp/cpr_dest/symlink')
+
+ # root is a symlink
+ ln_s 'cpr_src', 'tmp/cpr_src2'
+ cp_r 'tmp/cpr_src2', 'tmp/cpr_dest2'
+ assert_directory 'tmp/cpr_dest2'
+ #assert_not_symlink 'tmp/cpr_dest2'
+ # * 2005-05-26: feature change on trunk
+ #assert_symlink 'tmp/cpr_dest2'
+ # * 2005-09-19: revert for 1.8 (:dereference_root => true by default)
+ assert_not_symlink 'tmp/cpr_dest2'
+ assert_symlink 'tmp/cpr_dest2/symlink'
+ assert_equal 'SLdest', File.readlink('tmp/cpr_dest2/symlink')
+end
+
+ # pathname
+ touch 'tmp/cprtmp'
+ assert_nothing_raised {
+ cp_r Pathname.new('tmp/cprtmp'), 'tmp/tmpdest'
+ cp_r 'tmp/cprtmp', Pathname.new('tmp/tmpdest')
+ cp_r Pathname.new('tmp/cprtmp'), Pathname.new('tmp/tmpdest')
+ }
+ end
+
+ def test_mv
+ check_singleton :mv
+
+ mkdir 'tmp/dest'
+ TARGETS.each do |fname|
+ cp fname, 'tmp/mvsrc'
+ mv 'tmp/mvsrc', 'tmp/mvdest'
+ assert_same_file fname, 'tmp/mvdest'
+
+ mv 'tmp/mvdest', 'tmp/dest/'
+ assert_same_file fname, 'tmp/dest/mvdest'
+
+ mv 'tmp/dest/mvdest', 'tmp'
+ assert_same_file fname, 'tmp/mvdest'
+ end
+
+ # [ruby-talk:124368]
+ mkdir 'tmp/tmpdir'
+ mkdir_p 'tmp/dest2/tmpdir'
+ assert_raises(Errno::EEXIST) {
+ mv 'tmp/tmpdir', 'tmp/dest2'
+ }
+ mkdir 'tmp/dest2/tmpdir/junk'
+ assert_raises(Errno::EEXIST) {
+ mv 'tmp/tmpdir', 'tmp/dest2'
+ }
+
+ # src==dest (1) same path
+ touch 'tmp/cptmp'
+ assert_raises(ArgumentError) {
+ mv 'tmp/cptmp', 'tmp/cptmp'
+ }
+if have_symlink?
+ # src==dest (2) symlink and its target
+ File.symlink 'cptmp', 'tmp/cptmp_symlink'
+ assert_raises(ArgumentError) {
+ mv 'tmp/cptmp', 'tmp/cptmp_symlink'
+ }
+ assert_raises(ArgumentError) {
+ mv 'tmp/cptmp_symlink', 'tmp/cptmp'
+ }
+ # src==dest (3) looped symlink
+ File.symlink 'symlink', 'tmp/symlink'
+ assert_raises(Errno::ELOOP) {
+ mv 'tmp/symlink', 'tmp/symlink'
+ }
+end
+
+ # pathname
+ assert_nothing_raised {
+ touch 'tmp/mvtmpsrc'
+ mv Pathname.new('tmp/mvtmpsrc'), 'tmp/mvtmpdest'
+ touch 'tmp/mvtmpsrc'
+ mv 'tmp/mvtmpsrc', Pathname.new('tmp/mvtmpdest')
+ touch 'tmp/mvtmpsrc'
+ mv Pathname.new('tmp/mvtmpsrc'), Pathname.new('tmp/mvtmpdest')
+ }
+ end
+
+ def test_rm
+ check_singleton :rm
+
+ TARGETS.each do |fname|
+ cp fname, 'tmp/rmsrc'
+ rm 'tmp/rmsrc'
+ assert_file_not_exist 'tmp/rmsrc'
+ end
+
+ # pathname
+ touch 'tmp/rmtmp1'
+ touch 'tmp/rmtmp2'
+ touch 'tmp/rmtmp3'
+ assert_nothing_raised {
+ rm Pathname.new('tmp/rmtmp1')
+ rm [Pathname.new('tmp/rmtmp2'), Pathname.new('tmp/rmtmp3')]
+ }
+ assert_file_not_exist 'tmp/rmtmp1'
+ assert_file_not_exist 'tmp/rmtmp2'
+ assert_file_not_exist 'tmp/rmtmp3'
+ end
+
+ def test_rm_f
+ check_singleton :rm_f
+
+ TARGETS.each do |fname|
+ cp fname, 'tmp/rmsrc'
+ rm_f 'tmp/rmsrc'
+ assert_file_not_exist 'tmp/rmsrc'
+ end
+
+if have_symlink?
+ File.open('tmp/lnf_symlink_src', 'w') {|f| f.puts 'dummy' }
+ File.symlink 'tmp/lnf_symlink_src', 'tmp/lnf_symlink_dest'
+ rm_f 'tmp/lnf_symlink_dest'
+ assert_file_not_exist 'tmp/lnf_symlink_dest'
+ assert_file_exist 'tmp/lnf_symlink_src'
+end
+
+ rm_f 'notexistdatafile'
+ rm_f 'tmp/notexistdatafile'
+ my_rm_rf 'tmpdatadir'
+ Dir.mkdir 'tmpdatadir'
+ # rm_f 'tmpdatadir'
+ Dir.rmdir 'tmpdatadir'
+
+ Dir.mkdir 'tmp/tmpdir'
+ File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
+ rm_f ['tmp/tmpdir/a', 'tmp/tmpdir/b', 'tmp/tmpdir/c']
+ assert_file_not_exist 'tmp/tmpdir/a'
+ assert_file_not_exist 'tmp/tmpdir/c'
+ Dir.rmdir 'tmp/tmpdir'
+
+ # pathname
+ touch 'tmp/rmtmp1'
+ touch 'tmp/rmtmp2'
+ touch 'tmp/rmtmp3'
+ touch 'tmp/rmtmp4'
+ assert_nothing_raised {
+ rm_f Pathname.new('tmp/rmtmp1')
+ rm_f [Pathname.new('tmp/rmtmp2'), Pathname.new('tmp/rmtmp3')]
+ }
+ assert_file_not_exist 'tmp/rmtmp1'
+ assert_file_not_exist 'tmp/rmtmp2'
+ assert_file_not_exist 'tmp/rmtmp3'
+ assert_file_exist 'tmp/rmtmp4'
+ end
+
+ def test_rm_r
+ check_singleton :rm_r
+
+ my_rm_rf 'tmpdatadir'
+
+ Dir.mkdir 'tmpdatadir'
+ rm_r 'tmpdatadir'
+ assert_file_not_exist 'tmpdatadir'
+
+ Dir.mkdir 'tmpdatadir'
+ rm_r 'tmpdatadir/'
+ assert_file_not_exist 'tmpdatadir'
+
+ Dir.mkdir 'tmp/tmpdir'
+ rm_r 'tmp/tmpdir/'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+
+ Dir.mkdir 'tmp/tmpdir'
+ rm_r 'tmp/tmpdir'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+
+ Dir.mkdir 'tmp/tmpdir'
+ File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/b', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
+ rm_r 'tmp/tmpdir'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+
+ Dir.mkdir 'tmp/tmpdir'
+ File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
+ rm_r ['tmp/tmpdir/a', 'tmp/tmpdir/b', 'tmp/tmpdir/c'], :force => true
+ assert_file_not_exist 'tmp/tmpdir/a'
+ assert_file_not_exist 'tmp/tmpdir/c'
+ Dir.rmdir 'tmp/tmpdir'
+
+if have_symlink?
+ # [ruby-talk:94635] a symlink to the directory
+ Dir.mkdir 'tmp/tmpdir'
+ File.symlink '..', 'tmp/tmpdir/symlink_to_dir'
+ rm_r 'tmp/tmpdir'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+end
+
+ # pathname
+ Dir.mkdir 'tmp/tmpdir1'; touch 'tmp/tmpdir1/tmp'
+ Dir.mkdir 'tmp/tmpdir2'; touch 'tmp/tmpdir2/tmp'
+ Dir.mkdir 'tmp/tmpdir3'; touch 'tmp/tmpdir3/tmp'
+ assert_nothing_raised {
+ rm_r Pathname.new('tmp/tmpdir1')
+ rm_r [Pathname.new('tmp/tmpdir2'), Pathname.new('tmp/tmpdir3')]
+ }
+ assert_file_not_exist 'tmp/tmpdir1'
+ assert_file_not_exist 'tmp/tmpdir2'
+ assert_file_not_exist 'tmp/tmpdir3'
+ end
+
+ def test_remove_entry_secure
+ check_singleton :remove_entry_secure
+
+ my_rm_rf 'tmpdatadir'
+
+ Dir.mkdir 'tmpdatadir'
+ remove_entry_secure 'tmpdatadir'
+ assert_file_not_exist 'tmpdatadir'
+
+ Dir.mkdir 'tmpdatadir'
+ remove_entry_secure 'tmpdatadir/'
+ assert_file_not_exist 'tmpdatadir'
+
+ Dir.mkdir 'tmp/tmpdir'
+ remove_entry_secure 'tmp/tmpdir/'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+
+ Dir.mkdir 'tmp/tmpdir'
+ remove_entry_secure 'tmp/tmpdir'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+
+ Dir.mkdir 'tmp/tmpdir'
+ File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/b', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
+ remove_entry_secure 'tmp/tmpdir'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+
+ Dir.mkdir 'tmp/tmpdir'
+ File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
+ File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
+ remove_entry_secure 'tmp/tmpdir/a', true
+ remove_entry_secure 'tmp/tmpdir/b', true
+ remove_entry_secure 'tmp/tmpdir/c', true
+ assert_file_not_exist 'tmp/tmpdir/a'
+ assert_file_not_exist 'tmp/tmpdir/c'
+ Dir.rmdir 'tmp/tmpdir'
+
+if have_symlink?
+ # [ruby-talk:94635] a symlink to the directory
+ Dir.mkdir 'tmp/tmpdir'
+ File.symlink '..', 'tmp/tmpdir/symlink_to_dir'
+ remove_entry_secure 'tmp/tmpdir'
+ assert_file_not_exist 'tmp/tmpdir'
+ assert_file_exist 'tmp'
+end
+
+ # pathname
+ Dir.mkdir 'tmp/tmpdir1'; touch 'tmp/tmpdir1/tmp'
+ assert_nothing_raised {
+ remove_entry_secure Pathname.new('tmp/tmpdir1')
+ }
+ assert_file_not_exist 'tmp/tmpdir1'
+ end
+
+ def test_with_big_file
+ prepare_big_file
+
+ cp BIGFILE, 'tmp/cpdest'
+ assert_same_file BIGFILE, 'tmp/cpdest'
+ assert cmp(BIGFILE, 'tmp/cpdest'), 'orig != copied'
+
+ mv 'tmp/cpdest', 'tmp/mvdest'
+ assert_same_file BIGFILE, 'tmp/mvdest'
+ assert_file_not_exist 'tmp/cpdest'
+
+ rm 'tmp/mvdest'
+ assert_file_not_exist 'tmp/mvdest'
+ end
+
+if have_hardlink?
+ def test_ln
+ TARGETS.each do |fname|
+ ln fname, 'tmp/lndest'
+ assert_same_file fname, 'tmp/lndest'
+ File.unlink 'tmp/lndest'
+ end
+
+ ln TARGETS, 'tmp'
+ TARGETS.each do |fname|
+ assert_same_file fname, 'tmp/' + File.basename(fname)
+ end
+ TARGETS.each do |fname|
+ File.unlink 'tmp/' + File.basename(fname)
+ end
+
+ # src==dest (1) same path
+ touch 'tmp/cptmp'
+ assert_raises(Errno::EEXIST) {
+ ln 'tmp/cptmp', 'tmp/cptmp'
+ }
+if have_symlink?
+ # src==dest (2) symlink and its target
+ File.symlink 'cptmp', 'tmp/symlink'
+ assert_raises(Errno::EEXIST) {
+ ln 'tmp/cptmp', 'tmp/symlink' # normal file -> symlink
+ }
+ assert_raises(Errno::EEXIST) {
+ ln 'tmp/symlink', 'tmp/cptmp' # symlink -> normal file
+ }
+ # src==dest (3) looped symlink
+ File.symlink 'cptmp_symlink', 'tmp/cptmp_symlink'
+ begin
+ ln 'tmp/cptmp_symlink', 'tmp/cptmp_symlink'
+ rescue => err
+ assert_kind_of SystemCallError, err
+ end
+end
+
+ # pathname
+ touch 'tmp/lntmp'
+ assert_nothing_raised {
+ ln Pathname.new('tmp/lntmp'), 'tmp/lndesttmp1'
+ ln 'tmp/lntmp', Pathname.new('tmp/lndesttmp2')
+ ln Pathname.new('tmp/lntmp'), Pathname.new('tmp/lndesttmp3')
+ }
+ end
+end
+
+if have_symlink?
+ def test_ln_s
+ check_singleton :ln_s
+
+ TARGETS.each do |fname|
+ ln_s fname, 'tmp/lnsdest'
+ assert FileTest.symlink?('tmp/lnsdest'), 'not symlink'
+ assert_equal fname, File.readlink('tmp/lnsdest')
+ rm_f 'tmp/lnsdest'
+ end
+ assert_nothing_raised {
+ ln_s 'symlink', 'tmp/symlink'
+ }
+ assert_symlink 'tmp/symlink'
+
+ # pathname
+ touch 'tmp/lnsdest'
+ assert_nothing_raised {
+ ln_s Pathname.new('lnsdest'), 'tmp/symlink_tmp1'
+ ln_s 'lnsdest', Pathname.new('tmp/symlink_tmp2')
+ ln_s Pathname.new('lnsdest'), Pathname.new('tmp/symlink_tmp3')
+ }
+ end
+end
+
+if have_symlink?
+ def test_ln_sf
+ check_singleton :ln_sf
+
+ TARGETS.each do |fname|
+ ln_sf fname, 'tmp/lnsdest'
+ assert FileTest.symlink?('tmp/lnsdest'), 'not symlink'
+ assert_equal fname, File.readlink('tmp/lnsdest')
+ ln_sf fname, 'tmp/lnsdest'
+ ln_sf fname, 'tmp/lnsdest'
+ end
+ assert_nothing_raised {
+ ln_sf 'symlink', 'tmp/symlink'
+ }
+
+ # pathname
+ touch 'tmp/lns_dest'
+ assert_nothing_raised {
+ ln_sf Pathname.new('lns_dest'), 'tmp/symlink_tmp1'
+ ln_sf 'lns_dest', Pathname.new('tmp/symlink_tmp2')
+ ln_sf Pathname.new('lns_dest'), Pathname.new('tmp/symlink_tmp3')
+ }
+ end
+end
+
+ def test_mkdir
+ check_singleton :mkdir
+
+ my_rm_rf 'tmpdatadir'
+ mkdir 'tmpdatadir'
+ assert_directory 'tmpdatadir'
+ Dir.rmdir 'tmpdatadir'
+
+ mkdir 'tmpdatadir/'
+ assert_directory 'tmpdatadir'
+ Dir.rmdir 'tmpdatadir'
+
+ mkdir 'tmp/mkdirdest'
+ assert_directory 'tmp/mkdirdest'
+ Dir.rmdir 'tmp/mkdirdest'
+
+ mkdir 'tmp/tmp', :mode => 0700
+ assert_directory 'tmp/tmp'
+ assert_equal 0700, (File.stat('tmp/tmp').mode & 0777) if have_file_perm?
+ Dir.rmdir 'tmp/tmp'
+
+if have_file_perm?
+ mkdir 'tmp/tmp', :mode => 07777
+ assert_directory 'tmp/tmp'
+ assert_equal 07777, (File.stat('tmp/tmp').mode & 07777)
+ Dir.rmdir 'tmp/tmp'
+end
+
+if lf_in_path_allowed?
+ mkdir "tmp-first-line\ntmp-second-line"
+ assert_directory "tmp-first-line\ntmp-second-line"
+ Dir.rmdir "tmp-first-line\ntmp-second-line"
+end
+
+ # pathname
+ assert_nothing_raised {
+ mkdir Pathname.new('tmp/tmpdirtmp')
+ mkdir [Pathname.new('tmp/tmpdirtmp2'), Pathname.new('tmp/tmpdirtmp3')]
+ }
+ end
+
+ def test_mkdir_p
+ check_singleton :mkdir_p
+
+ dirs = %w(
+ tmpdir/dir/
+ tmpdir/dir/./
+ tmpdir/dir/./.././dir/
+ tmpdir/a
+ tmpdir/a/
+ tmpdir/a/b
+ tmpdir/a/b/
+ tmpdir/a/b/c/
+ tmpdir/a/b/c
+ tmpdir/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a
+ tmpdir/a/a
+ )
+ my_rm_rf 'tmpdir'
+ dirs.each do |d|
+ mkdir_p d
+ assert_directory d
+ assert_file_not_exist "#{d}/a"
+ assert_file_not_exist "#{d}/b"
+ assert_file_not_exist "#{d}/c"
+ my_rm_rf 'tmpdir'
+ end
+ dirs.each do |d|
+ mkdir_p d
+ assert_directory d
+ end
+ rm_rf 'tmpdir'
+ dirs.each do |d|
+ mkdir_p "#{Dir.pwd}/#{d}"
+ assert_directory d
+ end
+ rm_rf 'tmpdir'
+
+ mkdir_p 'tmp/tmp/tmp', :mode => 0700
+ assert_directory 'tmp/tmp'
+ assert_directory 'tmp/tmp/tmp'
+ assert_equal 0700, (File.stat('tmp/tmp').mode & 0777) if have_file_perm?
+ assert_equal 0700, (File.stat('tmp/tmp/tmp').mode & 0777) if have_file_perm?
+ rm_rf 'tmp/tmp'
+
+ mkdir_p 'tmp/tmp', :mode => 0
+ assert_directory 'tmp/tmp'
+ assert_equal 0, (File.stat('tmp/tmp').mode & 0777) if have_file_perm?
+ # DO NOT USE rm_rf here.
+ # (rm(1) try to chdir to parent directory, it fails to remove directory.)
+ Dir.rmdir 'tmp/tmp'
+ Dir.rmdir 'tmp'
+
+if have_file_perm?
+ mkdir_p 'tmp/tmp/tmp', :mode => 07777
+ assert_directory 'tmp/tmp/tmp'
+ assert_equal 07777, (File.stat('tmp/tmp/tmp').mode & 07777)
+ Dir.rmdir 'tmp/tmp/tmp'
+ Dir.rmdir 'tmp/tmp'
+end
+
+ # pathname
+ assert_nothing_raised {
+ mkdir_p Pathname.new('tmp/tmp/tmp')
+ }
+ end
+
+ def test_install
+ check_singleton :install
+
+ File.open('tmp/aaa', 'w') {|f| f.puts 'aaa' }
+ File.open('tmp/bbb', 'w') {|f| f.puts 'bbb' }
+ install 'tmp/aaa', 'tmp/bbb', :mode => 0600
+ assert_equal "aaa\n", File.read('tmp/bbb')
+ assert_equal 0600, (File.stat('tmp/bbb').mode & 0777) if have_file_perm?
+
+ t = File.mtime('tmp/bbb')
+ install 'tmp/aaa', 'tmp/bbb'
+ assert_equal "aaa\n", File.read('tmp/bbb')
+ assert_equal 0600, (File.stat('tmp/bbb').mode & 0777) if have_file_perm?
+ assert_equal t, File.mtime('tmp/bbb')
+
+ File.unlink 'tmp/aaa'
+ File.unlink 'tmp/bbb'
+
+ # src==dest (1) same path
+ touch 'tmp/cptmp'
+ assert_raises(ArgumentError) {
+ install 'tmp/cptmp', 'tmp/cptmp'
+ }
+if have_symlink?
+ # src==dest (2) symlink and its target
+ File.symlink 'cptmp', 'tmp/cptmp_symlink'
+ assert_raises(ArgumentError) {
+ install 'tmp/cptmp', 'tmp/cptmp_symlink'
+ }
+ assert_raises(ArgumentError) {
+ install 'tmp/cptmp_symlink', 'tmp/cptmp'
+ }
+ # src==dest (3) looped symlink
+ File.symlink 'symlink', 'tmp/symlink'
+ assert_raises(Errno::ELOOP) {
+ # File#install invokes open(2), always ELOOP must be raised
+ install 'tmp/symlink', 'tmp/symlink'
+ }
+end
+
+ # pathname
+ assert_nothing_raised {
+ rm_f 'tmp/a'; touch 'tmp/a'
+ install 'tmp/a', Pathname.new('tmp/b')
+ rm_f 'tmp/a'; touch 'tmp/a'
+ install Pathname.new('tmp/a'), 'tmp/b'
+ rm_f 'tmp/a'; touch 'tmp/a'
+ install Pathname.new('tmp/a'), Pathname.new('tmp/b')
+ rm_f 'tmp/a'
+ touch 'tmp/a'
+ touch 'tmp/b'
+ mkdir 'tmp/dest'
+ install [Pathname.new('tmp/a'), Pathname.new('tmp/b')], 'tmp/dest'
+ my_rm_rf 'tmp/dest'
+ mkdir 'tmp/dest'
+ install [Pathname.new('tmp/a'), Pathname.new('tmp/b')], Pathname.new('tmp/dest')
+ }
+ end
+
+if have_file_perm?
+ def test_chmod
+ check_singleton :chmod
+
+ touch 'tmp/a'
+ chmod 0700, 'tmp/a'
+ assert_equal 0700, File.stat('tmp/a').mode & 0777
+ chmod 0500, 'tmp/a'
+ assert_equal 0500, File.stat('tmp/a').mode & 0777
+ end
+
+ def test_chmod_R
+ check_singleton :chmod_R
+
+ mkdir_p 'tmp/dir/dir'
+ touch %w( tmp/dir/file tmp/dir/dir/file )
+ chmod_R 0700, 'tmp/dir'
+ assert_equal 0700, File.stat('tmp/dir').mode & 0777
+ assert_equal 0700, File.stat('tmp/dir/file').mode & 0777
+ assert_equal 0700, File.stat('tmp/dir/dir').mode & 0777
+ assert_equal 0700, File.stat('tmp/dir/dir/file').mode & 0777
+ chmod_R 0500, 'tmp/dir'
+ assert_equal 0500, File.stat('tmp/dir').mode & 0777
+ assert_equal 0500, File.stat('tmp/dir/file').mode & 0777
+ assert_equal 0500, File.stat('tmp/dir/dir').mode & 0777
+ assert_equal 0500, File.stat('tmp/dir/dir/file').mode & 0777
+ chmod_R 0700, 'tmp/dir' # to remove
+ end
+
+ # FIXME: How can I test this method?
+ def test_chown
+ check_singleton :chown
+ end
+
+ # FIXME: How can I test this method?
+ def test_chown_R
+ check_singleton :chown_R
+ end
+end
+
+ def test_copy_entry
+ check_singleton :copy_entry
+
+ each_srcdest do |srcpath, destpath|
+ copy_entry srcpath, destpath
+ assert_same_file srcpath, destpath
+ assert_equal File.stat(srcpath).ftype, File.stat(destpath).ftype
+ end
+if have_symlink?
+ # root is a symlink
+ File.symlink 'somewhere', 'tmp/symsrc'
+ copy_entry 'tmp/symsrc', 'tmp/symdest'
+ assert_symlink 'tmp/symdest'
+ assert_equal 'somewhere', File.readlink('tmp/symdest')
+
+ # content is a symlink
+ mkdir 'tmp/dir'
+ File.symlink 'somewhere', 'tmp/dir/sym'
+ copy_entry 'tmp/dir', 'tmp/dirdest'
+ assert_directory 'tmp/dirdest'
+ assert_not_symlink 'tmp/dirdest'
+ assert_symlink 'tmp/dirdest/sym'
+ assert_equal 'somewhere', File.readlink('tmp/dirdest/sym')
+end
+ end
+
+ def test_copy_file
+ check_singleton :copy_file
+
+ each_srcdest do |srcpath, destpath|
+ copy_file srcpath, destpath
+ assert_same_file srcpath, destpath
+ end
+ end
+
+ def test_copy_stream
+ check_singleton :copy_stream
+ # IO
+ each_srcdest do |srcpath, destpath|
+ File.open(srcpath) {|src|
+ File.open(destpath, 'w') {|dest|
+ copy_stream src, dest
+ }
+ }
+ assert_same_file srcpath, destpath
+ end
+
+ # duck typing test [ruby-dev:25369]
+ my_rm_rf 'tmp'
+ Dir.mkdir 'tmp'
+ each_srcdest do |srcpath, destpath|
+ File.open(srcpath) {|src|
+ File.open(destpath, 'w') {|dest|
+ copy_stream Stream.new(src), Stream.new(dest)
+ }
+ }
+ assert_same_file srcpath, destpath
+ end
+ end
+
+ def test_remove_file
+ check_singleton :remove_file
+ File.open('data/tmp', 'w') {|f| f.puts 'dummy' }
+ remove_file 'data/tmp'
+ assert_file_not_exist 'data/tmp'
+if have_file_perm?
+ File.open('data/tmp', 'w') {|f| f.puts 'dummy' }
+ File.chmod 0, 'data/tmp'
+ remove_file 'data/tmp'
+ assert_file_not_exist 'data/tmp'
+end
+ end
+
+ def test_remove_dir
+ check_singleton :remove_dir
+ Dir.mkdir 'data/tmpdir'
+ File.open('data/tmpdir/a', 'w') {|f| f.puts 'dummy' }
+ remove_dir 'data/tmpdir'
+ assert_file_not_exist 'data/tmpdir'
+if have_file_perm?
+ Dir.mkdir 'data/tmpdir'
+ File.chmod 0555, 'data/tmpdir'
+ remove_dir 'data/tmpdir'
+ assert_file_not_exist 'data/tmpdir'
+end
+ end
+
+ def test_compare_file
+ check_singleton :compare_file
+ # FIXME
+ end
+
+ def test_compare_stream
+ check_singleton :compare_stream
+ # FIXME
+ end
+
+ class Stream
+ def initialize(f)
+ @f = f
+ end
+
+ def read(n)
+ @f.read(n)
+ end
+
+ def write(str)
+ @f.write str
+ end
+ end
+
+ def test_uptodate?
+ check_singleton :uptodate?
+ prepare_time_data
+ Dir.chdir('data') {
+ assert( uptodate?('newest', %w(old newer notexist)) )
+ assert( ! uptodate?('newer', %w(old newest notexist)) )
+ assert( ! uptodate?('notexist', %w(old newest newer)) )
+ }
+
+ # pathname
+ touch 'tmp/a'
+ touch 'tmp/b'
+ touch 'tmp/c'
+ assert_nothing_raised {
+ uptodate? Pathname.new('tmp/a'), ['tmp/b', 'tmp/c']
+ uptodate? 'tmp/a', [Pathname.new('tmp/b'), 'tmp/c']
+ uptodate? 'tmp/a', ['tmp/b', Pathname.new('tmp/c')]
+ uptodate? Pathname.new('tmp/a'), [Pathname.new('tmp/b'), Pathname.new('tmp/c')]
+ }
+ end
+
+ def test_cd
+ check_singleton :cd
+ end
+
+ def test_chdir
+ check_singleton :chdir
+ end
+
+ def test_getwd
+ check_singleton :getwd
+ end
+
+ def test_identical?
+ check_singleton :identical?
+ end
+
+ def test_link
+ check_singleton :link
+ end
+
+ def test_makedirs
+ check_singleton :makedirs
+ end
+
+ def test_mkpath
+ check_singleton :mkpath
+ end
+
+ def test_move
+ check_singleton :move
+ end
+
+ def test_rm_rf
+ check_singleton :rm_rf
+ end
+
+ def test_rmdir
+ check_singleton :rmdir
+ end
+
+ def test_rmtree
+ check_singleton :rmtree
+ end
+
+ def test_safe_unlink
+ check_singleton :safe_unlink
+ end
+
+ def test_symlink
+ check_singleton :symlink
+ end
+
+ def test_touch
+ check_singleton :touch
+ end
+
+ def test_collect_methods
+ end
+
+ def test_commands
+ end
+
+ def test_have_option?
+ end
+
+ def test_options
+ end
+
+ def test_options_of
+ end
+
+end
diff --git a/ruby_1_8_6/test/fileutils/test_nowrite.rb b/ruby_1_8_6/test/fileutils/test_nowrite.rb
new file mode 100644
index 0000000000..369f8ca608
--- /dev/null
+++ b/ruby_1_8_6/test/fileutils/test_nowrite.rb
@@ -0,0 +1,99 @@
+# $Id$
+
+require 'fileutils'
+require 'fileasserts'
+require 'tmpdir'
+require 'test/unit'
+
+class TestFileUtilsNoWrite < Test::Unit::TestCase
+
+ include FileUtils::NoWrite
+
+ def test_visibility
+ FileUtils::METHODS.each do |m|
+ assert_equal true, FileUtils::NoWrite.respond_to?(m, true),
+ "FileUtils::NoWrite.#{m} is not defined"
+ assert_equal true, FileUtils::NoWrite.respond_to?(m, false),
+ "FileUtils::NoWrite.#{m} is not public"
+ end
+ FileUtils::METHODS.each do |m|
+ assert_equal true, respond_to?(m, true),
+ "FileUtils::NoWrite\##{m} is not defined"
+ assert_equal true, FileUtils::NoWrite.private_method_defined?(m),
+ "FileUtils::NoWrite\##{m} is not private"
+ end
+ end
+
+ def my_rm_rf(path)
+ if File.exist?('/bin/rm')
+ system %Q[/bin/rm -rf "#{path}"]
+ else
+ FileUtils.rm_rf path
+ end
+ end
+
+ SRC = 'data/src'
+ COPY = 'data/copy'
+
+ def setup
+ @prevdir = Dir.pwd
+ tmproot = "#{Dir.tmpdir}/fileutils.rb.#{$$}"
+ Dir.mkdir tmproot unless File.directory?(tmproot)
+ Dir.chdir tmproot
+ my_rm_rf 'data'; Dir.mkdir 'data'
+ my_rm_rf 'tmp'; Dir.mkdir 'tmp'
+ File.open(SRC, 'w') {|f| f.puts 'dummy' }
+ File.open(COPY, 'w') {|f| f.puts 'dummy' }
+ end
+
+ def teardown
+ tmproot = Dir.pwd
+ Dir.chdir @prevdir
+ my_rm_rf tmproot
+ end
+
+ def test_cp
+ cp SRC, 'tmp/cp'
+ check 'tmp/cp'
+ end
+
+ def test_mv
+ mv SRC, 'tmp/mv'
+ check 'tmp/mv'
+ end
+
+ def check(dest)
+ assert_file_not_exist dest
+ assert_file_exist SRC
+ assert_same_file SRC, COPY
+ end
+
+ def test_rm
+ rm SRC
+ assert_file_exist SRC
+ assert_same_file SRC, COPY
+ end
+
+ def test_rm_f
+ rm_f SRC
+ assert_file_exist SRC
+ assert_same_file SRC, COPY
+ end
+
+ def test_rm_rf
+ rm_rf SRC
+ assert_file_exist SRC
+ assert_same_file SRC, COPY
+ end
+
+ def test_mkdir
+ mkdir 'dir'
+ assert_file_not_exist 'dir'
+ end
+
+ def test_mkdir_p
+ mkdir 'dir/dir/dir'
+ assert_file_not_exist 'dir'
+ end
+
+end
diff --git a/ruby_1_8_6/test/fileutils/test_verbose.rb b/ruby_1_8_6/test/fileutils/test_verbose.rb
new file mode 100644
index 0000000000..e60e85ea4e
--- /dev/null
+++ b/ruby_1_8_6/test/fileutils/test_verbose.rb
@@ -0,0 +1,25 @@
+# $Id$
+
+require 'test/unit'
+require 'fileutils'
+
+class TestFileUtilsVerbose < Test::Unit::TestCase
+
+ include FileUtils::Verbose
+
+ def test_visibility
+ FileUtils::METHODS.each do |m|
+ assert_equal true, FileUtils::Verbose.respond_to?(m, true),
+ "FileUtils::Verbose.#{m} is not defined"
+ assert_equal true, FileUtils::Verbose.respond_to?(m, false),
+ "FileUtils::Verbose.#{m} is not public"
+ end
+ FileUtils::METHODS.each do |m|
+ assert_equal true, respond_to?(m, true),
+ "FileUtils::Verbose.#{m} is not defined"
+ assert_equal true, FileUtils::Verbose.private_method_defined?(m),
+ "FileUtils::Verbose.#{m} is not private"
+ end
+ end
+
+end
diff --git a/ruby_1_8_6/test/gdbm/test_gdbm.rb b/ruby_1_8_6/test/gdbm/test_gdbm.rb
new file mode 100644
index 0000000000..b84221e547
--- /dev/null
+++ b/ruby_1_8_6/test/gdbm/test_gdbm.rb
@@ -0,0 +1,692 @@
+require 'test/unit'
+
+begin
+ require 'gdbm'
+rescue LoadError
+end
+
+if defined? GDBM
+ require 'tmpdir'
+ require 'fileutils'
+
+ class TestGDBM < Test::Unit::TestCase
+ def TestGDBM.uname_s
+ require 'rbconfig'
+ case Config::CONFIG['target_os']
+ when 'cygwin'
+ require 'Win32API'
+ uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
+ utsname = ' ' * 100
+ raise 'cannot get system name' if uname.call(utsname) == -1
+
+ utsname.unpack('A20' * 5)[0]
+ else
+ Config::CONFIG['target_os']
+ end
+ end
+ SYSTEM = uname_s
+
+ def setup
+ @path = "tmptest_gdbm_"
+ assert_instance_of(GDBM, @gdbm = GDBM.new(@path))
+
+ # prepare to make readonly GDBM file
+ GDBM.open("tmptest_gdbm_rdonly", 0400) {|gdbm|
+ gdbm['foo'] = 'FOO'
+ }
+ assert_instance_of(GDBM, @gdbm_rdonly = GDBM.new("tmptest_gdbm_rdonly", nil))
+ end
+ def teardown
+ assert_nil(@gdbm.close)
+ assert_nil(@gdbm_rdonly.close)
+ ObjectSpace.each_object(GDBM) do |obj|
+ obj.close unless obj.closed?
+ end
+ File.delete *Dir.glob("*tmptest_gdbm*").to_a
+ p Dir.glob("*tmptest_gdbm*") if $DEBUG
+ end
+
+ def check_size(expect, gdbm=@gdbm)
+ assert_equal(expect, gdbm.size)
+ n = 0
+ gdbm.each { n+=1 }
+ assert_equal(expect, n)
+ if expect == 0
+ assert_equal(true, gdbm.empty?)
+ else
+ assert_equal(false, gdbm.empty?)
+ end
+ end
+
+ def have_fork?
+ begin
+ fork{}
+ true
+ rescue NotImplementedError
+ false
+ end
+ end
+
+ def test_s_new_has_no_block
+ # GDBM.new ignore the block
+ foo = true
+ assert_instance_of(GDBM, gdbm = GDBM.new("tmptest_gdbm") { foo = false })
+ assert_equal(foo, true)
+ assert_nil(gdbm.close)
+ end
+ def test_s_open_create_new
+ return if /^CYGWIN_9/ =~ SYSTEM
+
+ save_mask = File.umask(0)
+ begin
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
+ gdbm.close
+ assert_equal(File.stat("tmptest_gdbm").mode & 0777, 0666)
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm2", 0644))
+ gdbm.close
+ assert_equal(File.stat("tmptest_gdbm2").mode & 0777, 0644)
+ ensure
+ File.umask save_mask
+ end
+ end
+ def test_s_open_no_create
+ # this test is failed on libgdbm 1.8.0
+ assert_nil(gdbm = GDBM.open("tmptest_gdbm", nil))
+ ensure
+ gdbm.close if gdbm
+ end
+ def test_s_open_3rd_arg
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::FAST))
+ gdbm.close
+
+ # gdbm 1.8.0 specific
+ if defined? GDBM::SYNC
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::SYNC))
+ gdbm.close
+ end
+ # gdbm 1.8.0 specific
+ if defined? GDBM::NOLOCK
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::NOLOCK))
+ gdbm.close
+ end
+ end
+ def test_s_open_with_block
+ assert_equal(GDBM.open("tmptest_gdbm") { :foo }, :foo)
+ end
+ def test_s_open_lock
+ return unless have_fork? # snip this test
+ pid = fork() {
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ assert_raise(Errno::EWOULDBLOCK) {
+ begin
+ assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
+ rescue Errno::EAGAIN, Errno::EACCES
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ ensure
+ Process.wait pid
+ end
+ end
+
+=begin
+ # Is it guaranteed on many OS?
+ def test_s_open_lock_one_process
+ # locking on one process
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
+ assert_raise(Errno::EWOULDBLOCK) {
+ begin
+ GDBM.open("tmptest_gdbm", 0644)
+ rescue Errno::EAGAIN
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ end
+=end
+
+ def test_s_open_nolock
+ # gdbm 1.8.0 specific
+ if not defined? GDBM::NOLOCK
+ return
+ end
+ return unless have_fork? # snip this test
+
+ pid = fork() {
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::NOLOCK))
+ sleep 2
+ }
+ sleep 1
+ begin
+ gdbm2 = nil
+ assert_nothing_raised(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
+ }
+ ensure
+ Process.wait pid
+ gdbm2.close if gdbm2
+ end
+
+ p Dir.glob("tmptest_gdbm*") if $DEBUG
+
+ pid = Process.fork() {
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ gdbm2 = nil
+ assert_nothing_raised(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ # this test is failed on Cygwin98 (???)
+ assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::NOLOCK))
+ }
+ ensure
+ Process.wait pid
+ gdbm2.close if gdbm2
+ end
+ end
+
+ def test_s_open_error
+ return if /(ms|bcc)win|mingw|djgpp/ =~ RUBY_PLATFORM
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0))
+ assert_raise(Errno::EACCES) {
+ GDBM.open("tmptest_gdbm", 0)
+ }
+ gdbm.close
+ end
+
+ def test_close
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
+ assert_nil(gdbm.close)
+
+ # closed GDBM file
+ assert_raise(RuntimeError) { gdbm.close }
+ end
+
+ def test_aref
+ assert_equal('bar', @gdbm['foo'] = 'bar')
+ assert_equal('bar', @gdbm['foo'])
+
+ assert_nil(@gdbm['bar'])
+ end
+
+ def test_fetch
+ assert_equal('bar', @gdbm['foo']='bar')
+ assert_equal('bar', @gdbm.fetch('foo'))
+
+ # key not found
+ assert_raise(IndexError) {
+ @gdbm.fetch('bar')
+ }
+
+ # test for `ifnone' arg
+ assert_equal('baz', @gdbm.fetch('bar', 'baz'))
+
+ # test for `ifnone' block
+ assert_equal('foobar', @gdbm.fetch('bar') {|key| 'foo' + key })
+ end
+
+ def test_aset
+ num = 0
+ 2.times {|i|
+ assert_equal('foo', @gdbm['foo'] = 'foo')
+ assert_equal('foo', @gdbm['foo'])
+ assert_equal('bar', @gdbm['foo'] = 'bar')
+ assert_equal('bar', @gdbm['foo'])
+
+ num += 1 if i == 0
+ assert_equal(num, @gdbm.size)
+
+ # assign nil
+ assert_equal('', @gdbm['bar'] = '')
+ assert_equal('', @gdbm['bar'])
+
+ num += 1 if i == 0
+ assert_equal(num, @gdbm.size)
+
+ # empty string
+ assert_equal('', @gdbm[''] = '')
+ assert_equal('', @gdbm[''])
+
+ num += 1 if i == 0
+ assert_equal(num, @gdbm.size)
+
+ # Fixnum
+ assert_equal('200', @gdbm['100'] = '200')
+ assert_equal('200', @gdbm['100'])
+
+ num += 1 if i == 0
+ assert_equal(num, @gdbm.size)
+
+ # Big key and value
+ assert_equal('y' * 100, @gdbm['x' * 100] = 'y' * 100)
+ assert_equal('y' * 100, @gdbm['x' * 100])
+
+ num += 1 if i == 0
+ assert_equal(num, @gdbm.size)
+ }
+ end
+
+ def test_index
+ assert_equal('bar', @gdbm['foo'] = 'bar')
+ assert_equal('foo', @gdbm.index('bar'))
+ assert_nil(@gdbm['bar'])
+ end
+
+ def test_values_at
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+ assert_equal(values.reverse, @gdbm.values_at(*keys.reverse))
+ end
+
+ def test_select_with_block
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+ ret = @gdbm.select {|k,v|
+ assert_equal(k.upcase, v)
+ k != "bar"
+ }
+ assert_equal([['baz', 'BAZ'], ['foo', 'FOO']],
+ ret.sort)
+ end
+
+ def test_length
+ num = 10
+ assert_equal(0, @gdbm.size)
+ num.times {|i|
+ i = i.to_s
+ @gdbm[i] = i
+ }
+ assert_equal(num, @gdbm.size)
+
+ @gdbm.shift
+
+ assert_equal(num - 1, @gdbm.size)
+ end
+
+ def test_empty?
+ assert_equal(true, @gdbm.empty?)
+ @gdbm['foo'] = 'FOO'
+ assert_equal(false, @gdbm.empty?)
+ end
+
+ def test_each_pair
+ n = 0
+ @gdbm.each_pair { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ n = 0
+ ret = @gdbm.each_pair {|key, val|
+ assert_not_nil(i = keys.index(key))
+ assert_equal(val, values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@gdbm, ret)
+ end
+
+ def test_each_value
+ n = 0
+ @gdbm.each_value { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ n = 0
+ ret = @gdbm.each_value {|val|
+ assert_not_nil(key = @gdbm.index(val))
+ assert_not_nil(i = keys.index(key))
+ assert_equal(val, values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@gdbm, ret)
+ end
+
+ def test_each_key
+ n = 0
+ @gdbm.each_key { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ n = 0
+ ret = @gdbm.each_key {|key|
+ assert_not_nil(i = keys.index(key))
+ assert_equal(@gdbm[key], values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@gdbm, ret)
+ end
+
+ def test_keys
+ assert_equal([], @gdbm.keys)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ assert_equal(keys.sort, @gdbm.keys.sort)
+ assert_equal(values.sort, @gdbm.values.sort)
+ end
+
+ def test_values
+ test_keys
+ end
+
+ def test_shift
+ assert_nil(@gdbm.shift)
+ assert_equal(0, @gdbm.size)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ ret_keys = []
+ ret_values = []
+ while ret = @gdbm.shift
+ ret_keys.push ret[0]
+ ret_values.push ret[1]
+
+ assert_equal(keys.size - ret_keys.size, @gdbm.size)
+ end
+
+ assert_equal(keys.sort, ret_keys.sort)
+ assert_equal(values.sort, ret_values.sort)
+ end
+
+ def test_delete
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ key = keys[1]
+
+ assert_nil(@gdbm.delete(key))
+ assert_equal(0, @gdbm.size)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ assert_equal('BAR', @gdbm.delete(key))
+ assert_nil(@gdbm[key])
+ assert_equal(2, @gdbm.size)
+
+ assert_nil(@gdbm.delete(key))
+
+ if /^CYGWIN_9/ !~ SYSTEM
+ assert_raise(GDBMError) {
+ @gdbm_rdonly.delete("foo")
+ }
+
+ assert_nil(@gdbm_rdonly.delete("bar"))
+ end
+ end
+ def test_delete_with_block
+ key = 'no called block'
+ @gdbm[key] = 'foo'
+ assert_equal('foo', @gdbm.delete(key) {|k| k.replace 'called block'})
+ assert_equal('no called block', key)
+ assert_equal(0, @gdbm.size)
+
+ key = 'no called block'
+ assert_equal(:blockval,
+ @gdbm.delete(key) {|k| k.replace 'called block'; :blockval})
+ assert_equal('called block', key)
+ assert_equal(0, @gdbm.size)
+ end
+
+ def test_delete_if
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+
+ ret = @gdbm.delete_if {|key, val| key.to_i < 50}
+ assert_equal(@gdbm, ret)
+ check_size(50, @gdbm)
+
+ ret = @gdbm.delete_if {|key, val| key.to_i >= 50}
+ assert_equal(@gdbm, ret)
+ check_size(0, @gdbm)
+
+ # break
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+ check_size(100, @gdbm)
+ n = 0;
+ @gdbm.delete_if {|key, val|
+ break if n > 50
+ n+=1
+ true
+ }
+ assert_equal(51, n)
+ check_size(49, @gdbm)
+
+ @gdbm.clear
+
+ # raise
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+ check_size(100, @gdbm)
+ n = 0;
+ begin
+ @gdbm.delete_if {|key, val|
+ raise "runtime error" if n > 50
+ n+=1
+ true
+ }
+ rescue
+ end
+ assert_equal(51, n)
+ check_size(49, @gdbm)
+ end
+
+ def test_reject
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+
+ hash = @gdbm.reject {|key, val| key.to_i < 50}
+ assert_instance_of(Hash, hash)
+ assert_equal(100, @gdbm.size)
+
+ assert_equal(50, hash.size)
+ hash.each_pair {|key,val|
+ assert_equal(false, key.to_i < 50)
+ assert_equal(key, val)
+ }
+
+ hash = @gdbm.reject {|key, val| key.to_i < 100}
+ assert_instance_of(Hash, hash)
+ assert_equal(true, hash.empty?)
+ end
+
+ def test_clear
+ v = "1"
+ 100.times {v = v.next; @gdbm[v] = v}
+
+ assert_equal(@gdbm, @gdbm.clear)
+
+ # validate GDBM#size
+ i = 0
+ @gdbm.each { i += 1 }
+ assert_equal(@gdbm.size, i)
+ assert_equal(0, i)
+ end
+
+ def test_invert
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+
+ hash = @gdbm.invert
+ assert_instance_of(Hash, hash)
+ assert_equal(100, hash.size)
+ hash.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_update
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @gdbm["101"] = "101"
+ @gdbm.update hash
+ assert_equal(101, @gdbm.size)
+ @gdbm.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_replace
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @gdbm["101"] = "101"
+ @gdbm.replace hash
+ assert_equal(100, @gdbm.size)
+ @gdbm.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_reorganize
+ size1 = File.size(@path)
+ i = "1"
+ 1000.times {i = i.next; @gdbm[i] = i}
+ @gdbm.clear
+ @gdbm.sync
+
+ size2 = File.size(@path)
+ @gdbm.reorganize
+ size3 = File.size(@path)
+
+ # p [size1, size2, size3]
+ assert_equal(true, size1 < size2)
+ # this test is failed on Cygwin98. `GDBM version 1.8.0, as of May 19, 1999'
+ assert_equal(true, size3 < size2)
+ assert_equal(size1, size3)
+ end
+
+ def test_sync
+ assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666, GDBM::FAST))
+ assert_equal(gdbm.sync, gdbm)
+ gdbm.close
+ assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666))
+ assert_equal(gdbm.sync, gdbm)
+ gdbm.close
+ end
+
+ def test_cachesize=
+ assert_equal(@gdbm.cachesize = 1024, 1024)
+ end
+
+ def test_fastmode=
+ assert_equal(@gdbm.fastmode = true, true)
+ end
+
+ def test_syncmode=
+ assert_equal(@gdbm.syncmode = true, true)
+ end
+
+ def test_haskey?
+ assert_equal('bar', @gdbm['foo']='bar')
+ assert_equal(true, @gdbm.has_key?('foo'))
+ assert_equal(false, @gdbm.has_key?('bar'))
+ end
+
+ def test_has_value?
+ assert_equal('bar', @gdbm['foo']='bar')
+ assert_equal(true, @gdbm.has_value?('bar'))
+ assert_equal(false, @gdbm.has_value?('foo'))
+ end
+
+ def test_to_a
+ v = "0"
+ 100.times {v = v.next; @gdbm[v] = v}
+
+ ary = @gdbm.to_a
+ assert_instance_of(Array, ary)
+ assert_equal(100, ary.size)
+ ary.each {|key,val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_to_hash
+ v = "0"
+ 100.times {v = v.next; @gdbm[v] = v}
+
+ hash = @gdbm.to_hash
+ assert_instance_of(Hash, hash)
+ assert_equal(100, hash.size)
+ hash.each {|key,val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+ end
+
+ class TestGDBM2 < Test::Unit::TestCase
+ TMPROOT = "#{Dir.tmpdir}/ruby-gdbm.#{$$}"
+
+ def setup
+ Dir.mkdir TMPROOT
+ end
+
+ def teardown
+ FileUtils.rm_rf TMPROOT if File.directory?(TMPROOT)
+ end
+
+ def test_reader_open
+ GDBM.open("#{TMPROOT}/a.dbm") {}
+ v = GDBM.open("#{TMPROOT}/a.dbm", nil, GDBM::READER) {|d|
+ assert_raises(GDBMError) { d["k"] = "v" }
+ true
+ }
+ assert(v)
+ end
+
+ def test_newdb_open
+ GDBM.open("#{TMPROOT}/a.dbm") {|dbm|
+ dbm["k"] = "v"
+ }
+ v = GDBM.open("#{TMPROOT}/a.dbm", nil, GDBM::NEWDB) {|d|
+ assert_equal(0, d.length)
+ assert_nil(d["k"])
+ true
+ }
+ assert(v)
+ end
+
+ def test_freeze
+ GDBM.open("#{TMPROOT}/a.dbm") {|d|
+ d.freeze
+ assert_raises(TypeError) { d["k"] = "v" }
+ }
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/io/nonblock/test_flush.rb b/ruby_1_8_6/test/io/nonblock/test_flush.rb
new file mode 100644
index 0000000000..2afbba300e
--- /dev/null
+++ b/ruby_1_8_6/test/io/nonblock/test_flush.rb
@@ -0,0 +1,28 @@
+require 'test/unit'
+begin
+ require 'io/nonblock'
+rescue LoadError
+end
+
+class TestIONonblock < Test::Unit::TestCase
+ def test_flush # [ruby-dev:24985]
+ r,w = IO.pipe
+ w.nonblock = true
+ w.sync = false
+ w << "b"
+ w.flush
+ w << "a" * 4096
+ Thread.new {
+ Thread.pass
+ w.close
+ }
+ result = ""
+ t = Thread.new {
+ while (Thread.pass; s = r.read(4096))
+ result << s
+ end
+ }
+ assert_raise(IOError) {w.flush}
+ assert_nothing_raised {t.join}
+ end
+end if IO.method_defined?(:nonblock)
diff --git a/ruby_1_8_6/test/logger/test_logger.rb b/ruby_1_8_6/test/logger/test_logger.rb
new file mode 100644
index 0000000000..ab578a1b81
--- /dev/null
+++ b/ruby_1_8_6/test/logger/test_logger.rb
@@ -0,0 +1,376 @@
+require 'test/unit'
+require 'logger'
+require 'tempfile'
+
+
+class TestLoggerSeverity < Test::Unit::TestCase
+ def test_enum
+ logger_levels = Logger.constants
+ levels = ["WARN", "UNKNOWN", "INFO", "FATAL", "DEBUG", "ERROR"]
+ Logger::Severity.constants.each do |level|
+ assert(levels.include?(level))
+ assert(logger_levels.include?(level))
+ end
+ assert_equal(levels.size, Logger::Severity.constants.size)
+ end
+end
+
+
+class TestLogger < Test::Unit::TestCase
+ include Logger::Severity
+
+ def setup
+ @logger = Logger.new(nil)
+ end
+
+ class Log
+ attr_reader :label, :datetime, :pid, :severity, :progname, :msg
+ def initialize(line)
+ /\A(\w+), \[([^#]*)#(\d+)\]\s+(\w+) -- (\w*): ([\x0-\xff]*)/ =~ line
+ @label, @datetime, @pid, @severity, @progname, @msg = $1, $2, $3, $4, $5, $6
+ end
+ end
+
+ def log_add(logger, severity, msg, progname = nil, &block)
+ log(logger, :add, severity, msg, progname, &block)
+ end
+
+ def log(logger, msg_id, *arg, &block)
+ Log.new(log_raw(logger, msg_id, *arg, &block))
+ end
+
+ def log_raw(logger, msg_id, *arg, &block)
+ logdev = Tempfile.new(File.basename(__FILE__) + '.log')
+ logger.instance_eval { @logdev = Logger::LogDevice.new(logdev) }
+ logger.__send__(msg_id, *arg, &block)
+ logdev.open
+ msg = logdev.read
+ logdev.close
+ msg
+ end
+
+ def test_level
+ @logger.level = UNKNOWN
+ assert_equal(UNKNOWN, @logger.level)
+ @logger.level = INFO
+ assert_equal(INFO, @logger.level)
+ @logger.sev_threshold = ERROR
+ assert_equal(ERROR, @logger.sev_threshold)
+ @logger.sev_threshold = WARN
+ assert_equal(WARN, @logger.sev_threshold)
+ assert_equal(WARN, @logger.level)
+
+ @logger.level = DEBUG
+ assert(@logger.debug?)
+ assert(@logger.info?)
+ @logger.level = INFO
+ assert(!@logger.debug?)
+ assert(@logger.info?)
+ assert(@logger.warn?)
+ @logger.level = WARN
+ assert(!@logger.info?)
+ assert(@logger.warn?)
+ assert(@logger.error?)
+ @logger.level = ERROR
+ assert(!@logger.warn?)
+ assert(@logger.error?)
+ assert(@logger.fatal?)
+ @logger.level = FATAL
+ assert(!@logger.error?)
+ assert(@logger.fatal?)
+ @logger.level = UNKNOWN
+ assert(!@logger.error?)
+ assert(!@logger.fatal?)
+ end
+
+ def test_progname
+ assert_nil(@logger.progname)
+ @logger.progname = "name"
+ assert_equal("name", @logger.progname)
+ end
+
+ def test_datetime_format
+ dummy = STDERR
+ logger = Logger.new(dummy)
+ log = log_add(logger, INFO, "foo")
+ assert_match(/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\s*\d+ $/, log.datetime)
+ logger.datetime_format = "%d%b%Y@%H:%M:%S"
+ log = log_add(logger, INFO, "foo")
+ assert_match(/^\d\d\w\w\w\d\d\d\d@\d\d:\d\d:\d\d$/, log.datetime)
+ logger.datetime_format = ""
+ log = log_add(logger, INFO, "foo")
+ assert_match(/^$/, log.datetime)
+ end
+
+ def test_formatter
+ dummy = STDERR
+ logger = Logger.new(dummy)
+ # default
+ log = log(logger, :info, "foo")
+ assert_equal("foo\n", log.msg)
+ # config
+ logger.formatter = proc { |severity, timestamp, progname, msg|
+ "#{severity}:#{msg}\n\n"
+ }
+ line = log_raw(logger, :info, "foo")
+ assert_equal("INFO:foo\n\n", line)
+ # recover
+ logger.formatter = nil
+ log = log(logger, :info, "foo")
+ assert_equal("foo\n", log.msg)
+ # again
+ o = Object.new
+ def o.call(severity, timestamp, progname, msg)
+ "<<#{severity}-#{msg}>>\n"
+ end
+ logger.formatter = o
+ line = log_raw(logger, :info, "foo")
+ assert_equal("<<INFO-foo>>\n", line)
+ end
+
+ def test_initialize
+ logger = Logger.new(STDERR)
+ assert_nil(logger.progname)
+ assert_equal(DEBUG, logger.level)
+ assert_nil(logger.datetime_format)
+ end
+
+ def test_add
+ logger = Logger.new(nil)
+ logger.progname = "my_progname"
+ assert(logger.add(INFO))
+ log = log_add(logger, nil, "msg")
+ assert_equal("ANY", log.severity)
+ assert_equal("my_progname", log.progname)
+ logger.level = WARN
+ assert(logger.log(INFO))
+ assert_nil(log_add(logger, INFO, "msg").msg)
+ log = log_add(logger, WARN, nil) { "msg" }
+ assert_equal("msg\n", log.msg)
+ log = log_add(logger, WARN, "") { "msg" }
+ assert_equal("\n", log.msg)
+ assert_equal("my_progname", log.progname)
+ log = log_add(logger, WARN, nil, "progname?")
+ assert_equal("progname?\n", log.msg)
+ assert_equal("my_progname", log.progname)
+ end
+
+ def test_level_log
+ logger = Logger.new(nil)
+ logger.progname = "my_progname"
+ log = log(logger, :debug, "custom_progname") { "msg" }
+ assert_equal("msg\n", log.msg)
+ assert_equal("custom_progname", log.progname)
+ assert_equal("DEBUG", log.severity)
+ assert_equal("D", log.label)
+ #
+ log = log(logger, :debug) { "msg_block" }
+ assert_equal("msg_block\n", log.msg)
+ assert_equal("my_progname", log.progname)
+ log = log(logger, :debug, "msg_inline")
+ assert_equal("msg_inline\n", log.msg)
+ assert_equal("my_progname", log.progname)
+ #
+ log = log(logger, :info, "custom_progname") { "msg" }
+ assert_equal("msg\n", log.msg)
+ assert_equal("custom_progname", log.progname)
+ assert_equal("INFO", log.severity)
+ assert_equal("I", log.label)
+ #
+ log = log(logger, :warn, "custom_progname") { "msg" }
+ assert_equal("msg\n", log.msg)
+ assert_equal("custom_progname", log.progname)
+ assert_equal("WARN", log.severity)
+ assert_equal("W", log.label)
+ #
+ log = log(logger, :error, "custom_progname") { "msg" }
+ assert_equal("msg\n", log.msg)
+ assert_equal("custom_progname", log.progname)
+ assert_equal("ERROR", log.severity)
+ assert_equal("E", log.label)
+ #
+ log = log(logger, :fatal, "custom_progname") { "msg" }
+ assert_equal("msg\n", log.msg)
+ assert_equal("custom_progname", log.progname)
+ assert_equal("FATAL", log.severity)
+ assert_equal("F", log.label)
+ #
+ log = log(logger, :unknown, "custom_progname") { "msg" }
+ assert_equal("msg\n", log.msg)
+ assert_equal("custom_progname", log.progname)
+ assert_equal("ANY", log.severity)
+ assert_equal("A", log.label)
+ end
+
+ def test_close
+ r, w = IO.pipe
+ assert(!w.closed?)
+ logger = Logger.new(w)
+ logger.close
+ assert(w.closed?)
+ r.close
+ end
+
+ class MyError < StandardError
+ end
+
+ class MyMsg
+ def inspect
+ "my_msg"
+ end
+ end
+
+ def test_format
+ logger = Logger.new(nil)
+ log = log_add(logger, INFO, "msg\n")
+ assert_equal("msg\n\n", log.msg)
+ begin
+ raise MyError.new("excn")
+ rescue MyError => e
+ log = log_add(logger, INFO, e)
+ assert_match(/^excn \(TestLogger::MyError\)/, log.msg)
+ # expects backtrace is dumped across multi lines. 10 might be changed.
+ assert(log.msg.split(/\n/).size >= 10)
+ end
+ log = log_add(logger, INFO, MyMsg.new)
+ assert_equal("my_msg\n", log.msg)
+ end
+
+ def test_lshift
+ r, w = IO.pipe
+ logger = Logger.new(w)
+ logger << "msg"
+ read_ready, = IO.select([r], nil, nil, 0.1)
+ w.close
+ msg = r.read
+ r.close
+ assert_equal("msg", msg)
+ #
+ r, w = IO.pipe
+ logger = Logger.new(w)
+ logger << "msg2\n\n"
+ read_ready, = IO.select([r], nil, nil, 0.1)
+ w.close
+ msg = r.read
+ r.close
+ assert_equal("msg2\n\n", msg)
+ end
+end
+
+class TestLogDevice < Test::Unit::TestCase
+ def d(log)
+ Logger::LogDevice.new(log)
+ end
+
+ def test_initialize
+ logdev = d(STDERR)
+ assert_equal(STDERR, logdev.dev)
+ assert_nil(logdev.filename)
+ assert_raises(TypeError) do
+ d(nil)
+ end
+ #
+ filename = __FILE__ + ".#{$$}"
+ begin
+ logdev = d(filename)
+ assert(File.exist?(filename))
+ assert(logdev.dev.sync)
+ assert_equal(filename, logdev.filename)
+ ensure
+ logdev.close
+ File.unlink(filename)
+ end
+ end
+
+ def test_write
+ r, w = IO.pipe
+ logdev = d(w)
+ logdev.write("msg2\n\n")
+ read_ready, = IO.select([r], nil, nil, 0.1)
+ w.close
+ msg = r.read
+ r.close
+ assert_equal("msg2\n\n", msg)
+ end
+
+ def test_close
+ r, w = IO.pipe
+ logdev = d(w)
+ logdev.write("msg2\n\n")
+ read_ready, = IO.select([r], nil, nil, 0.1)
+ assert(!w.closed?)
+ logdev.close
+ assert(w.closed?)
+ r.close
+ end
+
+ def test_shifting_size
+ logfile = File.basename(__FILE__) + '_1.log'
+ logfile0 = logfile + '.0'
+ logfile1 = logfile + '.1'
+ logfile2 = logfile + '.2'
+ logfile3 = logfile + '.3'
+ File.unlink(logfile) if File.exist?(logfile)
+ File.unlink(logfile0) if File.exist?(logfile0)
+ File.unlink(logfile1) if File.exist?(logfile1)
+ File.unlink(logfile2) if File.exist?(logfile2)
+ logger = Logger.new(logfile, 4, 100)
+ logger.error("0" * 15)
+ assert(File.exist?(logfile))
+ assert(!File.exist?(logfile0))
+ logger.error("0" * 15)
+ assert(File.exist?(logfile0))
+ assert(!File.exist?(logfile1))
+ logger.error("0" * 15)
+ assert(File.exist?(logfile1))
+ assert(!File.exist?(logfile2))
+ logger.error("0" * 15)
+ assert(File.exist?(logfile2))
+ assert(!File.exist?(logfile3))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile3))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile3))
+ logger.close
+ File.unlink(logfile)
+ File.unlink(logfile0)
+ File.unlink(logfile1)
+ File.unlink(logfile2)
+
+ logfile = File.basename(__FILE__) + '_2.log'
+ logfile0 = logfile + '.0'
+ logfile1 = logfile + '.1'
+ logfile2 = logfile + '.2'
+ logfile3 = logfile + '.3'
+ logger = Logger.new(logfile, 4, 150)
+ logger.error("0" * 15)
+ assert(File.exist?(logfile))
+ assert(!File.exist?(logfile0))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile0))
+ logger.error("0" * 15)
+ assert(File.exist?(logfile0))
+ assert(!File.exist?(logfile1))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile1))
+ logger.error("0" * 15)
+ assert(File.exist?(logfile1))
+ assert(!File.exist?(logfile2))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile2))
+ logger.error("0" * 15)
+ assert(File.exist?(logfile2))
+ assert(!File.exist?(logfile3))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile3))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile3))
+ logger.error("0" * 15)
+ assert(!File.exist?(logfile3))
+ logger.close
+ File.unlink(logfile)
+ File.unlink(logfile0)
+ File.unlink(logfile1)
+ File.unlink(logfile2)
+ end
+end
diff --git a/ruby_1_8_6/test/monitor/test_monitor.rb b/ruby_1_8_6/test/monitor/test_monitor.rb
new file mode 100644
index 0000000000..b539cb3cca
--- /dev/null
+++ b/ruby_1_8_6/test/monitor/test_monitor.rb
@@ -0,0 +1,161 @@
+require "monitor"
+require "thread"
+
+require "test/unit"
+
+class TestMonitor < Test::Unit::TestCase
+ def setup
+ @monitor = Monitor.new
+ end
+
+ def test_enter
+ ary = []
+ queue = Queue.new
+ th = Thread.start {
+ queue.pop
+ @monitor.enter
+ for i in 6 .. 10
+ ary.push(i)
+ Thread.pass
+ end
+ @monitor.exit
+ }
+ @monitor.enter
+ queue.enq(nil)
+ for i in 1 .. 5
+ ary.push(i)
+ Thread.pass
+ end
+ @monitor.exit
+ th.join
+ assert_equal((1..10).to_a, ary)
+ end
+
+ def test_synchronize
+ ary = []
+ queue = Queue.new
+ th = Thread.start {
+ queue.pop
+ @monitor.synchronize do
+ for i in 6 .. 10
+ ary.push(i)
+ Thread.pass
+ end
+ end
+ }
+ @monitor.synchronize do
+ queue.enq(nil)
+ for i in 1 .. 5
+ ary.push(i)
+ Thread.pass
+ end
+ end
+ th.join
+ assert_equal((1..10).to_a, ary)
+ end
+
+ def test_try_enter
+ queue1 = Queue.new
+ queue2 = Queue.new
+ th = Thread.start {
+ queue1.deq
+ @monitor.enter
+ queue2.enq(nil)
+ queue1.deq
+ @monitor.exit
+ queue2.enq(nil)
+ }
+ assert_equal(true, @monitor.try_enter)
+ @monitor.exit
+ queue1.enq(nil)
+ queue2.deq
+ assert_equal(false, @monitor.try_enter)
+ queue1.enq(nil)
+ queue2.deq
+ assert_equal(true, @monitor.try_enter)
+ end
+
+ def test_cond
+ cond = @monitor.new_cond
+
+ a = "foo"
+ queue1 = Queue.new
+ Thread.start do
+ queue1.deq
+ @monitor.synchronize do
+ a = "bar"
+ cond.signal
+ end
+ end
+ @monitor.synchronize do
+ queue1.enq(nil)
+ assert_equal("foo", a)
+ result1 = cond.wait
+ assert_equal(true, result1)
+ assert_equal("bar", a)
+ end
+
+ b = "foo"
+ queue2 = Queue.new
+ Thread.start do
+ queue2.deq
+ @monitor.synchronize do
+ b = "bar"
+ cond.signal
+ end
+ end
+ @monitor.synchronize do
+ queue2.enq(nil)
+ assert_equal("foo", b)
+ result2 = cond.wait(0.1)
+ assert_equal(true, result2)
+ assert_equal("bar", b)
+ end
+
+ c = "foo"
+ queue3 = Queue.new
+ Thread.start do
+ queue3.deq
+ @monitor.synchronize do
+ c = "bar"
+ cond.signal
+ end
+ end
+ @monitor.synchronize do
+ assert_equal("foo", c)
+ result3 = cond.wait(0.1)
+ assert_equal(false, result3)
+ assert_equal("foo", c)
+ queue3.enq(nil)
+ result4 = cond.wait
+ assert_equal(true, result4)
+ assert_equal("bar", c)
+ end
+
+# d = "foo"
+# cumber_thread = Thread.start {
+# loop do
+# @monitor.synchronize do
+# d = "foo"
+# end
+# end
+# }
+# queue3 = Queue.new
+# Thread.start do
+# queue3.pop
+# @monitor.synchronize do
+# d = "bar"
+# cond.signal
+# end
+# end
+# @monitor.synchronize do
+# queue3.enq(nil)
+# assert_equal("foo", d)
+# result5 = cond.wait
+# assert_equal(true, result5)
+# # this thread has priority over cumber_thread
+# assert_equal("bar", d)
+# end
+# cumber_thread.kill
+ end
+end
diff --git a/ruby_1_8_6/test/net/http/test_httpheader.rb b/ruby_1_8_6/test/net/http/test_httpheader.rb
new file mode 100644
index 0000000000..3ba1b217c0
--- /dev/null
+++ b/ruby_1_8_6/test/net/http/test_httpheader.rb
@@ -0,0 +1,317 @@
+require 'net/http'
+require 'test/unit'
+
+class HTTPHeaderTest < Test::Unit::TestCase
+
+ class C
+ include Net::HTTPHeader
+ def initialize
+ initialize_http_header({})
+ end
+ attr_accessor :body
+ end
+
+ def setup
+ @c = C.new
+ end
+
+ def test_size
+ assert_equal 0, @c.size
+ @c['a'] = 'a'
+ assert_equal 1, @c.size
+ @c['b'] = 'b'
+ assert_equal 2, @c.size
+ @c['b'] = 'b'
+ assert_equal 2, @c.size
+ @c['c'] = 'c'
+ assert_equal 3, @c.size
+ end
+
+ def test_ASET
+ @c['My-Header'] = 'test string'
+ @c['my-Header'] = 'test string'
+ @c['My-header'] = 'test string'
+ @c['my-header'] = 'test string'
+ @c['MY-HEADER'] = 'test string'
+ assert_equal 1, @c.size
+
+ @c['AaA'] = 'aaa'
+ @c['aaA'] = 'aaa'
+ @c['AAa'] = 'aaa'
+ assert_equal 2, @c.length
+ end
+
+ def test_AREF
+ @c['My-Header'] = 'test string'
+ assert_equal 'test string', @c['my-header']
+ assert_equal 'test string', @c['MY-header']
+ assert_equal 'test string', @c['my-HEADER']
+
+ @c['Next-Header'] = 'next string'
+ assert_equal 'next string', @c['next-header']
+ end
+
+ def test_add_field
+ @c.add_field 'My-Header', 'a'
+ assert_equal 'a', @c['My-Header']
+ assert_equal ['a'], @c.get_fields('My-Header')
+ @c.add_field 'My-Header', 'b'
+ assert_equal 'a, b', @c['My-Header']
+ assert_equal ['a', 'b'], @c.get_fields('My-Header')
+ @c.add_field 'My-Header', 'c'
+ assert_equal 'a, b, c', @c['My-Header']
+ assert_equal ['a', 'b', 'c'], @c.get_fields('My-Header')
+ @c.add_field 'My-Header', 'd, d'
+ assert_equal 'a, b, c, d, d', @c['My-Header']
+ assert_equal ['a', 'b', 'c', 'd, d'], @c.get_fields('My-Header')
+ end
+
+ def test_get_fields
+ @c['My-Header'] = 'test string'
+ assert_equal ['test string'], @c.get_fields('my-header')
+ assert_equal ['test string'], @c.get_fields('My-header')
+ assert_equal ['test string'], @c.get_fields('my-Header')
+
+ assert_nil @c.get_fields('not-found')
+ assert_nil @c.get_fields('Not-Found')
+
+ @c.get_fields('my-header').push 'junk'
+ assert_equal ['test string'], @c.get_fields('my-header')
+ @c.get_fields('my-header').clear
+ assert_equal ['test string'], @c.get_fields('my-header')
+ end
+
+ def test_delete
+ @c['My-Header'] = 'test'
+ assert_equal 'test', @c['My-Header']
+ assert_nil @c['not-found']
+ @c.delete 'My-Header'
+ assert_nil @c['My-Header']
+ assert_nil @c['not-found']
+ @c.delete 'My-Header'
+ @c.delete 'My-Header'
+ assert_nil @c['My-Header']
+ assert_nil @c['not-found']
+ end
+
+ def test_each
+ @c['My-Header'] = 'test'
+ @c.each do |k, v|
+ assert_equal 'my-header', k
+ assert_equal 'test', v
+ end
+ @c.each do |k, v|
+ assert_equal 'my-header', k
+ assert_equal 'test', v
+ end
+ end
+
+ def test_each_key
+ @c['My-Header'] = 'test'
+ @c.each_key do |k|
+ assert_equal 'my-header', k
+ end
+ @c.each_key do |k|
+ assert_equal 'my-header', k
+ end
+ end
+
+ def test_each_value
+ @c['My-Header'] = 'test'
+ @c.each_value do |v|
+ assert_equal 'test', v
+ end
+ @c.each_value do |v|
+ assert_equal 'test', v
+ end
+ end
+
+ def test_canonical_each
+ @c['my-header'] = ['a', 'b']
+ @c.canonical_each do |k,v|
+ assert_equal 'My-Header', k
+ assert_equal 'a, b', v
+ end
+ end
+
+ def test_each_capitalized
+ @c['my-header'] = ['a', 'b']
+ @c.each_capitalized do |k,v|
+ assert_equal 'My-Header', k
+ assert_equal 'a, b', v
+ end
+ end
+
+ def test_key?
+ @c['My-Header'] = 'test'
+ assert_equal true, @c.key?('My-Header')
+ assert_equal true, @c.key?('my-header')
+ assert_equal false, @c.key?('Not-Found')
+ assert_equal false, @c.key?('not-found')
+ assert_equal false, @c.key?('')
+ assert_equal false, @c.key?('x' * 1024)
+ end
+
+ def test_to_hash
+ end
+
+ def test_range
+ try_range(1..5, '1-5')
+ try_range(234..567, '234-567')
+ try_range(-5..-1, '-5')
+ try_range(1..-1, '1-')
+ end
+
+ def try_range(r, s)
+ @c['range'] = "bytes=#{s}"
+ assert_equal r, Array(@c.range)[0]
+ end
+
+ def test_range=
+ @c.range = 0..499
+ assert_equal 'bytes=0-499', @c['range']
+ @c.range = 0...500
+ assert_equal 'bytes=0-499', @c['range']
+ @c.range = 300
+ assert_equal 'bytes=0-299', @c['range']
+ @c.range = -400
+ assert_equal 'bytes=-400', @c['range']
+ @c.set_range 0, 500
+ assert_equal 'bytes=0-499', @c['range']
+ end
+
+ def test_content_range
+ end
+
+ def test_range_length
+ @c['Content-Range'] = "bytes 0-499/1000"
+ assert_equal 500, @c.range_length
+ @c['Content-Range'] = "bytes 1-500/1000"
+ assert_equal 500, @c.range_length
+ @c['Content-Range'] = "bytes 1-1/1000"
+ assert_equal 1, @c.range_length
+ end
+
+ def test_chunked?
+ try_chunked true, 'chunked'
+ try_chunked true, ' chunked '
+ try_chunked true, '(OK)chunked'
+
+ try_chunked false, 'not-chunked'
+ try_chunked false, 'chunked-but-not-chunked'
+ end
+
+ def try_chunked(bool, str)
+ @c['transfer-encoding'] = str
+ assert_equal bool, @c.chunked?
+ end
+
+ def test_content_length
+ @c.delete('content-length')
+ assert_nil @c['content-length']
+
+ try_content_length 500, '500'
+ try_content_length 10000_0000_0000, '1000000000000'
+ try_content_length 123, ' 123'
+ try_content_length 1, '1 23'
+ try_content_length 500, '(OK)500'
+ assert_raises(Net::HTTPHeaderSyntaxError, 'here is no digit, but') {
+ @c['content-length'] = 'no digit'
+ @c.content_length
+ }
+ end
+
+ def try_content_length(len, str)
+ @c['content-length'] = str
+ assert_equal len, @c.content_length
+ end
+
+ def test_content_length=
+ @c.content_length = 0
+ assert_equal 0, @c.content_length
+ @c.content_length = 1
+ assert_equal 1, @c.content_length
+ @c.content_length = 999
+ assert_equal 999, @c.content_length
+ @c.content_length = 10000000000000
+ assert_equal 10000000000000, @c.content_length
+ end
+
+ def test_content_type
+ assert_nil @c.content_type
+ @c.content_type = 'text/html'
+ assert_equal 'text/html', @c.content_type
+ @c.content_type = 'application/pdf'
+ assert_equal 'application/pdf', @c.content_type
+ @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
+ assert_equal 'text/html', @c.content_type
+ @c.content_type = 'text'
+ assert_equal 'text', @c.content_type
+ end
+
+ def test_main_type
+ assert_nil @c.main_type
+ @c.content_type = 'text/html'
+ assert_equal 'text', @c.main_type
+ @c.content_type = 'application/pdf'
+ assert_equal 'application', @c.main_type
+ @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
+ assert_equal 'text', @c.main_type
+ @c.content_type = 'text'
+ assert_equal 'text', @c.main_type
+ end
+
+ def test_sub_type
+ assert_nil @c.sub_type
+ @c.content_type = 'text/html'
+ assert_equal 'html', @c.sub_type
+ @c.content_type = 'application/pdf'
+ assert_equal 'pdf', @c.sub_type
+ @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
+ assert_equal 'html', @c.sub_type
+ @c.content_type = 'text'
+ assert_nil @c.sub_type
+ end
+
+ def test_type_params
+ assert_equal({}, @c.type_params)
+ @c.content_type = 'text/html'
+ assert_equal({}, @c.type_params)
+ @c.content_type = 'application/pdf'
+ assert_equal({}, @c.type_params)
+ @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
+ assert_equal({'charset' => 'iso-2022-jp'}, @c.type_params)
+ @c.content_type = 'text'
+ assert_equal({}, @c.type_params)
+ end
+
+ def test_set_content_type
+ end
+
+ def test_form_data=
+ @c.form_data = {"cmd"=>"search", "q"=>"ruby", "max"=>"50"}
+ assert_equal 'application/x-www-form-urlencoded', @c.content_type
+ assert_equal %w( cmd=search max=50 q=ruby ), @c.body.split('&').sort
+ end
+
+ def test_set_form_data
+ @c.set_form_data "cmd"=>"search", "q"=>"ruby", "max"=>"50"
+ assert_equal 'application/x-www-form-urlencoded', @c.content_type
+ assert_equal %w( cmd=search max=50 q=ruby ), @c.body.split('&').sort
+
+ @c.set_form_data "cmd"=>"search", "q"=>"ruby", "max"=>50
+ assert_equal 'application/x-www-form-urlencoded', @c.content_type
+ assert_equal %w( cmd=search max=50 q=ruby ), @c.body.split('&').sort
+
+ @c.set_form_data({"cmd"=>"search", "q"=>"ruby", "max"=>"50"}, ';')
+ assert_equal 'application/x-www-form-urlencoded', @c.content_type
+ assert_equal %w( cmd=search max=50 q=ruby ), @c.body.split(';').sort
+ end
+
+ def test_basic_auth
+ end
+
+ def test_proxy_basic_auth
+ end
+
+end
diff --git a/ruby_1_8_6/test/net/http/test_https_proxy.rb b/ruby_1_8_6/test/net/http/test_https_proxy.rb
new file mode 100644
index 0000000000..6332319f26
--- /dev/null
+++ b/ruby_1_8_6/test/net/http/test_https_proxy.rb
@@ -0,0 +1,30 @@
+begin
+ require 'net/https'
+rescue LoadError
+end
+require 'test/unit'
+
+class HTTPSProxyTest < Test::Unit::TestCase
+ def test_https_proxy_authentication
+ TCPServer.open("127.0.0.1", 0) {|serv|
+ _, port, _, _ = serv.addr
+ t = Thread.new {
+ proxy = Net::HTTP.Proxy("127.0.0.1", port, 'user', 'password')
+ http = proxy.new("foo.example.org", 8000)
+ http.use_ssl = true
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
+ http.start
+ }
+ sock = serv.accept
+ proxy_request = sock.gets("\r\n\r\n")
+ assert_equal(
+ "CONNECT foo.example.org:8000 HTTP/1.1\r\n" +
+ "Host: foo.example.org:8000\r\n" +
+ "Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA==\r\n" +
+ "\r\n",
+ proxy_request,
+ "[ruby-dev:25673]")
+ }
+ end
+end if defined?(OpenSSL)
+
diff --git a/ruby_1_8_6/test/net/imap/test_imap.rb b/ruby_1_8_6/test/net/imap/test_imap.rb
new file mode 100644
index 0000000000..0ee217965c
--- /dev/null
+++ b/ruby_1_8_6/test/net/imap/test_imap.rb
@@ -0,0 +1,11 @@
+require "net/imap"
+require "test/unit"
+
+class IMAPTest < Test::Unit::TestCase
+ def test_parse_nomodesq
+ parser = Net::IMAP::ResponseParser.new
+ r = parser.parse(%Q'* OK [NOMODSEQ] Sorry, modsequences have not been enabled on this mailbox\r\n')
+ assert_equal("OK", r.name)
+ assert_equal("NOMODSEQ", r.data.code.name)
+ end
+end
diff --git a/ruby_1_8_6/test/nkf/test_kconv.rb b/ruby_1_8_6/test/nkf/test_kconv.rb
new file mode 100644
index 0000000000..2533424705
--- /dev/null
+++ b/ruby_1_8_6/test/nkf/test_kconv.rb
@@ -0,0 +1,71 @@
+require 'test/unit'
+require 'kconv'
+
+class TestKconv < Test::Unit::TestCase
+ EUC_STR = "\
+\xa5\xaa\xa5\xd6\xa5\xb8\xa5\xa7\xa5\xaf\xa5\xc8\xbb\xd8\xb8\xfe\
+\xa5\xd7\xa5\xed\xa5\xb0\xa5\xe9\xa5\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec
+\x52\x75\x62\x79"
+ UTF8_STR = "\
+\xe3\x82\xaa\xe3\x83\x96\xe3\x82\xb8\xe3\x82\xa7\
+\xe3\x82\xaf\xe3\x83\x88\xe6\x8c\x87\xe5\x90\x91\
+\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3\x83\x9f\
+\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e
+\x52\x75\x62\x79"
+ SJIS_STR = "\
+\x83\x49\x83\x75\x83\x57\x83\x46\x83\x4e\x83\x67\x8e\x77\x8c\xfc\
+\x83\x76\x83\x8d\x83\x4f\x83\x89\x83\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea
+\x52\x75\x62\x79"
+ JIS_STR = "\
+\x1b\x24\x42\x25\x2a\x25\x56\x25\x38\x25\x27\x25\x2f\x25\x48\x3b\x58\x38\x7e\
+\x25\x57\x25\x6d\x25\x30\x25\x69\x25\x5f\x25\x73\x25\x30\x38\x40\x38\x6c\x1b\x28\x42
+\x52\x75\x62\x79"
+
+ def test_eucjp
+ assert(EUC_STR.iseuc)
+ assert_equal(::Kconv::EUC, Kconv.guess(EUC_STR))
+ assert_equal(EUC_STR, EUC_STR.toeuc)
+ assert_equal(EUC_STR, SJIS_STR.toeuc)
+ assert_equal(EUC_STR, UTF8_STR.toeuc)
+ assert_equal(EUC_STR, JIS_STR.toeuc)
+ assert_equal(EUC_STR, EUC_STR.kconv(::NKF::EUC))
+ assert_equal(EUC_STR, SJIS_STR.kconv(::NKF::EUC))
+ assert_equal(EUC_STR, UTF8_STR.kconv(::NKF::EUC))
+ assert_equal(EUC_STR, JIS_STR.kconv(::NKF::EUC))
+ end
+ def test_shiftjis
+ assert(SJIS_STR.issjis)
+ assert_equal(::Kconv::SJIS, Kconv.guess(SJIS_STR))
+ assert_equal(SJIS_STR, EUC_STR.tosjis)
+ assert_equal(SJIS_STR, SJIS_STR.tosjis)
+ assert_equal(SJIS_STR, UTF8_STR.tosjis)
+ assert_equal(SJIS_STR, JIS_STR.tosjis)
+ assert_equal(SJIS_STR, EUC_STR.kconv(::NKF::SJIS))
+ assert_equal(SJIS_STR, SJIS_STR.kconv(::NKF::SJIS))
+ assert_equal(SJIS_STR, UTF8_STR.kconv(::NKF::SJIS))
+ assert_equal(SJIS_STR, JIS_STR.kconv(::NKF::SJIS))
+ end
+ def test_utf8
+ assert(UTF8_STR.isutf8)
+ assert_equal(::Kconv::UTF8, Kconv.guess(UTF8_STR))
+ assert_equal(UTF8_STR, EUC_STR.toutf8)
+ assert_equal(UTF8_STR, SJIS_STR.toutf8)
+ assert_equal(UTF8_STR, UTF8_STR.toutf8)
+ assert_equal(UTF8_STR, JIS_STR.toutf8)
+ assert_equal(UTF8_STR, EUC_STR.kconv(::NKF::UTF8))
+ assert_equal(UTF8_STR, SJIS_STR.kconv(::NKF::UTF8))
+ assert_equal(UTF8_STR, UTF8_STR.kconv(::NKF::UTF8))
+ assert_equal(UTF8_STR, JIS_STR.kconv(::NKF::UTF8))
+ end
+ def test_jis
+ assert_equal(::Kconv::JIS, Kconv.guess(JIS_STR))
+ assert_equal(JIS_STR, EUC_STR.tojis)
+ assert_equal(JIS_STR, SJIS_STR.tojis)
+ assert_equal(JIS_STR, UTF8_STR.tojis)
+ assert_equal(JIS_STR, JIS_STR.tojis)
+ assert_equal(JIS_STR, EUC_STR.kconv(::NKF::JIS))
+ assert_equal(JIS_STR, SJIS_STR.kconv(::NKF::JIS))
+ assert_equal(JIS_STR, UTF8_STR.kconv(::NKF::JIS))
+ assert_equal(JIS_STR, JIS_STR.kconv(::NKF::JIS))
+ end
+end
diff --git a/ruby_1_8_6/test/nkf/test_nkf.rb b/ruby_1_8_6/test/nkf/test_nkf.rb
new file mode 100644
index 0000000000..279ad59e1a
--- /dev/null
+++ b/ruby_1_8_6/test/nkf/test_nkf.rb
@@ -0,0 +1,16 @@
+require 'test/unit'
+require 'nkf'
+
+class TestNKF < Test::Unit::TestCase
+ EUC_STR = "\xa5\xaa\xa5\xd6\xa5\xb8\xa5\xa7\xa5\xaf\xa5\xc8\xbb\xd8\xb8\xfe\
+\xa5\xb9\xa5\xaf\xa5\xea\xa5\xd7\xa5\xc8\xb8\xc0\xb8\xec\
+Ruby"
+
+ def test_guess
+ str_euc = EUC_STR
+ str_jis = NKF.nkf('-j', str_euc)
+ assert_equal(::NKF::JIS, NKF.guess(str_jis))
+ assert_equal(::NKF::EUC, NKF.guess(str_euc))
+ end
+
+end
diff --git a/ruby_1_8_6/test/openssl/ssl_server.rb b/ruby_1_8_6/test/openssl/ssl_server.rb
new file mode 100644
index 0000000000..6e620629c5
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/ssl_server.rb
@@ -0,0 +1,81 @@
+require "socket"
+require "thread"
+require "openssl"
+require File.join(File.dirname(__FILE__), "utils.rb")
+
+def get_pem(io=$stdin)
+ buf = ""
+ while line = io.gets
+ if /^-----BEGIN / =~ line
+ buf << line
+ break
+ end
+ end
+ while line = io.gets
+ buf << line
+ if /^-----END / =~ line
+ break
+ end
+ end
+ return buf
+end
+
+def make_key(pem)
+ begin
+ return OpenSSL::PKey::RSA.new(pem)
+ rescue
+ return OpenSSL::PKey::DSA.new(pem)
+ end
+end
+
+ca_cert = OpenSSL::X509::Certificate.new(get_pem)
+ssl_cert = OpenSSL::X509::Certificate.new(get_pem)
+ssl_key = make_key(get_pem)
+port = Integer(ARGV.shift)
+verify_mode = Integer(ARGV.shift)
+start_immediately = (/yes/ =~ ARGV.shift)
+
+store = OpenSSL::X509::Store.new
+store.add_cert(ca_cert)
+store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
+ctx = OpenSSL::SSL::SSLContext.new
+ctx.cert_store = store
+#ctx.extra_chain_cert = [ ca_cert ]
+ctx.cert = ssl_cert
+ctx.key = ssl_key
+ctx.verify_mode = verify_mode
+
+Socket.do_not_reverse_lookup = true
+tcps = nil
+100.times{|i|
+ begin
+ tcps = TCPServer.new("0.0.0.0", port+i)
+ port = port + i
+ break
+ rescue Errno::EADDRINUSE
+ next
+ end
+}
+ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
+ssls.start_immediately = start_immediately
+
+$stdout.sync = true
+$stdout.puts Process.pid
+$stdout.puts port
+
+loop do
+ ssl = ssls.accept rescue next
+ Thread.start{
+ q = Queue.new
+ th = Thread.start{ ssl.write(q.shift) while true }
+ while line = ssl.gets
+ if line =~ /^STARTTLS$/
+ ssl.accept
+ next
+ end
+ q.push(line)
+ end
+ th.kill if q.empty?
+ ssl.close
+ }
+end
diff --git a/ruby_1_8_6/test/openssl/test_asn1.rb b/ruby_1_8_6/test/openssl/test_asn1.rb
new file mode 100644
index 0000000000..f196bc48fb
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_asn1.rb
@@ -0,0 +1,197 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require 'test/unit'
+
+class OpenSSL::TestASN1 < Test::Unit::TestCase
+ def test_decode
+ subj = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=TestCA")
+ key = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ now = Time.at(Time.now.to_i) # suppress usec
+ s = 0xdeadbeafdeadbeafdeadbeafdeadbeaf
+ exts = [
+ ["basicConstraints","CA:TRUE,pathlen:1",true],
+ ["keyUsage","keyCertSign, cRLSign",true],
+ ["subjectKeyIdentifier","hash",false],
+ ]
+ dgst = OpenSSL::Digest::SHA1.new
+ cert = OpenSSL::TestUtils.issue_cert(
+ subj, key, s, now, now+3600, exts, nil, nil, dgst)
+
+
+ asn1 = OpenSSL::ASN1.decode(cert)
+ assert_equal(OpenSSL::ASN1::Sequence, asn1.class)
+ assert_equal(3, asn1.value.size)
+ tbs_cert, sig_alg, sig_val = *asn1.value
+
+ assert_equal(OpenSSL::ASN1::Sequence, tbs_cert.class)
+ assert_equal(8, tbs_cert.value.size)
+
+ version = tbs_cert.value[0]
+ assert_equal(:CONTEXT_SPECIFIC, version.tag_class)
+ assert_equal(0, version.tag)
+ assert_equal(1, version.value.size)
+ assert_equal(OpenSSL::ASN1::Integer, version.value[0].class)
+ assert_equal(2, version.value[0].value)
+
+ serial = tbs_cert.value[1]
+ assert_equal(OpenSSL::ASN1::Integer, serial.class)
+ assert_equal(0xdeadbeafdeadbeafdeadbeafdeadbeaf, serial.value)
+
+ sig = tbs_cert.value[2]
+ assert_equal(OpenSSL::ASN1::Sequence, sig.class)
+ assert_equal(2, sig.value.size)
+ assert_equal(OpenSSL::ASN1::ObjectId, sig.value[0].class)
+ assert_equal("1.2.840.113549.1.1.5", sig.value[0].oid)
+ assert_equal(OpenSSL::ASN1::Null, sig.value[1].class)
+
+ dn = tbs_cert.value[3] # issuer
+ assert_equal(subj.hash, OpenSSL::X509::Name.new(dn).hash)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.class)
+ assert_equal(3, dn.value.size)
+ assert_equal(OpenSSL::ASN1::Set, dn.value[0].class)
+ assert_equal(OpenSSL::ASN1::Set, dn.value[1].class)
+ assert_equal(OpenSSL::ASN1::Set, dn.value[2].class)
+ assert_equal(1, dn.value[0].value.size)
+ assert_equal(1, dn.value[1].value.size)
+ assert_equal(1, dn.value[2].value.size)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.value[0].value[0].class)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.value[1].value[0].class)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.value[2].value[0].class)
+ assert_equal(2, dn.value[0].value[0].value.size)
+ assert_equal(2, dn.value[1].value[0].value.size)
+ assert_equal(2, dn.value[2].value[0].value.size)
+ oid, value = *dn.value[0].value[0].value
+ assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
+ assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
+ assert_equal(OpenSSL::ASN1::IA5String, value.class)
+ assert_equal("org", value.value)
+ oid, value = *dn.value[1].value[0].value
+ assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
+ assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
+ assert_equal(OpenSSL::ASN1::IA5String, value.class)
+ assert_equal("ruby-lang", value.value)
+ oid, value = *dn.value[2].value[0].value
+ assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
+ assert_equal("2.5.4.3", oid.oid)
+ assert_equal(OpenSSL::ASN1::UTF8String, value.class)
+ assert_equal("TestCA", value.value)
+
+ validity = tbs_cert.value[4]
+ assert_equal(OpenSSL::ASN1::Sequence, validity.class)
+ assert_equal(2, validity.value.size)
+ assert_equal(OpenSSL::ASN1::UTCTime, validity.value[0].class)
+ assert_equal(now, validity.value[0].value)
+ assert_equal(OpenSSL::ASN1::UTCTime, validity.value[1].class)
+ assert_equal(now+3600, validity.value[1].value)
+
+ dn = tbs_cert.value[5] # subject
+ assert_equal(subj.hash, OpenSSL::X509::Name.new(dn).hash)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.class)
+ assert_equal(3, dn.value.size)
+ assert_equal(OpenSSL::ASN1::Set, dn.value[0].class)
+ assert_equal(OpenSSL::ASN1::Set, dn.value[1].class)
+ assert_equal(OpenSSL::ASN1::Set, dn.value[2].class)
+ assert_equal(1, dn.value[0].value.size)
+ assert_equal(1, dn.value[1].value.size)
+ assert_equal(1, dn.value[2].value.size)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.value[0].value[0].class)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.value[1].value[0].class)
+ assert_equal(OpenSSL::ASN1::Sequence, dn.value[2].value[0].class)
+ assert_equal(2, dn.value[0].value[0].value.size)
+ assert_equal(2, dn.value[1].value[0].value.size)
+ assert_equal(2, dn.value[2].value[0].value.size)
+ oid, value = *dn.value[0].value[0].value
+ assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
+ assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
+ assert_equal(OpenSSL::ASN1::IA5String, value.class)
+ assert_equal("org", value.value)
+ oid, value = *dn.value[1].value[0].value
+ assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
+ assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
+ assert_equal(OpenSSL::ASN1::IA5String, value.class)
+ assert_equal("ruby-lang", value.value)
+ oid, value = *dn.value[2].value[0].value
+ assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
+ assert_equal("2.5.4.3", oid.oid)
+ assert_equal(OpenSSL::ASN1::UTF8String, value.class)
+ assert_equal("TestCA", value.value)
+
+ pkey = tbs_cert.value[6]
+ assert_equal(OpenSSL::ASN1::Sequence, pkey.class)
+ assert_equal(2, pkey.value.size)
+ assert_equal(OpenSSL::ASN1::Sequence, pkey.value[0].class)
+ assert_equal(2, pkey.value[0].value.size)
+ assert_equal(OpenSSL::ASN1::ObjectId, pkey.value[0].value[0].class)
+ assert_equal("1.2.840.113549.1.1.1", pkey.value[0].value[0].oid)
+ assert_equal(OpenSSL::ASN1::BitString, pkey.value[1].class)
+ assert_equal(0, pkey.value[1].unused_bits)
+ spkey = OpenSSL::ASN1.decode(pkey.value[1].value)
+ assert_equal(OpenSSL::ASN1::Sequence, spkey.class)
+ assert_equal(2, spkey.value.size)
+ assert_equal(OpenSSL::ASN1::Integer, spkey.value[0].class)
+ assert_equal(143085709396403084580358323862163416700436550432664688288860593156058579474547937626086626045206357324274536445865308750491138538454154232826011964045825759324933943290377903384882276841880081931690695505836279972214003660451338124170055999155993192881685495391496854691199517389593073052473319331505702779271, spkey.value[0].value)
+ assert_equal(OpenSSL::ASN1::Integer, spkey.value[1].class)
+ assert_equal(65537, spkey.value[1].value)
+
+ extensions = tbs_cert.value[7]
+ assert_equal(:CONTEXT_SPECIFIC, extensions.tag_class)
+ assert_equal(3, extensions.tag)
+ assert_equal(1, extensions.value.size)
+ assert_equal(OpenSSL::ASN1::Sequence, extensions.value[0].class)
+ assert_equal(3, extensions.value[0].value.size)
+
+ ext = extensions.value[0].value[0] # basicConstraints
+ assert_equal(OpenSSL::ASN1::Sequence, ext.class)
+ assert_equal(3, ext.value.size)
+ assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
+ assert_equal("2.5.29.19", ext.value[0].oid)
+ assert_equal(OpenSSL::ASN1::Boolean, ext.value[1].class)
+ assert_equal(true, ext.value[1].value)
+ assert_equal(OpenSSL::ASN1::OctetString, ext.value[2].class)
+ extv = OpenSSL::ASN1.decode(ext.value[2].value)
+ assert_equal(OpenSSL::ASN1::Sequence, extv.class)
+ assert_equal(2, extv.value.size)
+ assert_equal(OpenSSL::ASN1::Boolean, extv.value[0].class)
+ assert_equal(true, extv.value[0].value)
+ assert_equal(OpenSSL::ASN1::Integer, extv.value[1].class)
+ assert_equal(1, extv.value[1].value)
+
+ ext = extensions.value[0].value[1] # keyUsage
+ assert_equal(OpenSSL::ASN1::Sequence, ext.class)
+ assert_equal(3, ext.value.size)
+ assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
+ assert_equal("2.5.29.15", ext.value[0].oid)
+ assert_equal(OpenSSL::ASN1::Boolean, ext.value[1].class)
+ assert_equal(true, ext.value[1].value)
+ assert_equal(OpenSSL::ASN1::OctetString, ext.value[2].class)
+ extv = OpenSSL::ASN1.decode(ext.value[2].value)
+ assert_equal(OpenSSL::ASN1::BitString, extv.class)
+ str = "\000"; str[0] = 0b00000110
+ assert_equal(str, extv.value)
+
+ ext = extensions.value[0].value[2] # subjetKeyIdentifier
+ assert_equal(OpenSSL::ASN1::Sequence, ext.class)
+ assert_equal(2, ext.value.size)
+ assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
+ assert_equal("2.5.29.14", ext.value[0].oid)
+ assert_equal(OpenSSL::ASN1::OctetString, ext.value[1].class)
+ extv = OpenSSL::ASN1.decode(ext.value[1].value)
+ assert_equal(OpenSSL::ASN1::OctetString, extv.class)
+ sha1 = OpenSSL::Digest::SHA1.new
+ sha1.update(pkey.value[1].value)
+ assert_equal(sha1.digest, extv.value)
+
+ assert_equal(OpenSSL::ASN1::Sequence, sig_alg.class)
+ assert_equal(2, sig_alg.value.size)
+ assert_equal(OpenSSL::ASN1::ObjectId, pkey.value[0].value[0].class)
+ assert_equal("1.2.840.113549.1.1.1", pkey.value[0].value[0].oid)
+ assert_equal(OpenSSL::ASN1::Null, pkey.value[0].value[1].class)
+
+ assert_equal(OpenSSL::ASN1::BitString, sig_val.class)
+ cululated_sig = key.sign(OpenSSL::Digest::SHA1.new, tbs_cert.to_der)
+ assert_equal(cululated_sig, sig_val.value)
+ end
+end if defined?(OpenSSL)
diff --git a/ruby_1_8_6/test/openssl/test_cipher.rb b/ruby_1_8_6/test/openssl/test_cipher.rb
new file mode 100644
index 0000000000..d671908165
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_cipher.rb
@@ -0,0 +1,95 @@
+begin
+ require "openssl"
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestCipher < Test::Unit::TestCase
+ def setup
+ @c1 = OpenSSL::Cipher::Cipher.new("DES-EDE3-CBC")
+ @c2 = OpenSSL::Cipher::DES.new(:EDE3, "CBC")
+ @key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+ @iv = "\0\0\0\0\0\0\0\0"
+ @hexkey = "0000000000000000000000000000000000000000000000"
+ @hexiv = "0000000000000000"
+ @data = "DATA"
+ end
+
+ def teardown
+ @c1 = @c2 = nil
+ end
+
+ def test_crypt
+ @c1.encrypt.pkcs5_keyivgen(@key, @iv)
+ @c2.encrypt.pkcs5_keyivgen(@key, @iv)
+ s1 = @c1.update(@data) + @c1.final
+ s2 = @c2.update(@data) + @c2.final
+ assert_equal(s1, s2, "encrypt")
+
+ @c1.decrypt.pkcs5_keyivgen(@key, @iv)
+ @c2.decrypt.pkcs5_keyivgen(@key, @iv)
+ assert_equal(@data, @c1.update(s1)+@c1.final, "decrypt")
+ assert_equal(@data, @c2.update(s2)+@c2.final, "decrypt")
+ end
+
+ def test_info
+ assert_equal("DES-EDE3-CBC", @c1.name, "name")
+ assert_equal("DES-EDE3-CBC", @c2.name, "name")
+ assert_kind_of(Fixnum, @c1.key_len, "key_len")
+ assert_kind_of(Fixnum, @c1.iv_len, "iv_len")
+ end
+
+ def test_dup
+ assert_equal(@c1.name, @c1.dup.name, "dup")
+ assert_equal(@c1.name, @c1.clone.name, "clone")
+ @c1.encrypt
+ @c1.key = @key
+ @c1.iv = @iv
+ tmpc = @c1.dup
+ s1 = @c1.update(@data) + @c1.final
+ s2 = tmpc.update(@data) + tmpc.final
+ assert_equal(s1, s2, "encrypt dup")
+ end
+
+ def test_reset
+ @c1.encrypt
+ @c1.key = @key
+ @c1.iv = @iv
+ s1 = @c1.update(@data) + @c1.final
+ @c1.reset
+ s2 = @c1.update(@data) + @c1.final
+ assert_equal(s1, s2, "encrypt reset")
+ end
+
+ def test_empty_data
+ @c1.encrypt
+ assert_raises(ArgumentError){ @c1.update("") }
+ end
+
+ if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00907000
+ def test_ciphers
+ OpenSSL::Cipher.ciphers.each{|name|
+ assert(OpenSSL::Cipher::Cipher.new(name).is_a?(OpenSSL::Cipher::Cipher))
+ }
+ end
+
+ def test_AES
+ pt = File.read(__FILE__)
+ %w(ECB CBC CFB OFB).each{|mode|
+ c1 = OpenSSL::Cipher::AES256.new(mode)
+ c1.encrypt
+ c1.pkcs5_keyivgen("passwd")
+ ct = c1.update(pt) + c1.final
+
+ c2 = OpenSSL::Cipher::AES256.new(mode)
+ c2.decrypt
+ c2.pkcs5_keyivgen("passwd")
+ assert_equal(pt, c2.update(ct) + c2.final)
+ }
+ end
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_digest.rb b/ruby_1_8_6/test/openssl/test_digest.rb
new file mode 100644
index 0000000000..8941588b97
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_digest.rb
@@ -0,0 +1,88 @@
+begin
+ require "openssl"
+rescue LoadError
+end
+require "digest/md5"
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestDigest < Test::Unit::TestCase
+ def setup
+ @d1 = OpenSSL::Digest::Digest::new("MD5")
+ @d2 = OpenSSL::Digest::MD5.new
+ @md = Digest::MD5.new
+ @data = "DATA"
+ end
+
+ def teardown
+ @d1 = @d2 = @md = nil
+ end
+
+ def test_digest
+ assert_equal(@md.digest, @d1.digest)
+ assert_equal(@md.hexdigest, @d1.hexdigest)
+ @d1 << @data
+ @d2 << @data
+ @md << @data
+ assert_equal(@md.digest, @d1.digest)
+ assert_equal(@md.hexdigest, @d1.hexdigest)
+ assert_equal(@d1.digest, @d2.digest)
+ assert_equal(@d1.hexdigest, @d2.hexdigest)
+ assert_equal(@md.digest, OpenSSL::Digest::MD5.digest(@data))
+ assert_equal(@md.hexdigest, OpenSSL::Digest::MD5.hexdigest(@data))
+ end
+
+ def test_eql
+ assert(@d1 == @d2, "==")
+ d = @d1.clone
+ assert(d == @d1, "clone")
+ end
+
+ def test_info
+ assert_equal("MD5", @d1.name, "name")
+ assert_equal("MD5", @d2.name, "name")
+ assert_equal(16, @d1.size, "size")
+ end
+
+ def test_dup
+ @d1.update(@data)
+ assert_equal(@d1.name, @d1.dup.name, "dup")
+ assert_equal(@d1.name, @d1.clone.name, "clone")
+ assert_equal(@d1.digest, @d1.clone.digest, "clone .digest")
+ end
+
+ def test_reset
+ @d1.update(@data)
+ dig1 = @d1.digest
+ @d1.reset
+ @d1.update(@data)
+ dig2 = @d1.digest
+ assert_equal(dig1, dig2, "reset")
+ end
+
+ if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00908000
+ def encode16(str)
+ str.unpack("H*").first
+ end
+
+ def test_098_features
+ sha224_a = "abd37534c7d9a2efb9465de931cd7055ffdb8879563ae98078d6d6d5"
+ sha256_a = "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
+ sha384_a = "54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31"
+ sha512_a = "1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75"
+
+ assert_equal(sha224_a, OpenSSL::Digest::SHA224.hexdigest("a"))
+ assert_equal(sha256_a, OpenSSL::Digest::SHA256.hexdigest("a"))
+ assert_equal(sha384_a, OpenSSL::Digest::SHA384.hexdigest("a"))
+ assert_equal(sha512_a, OpenSSL::Digest::SHA512.hexdigest("a"))
+
+ assert_equal(sha224_a, encode16(OpenSSL::Digest::SHA224.digest("a")))
+ assert_equal(sha256_a, encode16(OpenSSL::Digest::SHA256.digest("a")))
+ assert_equal(sha384_a, encode16(OpenSSL::Digest::SHA384.digest("a")))
+ assert_equal(sha512_a, encode16(OpenSSL::Digest::SHA512.digest("a")))
+ end
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_hmac.rb b/ruby_1_8_6/test/openssl/test_hmac.rb
new file mode 100644
index 0000000000..2f8d6bba20
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_hmac.rb
@@ -0,0 +1,34 @@
+begin
+ require "openssl"
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestHMAC < Test::Unit::TestCase
+ def setup
+ @digest = OpenSSL::Digest::MD5.new
+ @key = "KEY"
+ @data = "DATA"
+ @h1 = OpenSSL::HMAC.new(@key, @digest)
+ @h2 = OpenSSL::HMAC.new(@key, @digest)
+ end
+
+ def teardown
+ end
+
+ def test_hmac
+ @h1.update(@data)
+ assert_equal(OpenSSL::HMAC.digest(@digest, @key, @data), @h1.digest, "digest")
+ assert_equal(OpenSSL::HMAC.hexdigest(@digest, @key, @data), @h1.hexdigest, "hexdigest")
+ end
+
+ def test_dup
+ @h1.update(@data)
+ h = @h1.dup
+ assert_equal(@h1.digest, h.digest, "dup digest")
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_ns_spki.rb b/ruby_1_8_6/test/openssl/test_ns_spki.rb
new file mode 100644
index 0000000000..3937132aa0
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_ns_spki.rb
@@ -0,0 +1,59 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+
+class OpenSSL::TestNSSPI < Test::Unit::TestCase
+ def setup
+ # This request data is adopt from the specification of
+ # "Netscape Extensions for User Key Generation".
+ # -- http://wp.netscape.com/eng/security/comm4-keygen.html
+ @b64 = "MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue+PtwBRE6XfV"
+ @b64 << "WtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID"
+ @b64 << "AQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n/S"
+ @b64 << "r/7iJNroWlSzSMtTiQTEB+ADWHGj9u1xrUrOilq/o2cuQxIfZcNZkYAkWP4DubqW"
+ @b64 << "i0//rgBvmco="
+ end
+
+ def teardown
+ end
+
+ def test_build_data
+ key1 = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ key2 = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ spki = OpenSSL::Netscape::SPKI.new
+ spki.challenge = "RandomString"
+ spki.public_key = key1.public_key
+ spki.sign(key1, OpenSSL::Digest::SHA1.new)
+ assert(spki.verify(spki.public_key))
+ assert(spki.verify(key1.public_key))
+ assert(!spki.verify(key2.public_key))
+
+ der = spki.to_der
+ spki = OpenSSL::Netscape::SPKI.new(der)
+ assert_equal("RandomString", spki.challenge)
+ assert_equal(key1.public_key.to_der, spki.public_key.to_der)
+ assert(spki.verify(spki.public_key))
+ end
+
+ def test_decode_data
+ spki = OpenSSL::Netscape::SPKI.new(@b64)
+ assert_equal(@b64, spki.to_pem)
+ assert_equal(@b64.unpack("m").first, spki.to_der)
+ assert_equal("MozillaIsMyFriend", spki.challenge)
+ assert_equal(OpenSSL::PKey::RSA, spki.public_key.class)
+
+ spki = OpenSSL::Netscape::SPKI.new(@b64.unpack("m").first)
+ assert_equal(@b64, spki.to_pem)
+ assert_equal(@b64.unpack("m").first, spki.to_der)
+ assert_equal("MozillaIsMyFriend", spki.challenge)
+ assert_equal(OpenSSL::PKey::RSA, spki.public_key.class)
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_pair.rb b/ruby_1_8_6/test/openssl/test_pair.rb
new file mode 100644
index 0000000000..7273554362
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_pair.rb
@@ -0,0 +1,144 @@
+begin
+ require "openssl"
+rescue LoadError
+end
+require 'test/unit'
+
+if defined?(OpenSSL)
+
+require 'socket'
+dir = File.expand_path(__FILE__)
+2.times {dir = File.dirname(dir)}
+$:.replace([File.join(dir, "ruby")] | $:)
+require 'ut_eof'
+
+module SSLPair
+ def server
+ host = "127.0.0.1"
+ port = 0
+ ctx = OpenSSL::SSL::SSLContext.new()
+ ctx.ciphers = "ADH"
+ tcps = TCPServer.new(host, port)
+ ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
+ return ssls
+ end
+
+ def client(port)
+ host = "127.0.0.1"
+ ctx = OpenSSL::SSL::SSLContext.new()
+ ctx.ciphers = "ADH"
+ s = TCPSocket.new(host, port)
+ ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
+ ssl.connect
+ ssl.sync_close = true
+ ssl
+ end
+
+ def ssl_pair
+ ssls = server
+ th = Thread.new {
+ ns = ssls.accept
+ ssls.close
+ ns
+ }
+ port = ssls.to_io.addr[1]
+ c = client(port)
+ s = th.value
+ if block_given?
+ begin
+ yield c, s
+ ensure
+ c.close unless c.closed?
+ s.close unless s.closed?
+ end
+ else
+ return c, s
+ end
+ end
+end
+
+class OpenSSL::TestEOF1 < Test::Unit::TestCase
+ include TestEOF
+ include SSLPair
+
+ def open_file(content)
+ s1, s2 = ssl_pair
+ Thread.new { s2 << content; s2.close }
+ yield s1
+ end
+end
+
+class OpenSSL::TestEOF2 < Test::Unit::TestCase
+ include TestEOF
+ include SSLPair
+
+ def open_file(content)
+ s1, s2 = ssl_pair
+ Thread.new { s1 << content; s1.close }
+ yield s2
+ end
+end
+
+class OpenSSL::TestPair < Test::Unit::TestCase
+ include SSLPair
+
+ def test_getc
+ ssl_pair {|s1, s2|
+ s1 << "a"
+ assert_equal(?a, s2.getc)
+ }
+ end
+
+ def test_readpartial
+ ssl_pair {|s1, s2|
+ s2.write "a\nbcd"
+ assert_equal("a\n", s1.gets)
+ assert_equal("bcd", s1.readpartial(10))
+ s2.write "efg"
+ assert_equal("efg", s1.readpartial(10))
+ s2.close
+ assert_raise(EOFError) { s1.readpartial(10) }
+ assert_raise(EOFError) { s1.readpartial(10) }
+ assert_equal("", s1.readpartial(0))
+ }
+ end
+
+ def test_readall
+ ssl_pair {|s1, s2|
+ s2.close
+ assert_equal("", s1.read)
+ }
+ end
+
+ def test_readline
+ ssl_pair {|s1, s2|
+ s2.close
+ assert_raise(EOFError) { s1.readline }
+ }
+ end
+
+ def test_puts_meta
+ ssl_pair {|s1, s2|
+ begin
+ old = $/
+ $/ = '*'
+ s1.puts 'a'
+ ensure
+ $/ = old
+ end
+ s1.close
+ assert_equal("a\n", s2.read)
+ }
+ end
+
+ def test_puts_empty
+ ssl_pair {|s1, s2|
+ s1.puts
+ s1.close
+ assert_equal("\n", s2.read)
+ }
+ end
+
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_pkcs7.rb b/ruby_1_8_6/test/openssl/test_pkcs7.rb
new file mode 100644
index 0000000000..9b472c1795
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_pkcs7.rb
@@ -0,0 +1,154 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestPKCS7 < Test::Unit::TestCase
+ def setup
+ @rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ @rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
+ ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
+ ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
+
+ now = Time.now
+ ca_exts = [
+ ["basicConstraints","CA:TRUE",true],
+ ["keyUsage","keyCertSign, cRLSign",true],
+ ["subjectKeyIdentifier","hash",false],
+ ["authorityKeyIdentifier","keyid:always",false],
+ ]
+ @ca_cert = issue_cert(ca, @rsa2048, 1, Time.now, Time.now+3600, ca_exts,
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ ee_exts = [
+ ["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
+ ["authorityKeyIdentifier","keyid:always",false],
+ ["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
+ ]
+ @ee1_cert = issue_cert(ee1, @rsa1024, 2, Time.now, Time.now+1800, ee_exts,
+ @ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ @ee2_cert = issue_cert(ee2, @rsa1024, 3, Time.now, Time.now+1800, ee_exts,
+ @ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ end
+
+ def issue_cert(*args)
+ OpenSSL::TestUtils.issue_cert(*args)
+ end
+
+ def test_signed
+ store = OpenSSL::X509::Store.new
+ store.add_cert(@ca_cert)
+ ca_certs = [@ca_cert]
+
+ data = "aaaaa\r\nbbbbb\r\nccccc\r\n"
+ tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs)
+ p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
+ certs = p7.certificates
+ signers = p7.signers
+ assert(p7.verify([], store))
+ assert_equal(data, p7.data)
+ assert_equal(2, certs.size)
+ assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
+ assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
+ assert_equal(1, signers.size)
+ assert_equal(@ee1_cert.serial, signers[0].serial)
+ assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
+
+ # Normaly OpenSSL tries to translate the supplied content into canonical
+ # MIME format (e.g. a newline character is converted into CR+LF).
+ # If the content is a binary, PKCS7::BINARY flag should be used.
+
+ data = "aaaaa\nbbbbb\nccccc\n"
+ flag = OpenSSL::PKCS7::BINARY
+ tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
+ p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
+ certs = p7.certificates
+ signers = p7.signers
+ assert(p7.verify([], store))
+ assert_equal(data, p7.data)
+ assert_equal(2, certs.size)
+ assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
+ assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
+ assert_equal(1, signers.size)
+ assert_equal(@ee1_cert.serial, signers[0].serial)
+ assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
+
+ # A signed-data which have multiple signatures can be created
+ # through the following steps.
+ # 1. create two signed-data
+ # 2. copy signerInfo and certificate from one to another
+
+ tmp1 = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, [], flag)
+ tmp2 = OpenSSL::PKCS7.sign(@ee2_cert, @rsa1024, data, [], flag)
+ tmp1.add_signer(tmp2.signers[0])
+ tmp1.add_certificate(@ee2_cert)
+
+ p7 = OpenSSL::PKCS7::PKCS7.new(tmp1.to_der)
+ certs = p7.certificates
+ signers = p7.signers
+ assert(p7.verify([], store))
+ assert_equal(data, p7.data)
+ assert_equal(2, certs.size)
+ assert_equal(2, signers.size)
+ assert_equal(@ee1_cert.serial, signers[0].serial)
+ assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
+ assert_equal(@ee2_cert.serial, signers[1].serial)
+ assert_equal(@ee2_cert.issuer.to_s, signers[1].issuer.to_s)
+ end
+
+ def test_detached_sign
+ store = OpenSSL::X509::Store.new
+ store.add_cert(@ca_cert)
+ ca_certs = [@ca_cert]
+
+ data = "aaaaa\nbbbbb\nccccc\n"
+ flag = OpenSSL::PKCS7::BINARY|OpenSSL::PKCS7::DETACHED
+ tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
+ p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
+ a1 = OpenSSL::ASN1.decode(p7)
+
+ certs = p7.certificates
+ signers = p7.signers
+ assert(!p7.verify([], store))
+ assert(p7.verify([], store, data))
+ assert_equal(data, p7.data)
+ assert_equal(2, certs.size)
+ assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
+ assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
+ assert_equal(1, signers.size)
+ assert_equal(@ee1_cert.serial, signers[0].serial)
+ assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
+ end
+
+ def test_enveloped
+ if OpenSSL::OPENSSL_VERSION_NUMBER <= 0x0090704f
+ # PKCS7_encrypt() of OpenSSL-0.9.7d goes to SEGV.
+ # http://www.mail-archive.com/openssl-dev@openssl.org/msg17376.html
+ return
+ end
+
+ certs = [@ee1_cert, @ee2_cert]
+ cipher = OpenSSL::Cipher::AES.new("128-CBC")
+ data = "aaaaa\nbbbbb\nccccc\n"
+
+ tmp = OpenSSL::PKCS7.encrypt(certs, data, cipher, OpenSSL::PKCS7::BINARY)
+ p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
+ recip = p7.recipients
+ assert_equal(:enveloped, p7.type)
+ assert_equal(2, recip.size)
+
+ assert_equal(@ca_cert.subject.to_s, recip[0].issuer.to_s)
+ assert_equal(2, recip[0].serial)
+ assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
+
+ assert_equal(@ca_cert.subject.to_s, recip[1].issuer.to_s)
+ assert_equal(3, recip[1].serial)
+ assert_equal(data, p7.decrypt(@rsa1024, @ee2_cert))
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_pkey_rsa.rb b/ruby_1_8_6/test/openssl/test_pkey_rsa.rb
new file mode 100644
index 0000000000..401cb6c3e0
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_pkey_rsa.rb
@@ -0,0 +1,49 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require 'test/unit'
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestPKeyRSA < Test::Unit::TestCase
+ def test_padding
+ key = OpenSSL::PKey::RSA.new(512, 3)
+
+ # Need right size for raw mode
+ plain0 = "x" * (512/8)
+ cipher = key.private_encrypt(plain0, OpenSSL::PKey::RSA::NO_PADDING)
+ plain1 = key.public_decrypt(cipher, OpenSSL::PKey::RSA::NO_PADDING)
+ assert_equal(plain0, plain1)
+
+ # Need smaller size for pkcs1 mode
+ plain0 = "x" * (512/8 - 11)
+ cipher1 = key.private_encrypt(plain0, OpenSSL::PKey::RSA::PKCS1_PADDING)
+ plain1 = key.public_decrypt(cipher1, OpenSSL::PKey::RSA::PKCS1_PADDING)
+ assert_equal(plain0, plain1)
+
+ cipherdef = key.private_encrypt(plain0) # PKCS1_PADDING is default
+ plain1 = key.public_decrypt(cipherdef)
+ assert_equal(plain0, plain1)
+ assert_equal(cipher1, cipherdef)
+
+ # Failure cases
+ assert_raise(ArgumentError){ key.private_encrypt() }
+ assert_raise(ArgumentError){ key.private_encrypt("hi", 1, nil) }
+ assert_raise(OpenSSL::PKey::RSAError){ key.private_encrypt(plain0, 666) }
+ end
+
+ def test_private
+ key = OpenSSL::PKey::RSA.new(512, 3)
+ assert(key.private?)
+ key2 = OpenSSL::PKey::RSA.new(key.to_der)
+ assert(key2.private?)
+ key3 = key.public_key
+ assert(!key3.private?)
+ key4 = OpenSSL::PKey::RSA.new(key3.to_der)
+ assert(!key4.private?)
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_ssl.rb b/ruby_1_8_6/test/openssl/test_ssl.rb
new file mode 100644
index 0000000000..ec1bf6b8c8
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_ssl.rb
@@ -0,0 +1,286 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "rbconfig"
+require "socket"
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestSSL < Test::Unit::TestCase
+ RUBY = ENV["RUBY"] || File.join(
+ ::Config::CONFIG["bindir"],
+ ::Config::CONFIG["ruby_install_name"] + ::Config::CONFIG["EXEEXT"]
+ )
+ SSL_SERVER = File.join(File.dirname(__FILE__), "ssl_server.rb")
+ PORT = 20443
+ ITERATIONS = ($0 == __FILE__) ? 100 : 10
+
+ def setup
+ @ca_key = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ @svr_key = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ @cli_key = OpenSSL::TestUtils::TEST_KEY_DSA256
+ @ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
+ @svr = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=localhost")
+ @cli = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=localhost")
+
+ now = Time.at(Time.now.to_i)
+ ca_exts = [
+ ["basicConstraints","CA:TRUE",true],
+ ["keyUsage","cRLSign,keyCertSign",true],
+ ]
+ ee_exts = [
+ ["keyUsage","keyEncipherment,digitalSignature",true],
+ ]
+ @ca_cert = issue_cert(@ca, @ca_key, 1, now, now+3600, ca_exts,
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ @svr_cert = issue_cert(@svr, @svr_key, 2, now, now+1800, ee_exts,
+ @ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
+ @cli_cert = issue_cert(@cli, @cli_key, 3, now, now+1800, ee_exts,
+ @ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
+ @server = nil
+ end
+
+ def teardown
+ end
+
+ def issue_cert(*arg)
+ OpenSSL::TestUtils.issue_cert(*arg)
+ end
+
+ def issue_crl(*arg)
+ OpenSSL::TestUtils.issue_crl(*arg)
+ end
+
+ def start_server(port0, verify_mode, start_immediately, &block)
+ server = nil
+ begin
+ cmd = [RUBY]
+ cmd << "-d" if $DEBUG
+ cmd << SSL_SERVER << port0.to_s << verify_mode.to_s
+ cmd << (start_immediately ? "yes" : "no")
+ server = IO.popen(cmd.join(" "), "w+")
+ server.write(@ca_cert.to_pem)
+ server.write(@svr_cert.to_pem)
+ server.write(@svr_key.to_pem)
+ pid = Integer(server.gets)
+ if port = server.gets
+ if $DEBUG
+ $stderr.printf("%s started: pid=%d port=%d\n", SSL_SERVER, pid, port)
+ end
+ block.call(server, port.to_i)
+ end
+ ensure
+ if server
+ Process.kill(:KILL, pid)
+ server.close
+ end
+ end
+ end
+
+ def starttls(ssl)
+ ssl.puts("STARTTLS")
+
+ sleep 1 # When this line is eliminated, process on Cygwin blocks
+ # forever at ssl.connect. But I don't know why it does.
+
+ ssl.connect
+ end
+
+ def test_connect_and_close
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ assert(ssl.connect)
+ ssl.close
+ assert(!sock.closed?)
+ sock.close
+
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.sync_close = true # !!
+ assert(ssl.connect)
+ ssl.close
+ assert(sock.closed?)
+ }
+ end
+
+ def test_read_and_write
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.sync_close = true
+ ssl.connect
+
+ # syswrite and sysread
+ ITERATIONS.times{|i|
+ str = "x" * 100 + "\n"
+ ssl.syswrite(str)
+ assert_equal(str, ssl.sysread(str.size))
+
+ str = "x" * i * 100 + "\n"
+ buf = ""
+ ssl.syswrite(str)
+ assert_equal(buf.object_id, ssl.sysread(str.size, buf).object_id)
+ assert_equal(str, buf)
+ }
+
+ # puts and gets
+ ITERATIONS.times{
+ str = "x" * 100 + "\n"
+ ssl.puts(str)
+ assert_equal(str, ssl.gets)
+ }
+
+ # read and write
+ ITERATIONS.times{|i|
+ str = "x" * 100 + "\n"
+ ssl.write(str)
+ assert_equal(str, ssl.read(str.size))
+
+ str = "x" * i * 100 + "\n"
+ buf = ""
+ ssl.write(str)
+ assert_equal(buf.object_id, ssl.read(str.size, buf).object_id)
+ assert_equal(str, buf)
+ }
+
+ ssl.close
+ }
+ end
+
+ def test_client_auth
+ vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
+ start_server(PORT, vflag, true){|s, p|
+ assert_raises(OpenSSL::SSL::SSLError){
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.connect
+ }
+
+ ctx = OpenSSL::SSL::SSLContext.new
+ ctx.key = @cli_key
+ ctx.cert = @cli_cert
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
+ ssl.sync_close = true
+ ssl.connect
+ ssl.puts("foo")
+ assert_equal("foo\n", ssl.gets)
+ ssl.close
+
+ called = nil
+ ctx = OpenSSL::SSL::SSLContext.new
+ ctx.client_cert_cb = Proc.new{|ssl|
+ called = true
+ [@cli_cert, @cli_key]
+ }
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
+ ssl.sync_close = true
+ ssl.connect
+ assert(called)
+ ssl.puts("foo")
+ assert_equal("foo\n", ssl.gets)
+ ssl.close
+ }
+ end
+
+ def test_starttls
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, false){|s, p|
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.sync_close = true
+ str = "x" * 1000 + "\n"
+
+ ITERATIONS.times{
+ ssl.puts(str)
+ assert_equal(str, ssl.gets)
+ }
+
+ starttls(ssl)
+
+ ITERATIONS.times{
+ ssl.puts(str)
+ assert_equal(str, ssl.gets)
+ }
+
+ ssl.close
+ }
+ end
+
+ def test_parallel
+ GC.start
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ ssls = []
+ 10.times{
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.connect
+ ssl.sync_close = true
+ ssls << ssl
+ }
+ str = "x" * 1000 + "\n"
+ ITERATIONS.times{
+ ssls.each{|ssl|
+ ssl.puts(str)
+ assert_equal(str, ssl.gets)
+ }
+ }
+ ssls.each{|ssl| ssl.close }
+ }
+ end
+
+ def test_post_connection_check
+ sslerr = OpenSSL::SSL::SSLError
+
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.connect
+ assert_raises(sslerr){ssl.post_connection_check("localhost.localdomain")}
+ assert_raises(sslerr){ssl.post_connection_check("127.0.0.1")}
+ assert(ssl.post_connection_check("localhost"))
+ assert_raises(sslerr){ssl.post_connection_check("foo.example.com")}
+ }
+
+ now = Time.now
+ exts = [
+ ["keyUsage","keyEncipherment,digitalSignature",true],
+ ["subjectAltName","DNS:localhost.localdomain",false],
+ ["subjectAltName","IP:127.0.0.1",false],
+ ]
+ @svr_cert = issue_cert(@svr, @svr_key, 4, now, now+1800, exts,
+ @ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.connect
+ assert(ssl.post_connection_check("localhost.localdomain"))
+ assert(ssl.post_connection_check("127.0.0.1"))
+ assert_raises(sslerr){ssl.post_connection_check("localhost")}
+ assert_raises(sslerr){ssl.post_connection_check("foo.example.com")}
+ }
+
+ now = Time.now
+ exts = [
+ ["keyUsage","keyEncipherment,digitalSignature",true],
+ ["subjectAltName","DNS:*.localdomain",false],
+ ]
+ @svr_cert = issue_cert(@svr, @svr_key, 5, now, now+1800, exts,
+ @ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ sock = TCPSocket.new("127.0.0.1", p)
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
+ ssl.connect
+ assert(ssl.post_connection_check("localhost.localdomain"))
+ assert_raises(sslerr){ssl.post_connection_check("127.0.0.1")}
+ assert_raises(sslerr){ssl.post_connection_check("localhost")}
+ assert_raises(sslerr){ssl.post_connection_check("foo.example.com")}
+ }
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_x509cert.rb b/ruby_1_8_6/test/openssl/test_x509cert.rb
new file mode 100644
index 0000000000..a5a75ff1b6
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_x509cert.rb
@@ -0,0 +1,175 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestX509Certificate < Test::Unit::TestCase
+ def setup
+ @rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ @rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ @dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
+ @dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
+ @ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
+ @ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
+ @ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
+ end
+
+ def teardown
+ end
+
+ def issue_cert(*args)
+ OpenSSL::TestUtils.issue_cert(*args)
+ end
+
+ def test_serial
+ [1, 2**32, 2**100].each{|s|
+ cert = issue_cert(@ca, @rsa2048, s, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ assert_equal(s, cert.serial)
+ cert = OpenSSL::X509::Certificate.new(cert.to_der)
+ assert_equal(s, cert.serial)
+ }
+ end
+
+ def test_public_key
+ exts = [
+ ["basicConstraints","CA:TRUE",true],
+ ["subjectKeyIdentifier","hash",false],
+ ["authorityKeyIdentifier","keyid:always",false],
+ ]
+
+ sha1 = OpenSSL::Digest::SHA1.new
+ dss1 = OpenSSL::Digest::DSS1.new
+ [
+ [@rsa1024, sha1], [@rsa2048, sha1], [@dsa256, dss1], [@dsa512, dss1],
+ ].each{|pk, digest|
+ cert = issue_cert(@ca, pk, 1, Time.now, Time.now+3600, exts,
+ nil, nil, digest)
+ assert_equal(cert.extensions[1].value,
+ OpenSSL::TestUtils.get_subject_key_id(cert))
+ cert = OpenSSL::X509::Certificate.new(cert.to_der)
+ assert_equal(cert.extensions[1].value,
+ OpenSSL::TestUtils.get_subject_key_id(cert))
+ }
+ end
+
+ def test_validity
+ now = Time.now until now && now.usec != 0
+ cert = issue_cert(@ca, @rsa2048, 1, now, now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ assert_not_equal(now, cert.not_before)
+ assert_not_equal(now+3600, cert.not_after)
+
+ now = Time.at(now.to_i)
+ cert = issue_cert(@ca, @rsa2048, 1, now, now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ assert_equal(now.getutc, cert.not_before)
+ assert_equal((now+3600).getutc, cert.not_after)
+
+ now = Time.at(0)
+ cert = issue_cert(@ca, @rsa2048, 1, now, now, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ assert_equal(now.getutc, cert.not_before)
+ assert_equal(now.getutc, cert.not_after)
+
+ now = Time.at(0x7fffffff)
+ cert = issue_cert(@ca, @rsa2048, 1, now, now, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ assert_equal(now.getutc, cert.not_before)
+ assert_equal(now.getutc, cert.not_after)
+ end
+
+ def test_extension
+ ca_exts = [
+ ["basicConstraints","CA:TRUE",true],
+ ["keyUsage","keyCertSign, cRLSign",true],
+ ["subjectKeyIdentifier","hash",false],
+ ["authorityKeyIdentifier","keyid:always",false],
+ ]
+ ca_cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, ca_exts,
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ ca_cert.extensions.each_with_index{|ext, i|
+ assert_equal(ca_exts[i].first, ext.oid)
+ assert_equal(ca_exts[i].last, ext.critical?)
+ }
+
+ ee1_exts = [
+ ["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
+ ["subjectKeyIdentifier","hash",false],
+ ["authorityKeyIdentifier","keyid:always",false],
+ ["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
+ ["subjectAltName","email:ee1@ruby-lang.org",false],
+ ]
+ ee1_cert = issue_cert(@ee1, @rsa1024, 2, Time.now, Time.now+1800, ee1_exts,
+ ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ assert_equal(ca_cert.subject.to_der, ee1_cert.issuer.to_der)
+ ee1_cert.extensions.each_with_index{|ext, i|
+ assert_equal(ee1_exts[i].first, ext.oid)
+ assert_equal(ee1_exts[i].last, ext.critical?)
+ }
+
+ ee2_exts = [
+ ["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
+ ["subjectKeyIdentifier","hash",false],
+ ["authorityKeyIdentifier","issuer:always",false],
+ ["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
+ ["subjectAltName","email:ee2@ruby-lang.org",false],
+ ]
+ ee2_cert = issue_cert(@ee2, @rsa1024, 3, Time.now, Time.now+1800, ee2_exts,
+ ca_cert, @rsa2048, OpenSSL::Digest::MD5.new)
+ assert_equal(ca_cert.subject.to_der, ee2_cert.issuer.to_der)
+ ee2_cert.extensions.each_with_index{|ext, i|
+ assert_equal(ee2_exts[i].first, ext.oid)
+ assert_equal(ee2_exts[i].last, ext.critical?)
+ }
+
+ end
+
+ def test_sign_and_verify
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ assert_equal(false, cert.verify(@rsa1024))
+ assert_equal(true, cert.verify(@rsa2048))
+ assert_equal(false, cert.verify(@dsa256))
+ assert_equal(false, cert.verify(@dsa512))
+ cert.serial = 2
+ assert_equal(false, cert.verify(@rsa2048))
+
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::MD5.new)
+ assert_equal(false, cert.verify(@rsa1024))
+ assert_equal(true, cert.verify(@rsa2048))
+ assert_equal(false, cert.verify(@dsa256))
+ assert_equal(false, cert.verify(@dsa512))
+ cert.subject = @ee1
+ assert_equal(false, cert.verify(@rsa2048))
+
+ cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::DSS1.new)
+ assert_equal(false, cert.verify(@rsa1024))
+ assert_equal(false, cert.verify(@rsa2048))
+ assert_equal(false, cert.verify(@dsa256))
+ assert_equal(true, cert.verify(@dsa512))
+ cert.not_after = Time.now
+ assert_equal(false, cert.verify(@dsa512))
+
+ assert_raises(OpenSSL::X509::CertificateError){
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::DSS1.new)
+ }
+ assert_raises(OpenSSL::X509::CertificateError){
+ cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::MD5.new)
+ }
+ assert_raises(OpenSSL::X509::CertificateError){
+ cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ }
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_x509crl.rb b/ruby_1_8_6/test/openssl/test_x509crl.rb
new file mode 100644
index 0000000000..444a00a586
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_x509crl.rb
@@ -0,0 +1,218 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestX509CRL < Test::Unit::TestCase
+ def setup
+ @rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ @rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ @dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
+ @dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
+ @ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
+ @ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
+ @ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
+ end
+
+ def teardown
+ end
+
+ def issue_crl(*args)
+ OpenSSL::TestUtils.issue_crl(*args)
+ end
+
+ def issue_cert(*args)
+ OpenSSL::TestUtils.issue_cert(*args)
+ end
+
+ def test_basic
+ now = Time.at(Time.now.to_i)
+
+ cert = issue_cert(@ca, @rsa2048, 1, now, now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ crl = issue_crl([], 1, now, now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ assert_equal(1, crl.version)
+ assert_equal(cert.issuer.to_der, crl.issuer.to_der)
+ assert_equal(now, crl.last_update)
+ assert_equal(now+1600, crl.next_update)
+
+ crl = OpenSSL::X509::CRL.new(crl.to_der)
+ assert_equal(1, crl.version)
+ assert_equal(cert.issuer.to_der, crl.issuer.to_der)
+ assert_equal(now, crl.last_update)
+ assert_equal(now+1600, crl.next_update)
+ end
+
+ def test_revoked
+
+ # CRLReason ::= ENUMERATED {
+ # unspecified (0),
+ # keyCompromise (1),
+ # cACompromise (2),
+ # affiliationChanged (3),
+ # superseded (4),
+ # cessationOfOperation (5),
+ # certificateHold (6),
+ # removeFromCRL (8),
+ # privilegeWithdrawn (9),
+ # aACompromise (10) }
+
+ now = Time.at(Time.now.to_i)
+ revoke_info = [
+ [1, Time.at(0), 1],
+ [2, Time.at(0x7fffffff), 2],
+ [3, now, 3],
+ [4, now, 4],
+ [5, now, 5],
+ ]
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ crl = issue_crl(revoke_info, 1, Time.now, Time.now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ revoked = crl.revoked
+ assert_equal(5, revoked.size)
+ assert_equal(1, revoked[0].serial)
+ assert_equal(2, revoked[1].serial)
+ assert_equal(3, revoked[2].serial)
+ assert_equal(4, revoked[3].serial)
+ assert_equal(5, revoked[4].serial)
+
+ assert_equal(Time.at(0), revoked[0].time)
+ assert_equal(Time.at(0x7fffffff), revoked[1].time)
+ assert_equal(now, revoked[2].time)
+ assert_equal(now, revoked[3].time)
+ assert_equal(now, revoked[4].time)
+
+ assert_equal("CRLReason", revoked[0].extensions[0].oid)
+ assert_equal("CRLReason", revoked[1].extensions[0].oid)
+ assert_equal("CRLReason", revoked[2].extensions[0].oid)
+ assert_equal("CRLReason", revoked[3].extensions[0].oid)
+ assert_equal("CRLReason", revoked[4].extensions[0].oid)
+
+ assert_equal("Key Compromise", revoked[0].extensions[0].value)
+ assert_equal("CA Compromise", revoked[1].extensions[0].value)
+ assert_equal("Affiliation Changed", revoked[2].extensions[0].value)
+ assert_equal("Superseded", revoked[3].extensions[0].value)
+ assert_equal("Cessation Of Operation", revoked[4].extensions[0].value)
+
+ assert_equal(false, revoked[0].extensions[0].critical?)
+ assert_equal(false, revoked[1].extensions[0].critical?)
+ assert_equal(false, revoked[2].extensions[0].critical?)
+ assert_equal(false, revoked[3].extensions[0].critical?)
+ assert_equal(false, revoked[4].extensions[0].critical?)
+
+ crl = OpenSSL::X509::CRL.new(crl.to_der)
+ assert_equal("Key Compromise", revoked[0].extensions[0].value)
+ assert_equal("CA Compromise", revoked[1].extensions[0].value)
+ assert_equal("Affiliation Changed", revoked[2].extensions[0].value)
+ assert_equal("Superseded", revoked[3].extensions[0].value)
+ assert_equal("Cessation Of Operation", revoked[4].extensions[0].value)
+
+ revoke_info = (1..1000).collect{|i| [i, now, 0] }
+ crl = issue_crl(revoke_info, 1, Time.now, Time.now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ revoked = crl.revoked
+ assert_equal(1000, revoked.size)
+ assert_equal(1, revoked[0].serial)
+ assert_equal(1000, revoked[999].serial)
+ end
+
+ def test_extension
+ cert_exts = [
+ ["basicConstraints", "CA:TRUE", true],
+ ["subjectKeyIdentifier", "hash", false],
+ ["authorityKeyIdentifier", "keyid:always", false],
+ ["subjectAltName", "email:xyzzy@ruby-lang.org", false],
+ ["keyUsage", "cRLSign, keyCertSign", true],
+ ]
+ crl_exts = [
+ ["authorityKeyIdentifier", "keyid:always", false],
+ ["issuerAltName", "issuer:copy", false],
+ ]
+
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, cert_exts,
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ crl = issue_crl([], 1, Time.now, Time.now+1600, crl_exts,
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ exts = crl.extensions
+ assert_equal(3, exts.size)
+ assert_equal("1", exts[0].value)
+ assert_equal("crlNumber", exts[0].oid)
+ assert_equal(false, exts[0].critical?)
+
+ assert_equal("authorityKeyIdentifier", exts[1].oid)
+ keyid = OpenSSL::TestUtils.get_subject_key_id(cert)
+ assert_match(/^keyid:#{keyid}/, exts[1].value)
+ assert_equal(false, exts[1].critical?)
+
+ assert_equal("issuerAltName", exts[2].oid)
+ assert_equal("email:xyzzy@ruby-lang.org", exts[2].value)
+ assert_equal(false, exts[2].critical?)
+
+ crl = OpenSSL::X509::CRL.new(crl.to_der)
+ exts = crl.extensions
+ assert_equal(3, exts.size)
+ assert_equal("1", exts[0].value)
+ assert_equal("crlNumber", exts[0].oid)
+ assert_equal(false, exts[0].critical?)
+
+ assert_equal("authorityKeyIdentifier", exts[1].oid)
+ keyid = OpenSSL::TestUtils.get_subject_key_id(cert)
+ assert_match(/^keyid:#{keyid}/, exts[1].value)
+ assert_equal(false, exts[1].critical?)
+
+ assert_equal("issuerAltName", exts[2].oid)
+ assert_equal("email:xyzzy@ruby-lang.org", exts[2].value)
+ assert_equal(false, exts[2].critical?)
+ end
+
+ def test_crlnumber
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ crl = issue_crl([], 1, Time.now, Time.now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ assert_match(1.to_s, crl.extensions[0].value)
+ assert_match(/X509v3 CRL Number:\s+#{1}/m, crl.to_text)
+
+ crl = issue_crl([], 2**32, Time.now, Time.now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ assert_match((2**32).to_s, crl.extensions[0].value)
+ assert_match(/X509v3 CRL Number:\s+#{2**32}/m, crl.to_text)
+
+ crl = issue_crl([], 2**100, Time.now, Time.now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ assert_match(/X509v3 CRL Number:\s+#{2**100}/m, crl.to_text)
+ assert_match((2**100).to_s, crl.extensions[0].value)
+ end
+
+ def test_sign_and_verify
+ cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ crl = issue_crl([], 1, Time.now, Time.now+1600, [],
+ cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ assert_equal(false, crl.verify(@rsa1024))
+ assert_equal(true, crl.verify(@rsa2048))
+ assert_equal(false, crl.verify(@dsa256))
+ assert_equal(false, crl.verify(@dsa512))
+ crl.version = 0
+ assert_equal(false, crl.verify(@rsa2048))
+
+ cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
+ nil, nil, OpenSSL::Digest::DSS1.new)
+ crl = issue_crl([], 1, Time.now, Time.now+1600, [],
+ cert, @dsa512, OpenSSL::Digest::DSS1.new)
+ assert_equal(false, crl.verify(@rsa1024))
+ assert_equal(false, crl.verify(@rsa2048))
+ assert_equal(false, crl.verify(@dsa256))
+ assert_equal(true, crl.verify(@dsa512))
+ crl.version = 0
+ assert_equal(false, crl.verify(@dsa512))
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_x509ext.rb b/ruby_1_8_6/test/openssl/test_x509ext.rb
new file mode 100644
index 0000000000..d43bbd6bd3
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_x509ext.rb
@@ -0,0 +1,74 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestX509Extension < Test::Unit::TestCase
+ def setup
+ @basic_constraints_value = OpenSSL::ASN1::Sequence([
+ OpenSSL::ASN1::Boolean(true), # CA
+ OpenSSL::ASN1::Integer(2) # pathlen
+ ])
+ @basic_constraints = OpenSSL::ASN1::Sequence([
+ OpenSSL::ASN1::ObjectId("basicConstraints"),
+ OpenSSL::ASN1::Boolean(true),
+ OpenSSL::ASN1::OctetString(@basic_constraints_value.to_der),
+ ])
+ end
+
+ def teardown
+ end
+
+ def test_new
+ ext = OpenSSL::X509::Extension.new(@basic_constraints.to_der)
+ assert_equal("basicConstraints", ext.oid)
+ assert_equal(true, ext.critical?)
+ assert_equal("CA:TRUE, pathlen:2", ext.value)
+
+ ext = OpenSSL::X509::Extension.new("2.5.29.19",
+ @basic_constraints_value.to_der, true)
+ assert_equal(@basic_constraints.to_der, ext.to_der)
+ end
+
+ def test_create_by_factory
+ ef = OpenSSL::X509::ExtensionFactory.new
+
+ bc = ef.create_extension("basicConstraints", "critical, CA:TRUE, pathlen:2")
+ assert_equal(@basic_constraints.to_der, bc.to_der)
+
+ bc = ef.create_extension("basicConstraints", "CA:TRUE, pathlen:2", true)
+ assert_equal(@basic_constraints.to_der, bc.to_der)
+
+ begin
+ ef.config = OpenSSL::Config.parse(<<-_end_of_cnf_)
+ [crlDistPts]
+ URI.1 = http://www.example.com/crl
+ URI.2 = ldap://ldap.example.com/cn=ca?certificateRevocationList;binary
+ _end_of_cnf_
+ rescue NotImplementedError
+ return
+ end
+
+ cdp = ef.create_extension("crlDistributionPoints", "@crlDistPts")
+ assert_equal(false, cdp.critical?)
+ assert_equal("crlDistributionPoints", cdp.oid)
+ assert_match(%{URI:http://www\.example\.com/crl}, cdp.value)
+ assert_match(
+ %r{URI:ldap://ldap\.example\.com/cn=ca\?certificateRevocationList;binary},
+ cdp.value)
+
+ cdp = ef.create_extension("crlDistributionPoints", "critical, @crlDistPts")
+ assert_equal(true, cdp.critical?)
+ assert_equal("crlDistributionPoints", cdp.oid)
+ assert_match(%{URI:http://www.example.com/crl}, cdp.value)
+ assert_match(
+ %r{URI:ldap://ldap.example.com/cn=ca\?certificateRevocationList;binary},
+ cdp.value)
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_x509name.rb b/ruby_1_8_6/test/openssl/test_x509name.rb
new file mode 100644
index 0000000000..fb5a1ae4ff
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_x509name.rb
@@ -0,0 +1,266 @@
+begin
+ require "openssl"
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestX509Name < Test::Unit::TestCase
+ OpenSSL::ASN1::ObjectId.register(
+ "1.2.840.113549.1.9.1", "emailAddress", "emailAddress")
+ OpenSSL::ASN1::ObjectId.register(
+ "2.5.4.5", "serialNumber", "serialNumber")
+
+ def setup
+ @obj_type_tmpl = Hash.new(OpenSSL::ASN1::PRINTABLESTRING)
+ @obj_type_tmpl.update(OpenSSL::X509::Name::OBJECT_TYPE_TEMPLATE)
+ end
+
+ def teardown
+ end
+
+ def test_s_new
+ dn = [ ["C", "JP"], ["O", "example"], ["CN", "www.example.jp"] ]
+ name = OpenSSL::X509::Name.new(dn)
+ ary = name.to_a
+ assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
+ assert_equal("C", ary[0][0])
+ assert_equal("O", ary[1][0])
+ assert_equal("CN", ary[2][0])
+ assert_equal("JP", ary[0][1])
+ assert_equal("example", ary[1][1])
+ assert_equal("www.example.jp", ary[2][1])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
+
+ dn = [
+ ["countryName", "JP"],
+ ["organizationName", "example"],
+ ["commonName", "www.example.jp"]
+ ]
+ name = OpenSSL::X509::Name.new(dn)
+ ary = name.to_a
+ assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
+ assert_equal("C", ary[0][0])
+ assert_equal("O", ary[1][0])
+ assert_equal("CN", ary[2][0])
+ assert_equal("JP", ary[0][1])
+ assert_equal("example", ary[1][1])
+ assert_equal("www.example.jp", ary[2][1])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
+
+ name = OpenSSL::X509::Name.new(dn, @obj_type_tmpl)
+ ary = name.to_a
+ assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
+
+ dn = [
+ ["countryName", "JP", OpenSSL::ASN1::PRINTABLESTRING],
+ ["organizationName", "example", OpenSSL::ASN1::PRINTABLESTRING],
+ ["commonName", "www.example.jp", OpenSSL::ASN1::PRINTABLESTRING]
+ ]
+ name = OpenSSL::X509::Name.new(dn)
+ ary = name.to_a
+ assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
+
+ dn = [
+ ["DC", "org"],
+ ["DC", "ruby-lang"],
+ ["CN", "GOTOU Yuuzou"],
+ ["emailAddress", "gotoyuzo@ruby-lang.org"],
+ ["serialNumber", "123"],
+ ]
+ name = OpenSSL::X509::Name.new(dn)
+ ary = name.to_a
+ assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
+ assert_equal("DC", ary[0][0])
+ assert_equal("DC", ary[1][0])
+ assert_equal("CN", ary[2][0])
+ assert_equal("emailAddress", ary[3][0])
+ assert_equal("serialNumber", ary[4][0])
+ assert_equal("org", ary[0][1])
+ assert_equal("ruby-lang", ary[1][1])
+ assert_equal("GOTOU Yuuzou", ary[2][1])
+ assert_equal("gotoyuzo@ruby-lang.org", ary[3][1])
+ assert_equal("123", ary[4][1])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[3][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[4][2])
+
+ name_from_der = OpenSSL::X509::Name.new(name.to_der)
+ assert_equal(name_from_der.to_s, name.to_s)
+ assert_equal(name_from_der.to_a, name.to_a)
+ assert_equal(name_from_der.to_der, name.to_der)
+ end
+
+ def test_s_parse
+ dn = "/DC=org/DC=ruby-lang/CN=www.ruby-lang.org"
+ name = OpenSSL::X509::Name.parse(dn)
+ assert_equal(dn, name.to_s)
+ ary = name.to_a
+ assert_equal("DC", ary[0][0])
+ assert_equal("DC", ary[1][0])
+ assert_equal("CN", ary[2][0])
+ assert_equal("org", ary[0][1])
+ assert_equal("ruby-lang", ary[1][1])
+ assert_equal("www.ruby-lang.org", ary[2][1])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
+
+ dn2 = "DC=org, DC=ruby-lang, CN=www.ruby-lang.org"
+ name = OpenSSL::X509::Name.parse(dn)
+ ary = name.to_a
+ assert_equal(dn, name.to_s)
+ assert_equal("org", ary[0][1])
+ assert_equal("ruby-lang", ary[1][1])
+ assert_equal("www.ruby-lang.org", ary[2][1])
+
+ name = OpenSSL::X509::Name.parse(dn, @obj_type_tmpl)
+ ary = name.to_a
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
+ end
+
+ def test_s_parse_rfc2253
+ scanner = OpenSSL::X509::Name::RFC2253DN.method(:scan)
+
+ assert_equal([["C", "JP"]], scanner.call("C=JP"))
+ assert_equal([
+ ["DC", "org"],
+ ["DC", "ruby-lang"],
+ ["CN", "GOTOU Yuuzou"],
+ ["emailAddress", "gotoyuzo@ruby-lang.org"],
+ ],
+ scanner.call(
+ "emailAddress=gotoyuzo@ruby-lang.org,CN=GOTOU Yuuzou,"+
+ "DC=ruby-lang,DC=org")
+ )
+
+ u8 = OpenSSL::ASN1::UTF8STRING
+ assert_equal([
+ ["DC", "org"],
+ ["DC", "ruby-lang"],
+ ["O", ",=+<>#;"],
+ ["O", ",=+<>#;"],
+ ["OU", ""],
+ ["OU", ""],
+ ["L", "aaa=\"bbb, ccc\""],
+ ["L", "aaa=\"bbb, ccc\""],
+ ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
+ ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
+ ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
+ ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265", u8],
+ ["2.5.4.3", "GOTOU, Yuuzou"],
+ ["2.5.4.3", "GOTOU, Yuuzou"],
+ ["2.5.4.3", "GOTOU, Yuuzou"],
+ ["2.5.4.3", "GOTOU, Yuuzou"],
+ ["CN", "GOTOU \"gotoyuzo\" Yuuzou"],
+ ["CN", "GOTOU \"gotoyuzo\" Yuuzou"],
+ ["1.2.840.113549.1.9.1", "gotoyuzo@ruby-lang.org"],
+ ["emailAddress", "gotoyuzo@ruby-lang.org"],
+ ],
+ scanner.call(
+ "emailAddress=gotoyuzo@ruby-lang.org," +
+ "1.2.840.113549.1.9.1=gotoyuzo@ruby-lang.org," +
+ 'CN=GOTOU \"gotoyuzo\" Yuuzou,' +
+ 'CN="GOTOU \"gotoyuzo\" Yuuzou",' +
+ '2.5.4.3=GOTOU\,\20Yuuzou,' +
+ '2.5.4.3=GOTOU\, Yuuzou,' +
+ '2.5.4.3="GOTOU, Yuuzou",' +
+ '2.5.4.3="GOTOU\, Yuuzou",' +
+ "CN=#0C0CE5BE8CE897A4E8A395E894B5," +
+ 'CN=\E5\BE\8C\E8\97\A4\E8\A3\95\E8\94\B5,' +
+ "CN=\"\xE5\xBE\x8C\xE8\x97\xA4\xE8\xA3\x95\xE8\x94\xB5\"," +
+ "CN=\xE5\xBE\x8C\xE8\x97\xA4\xE8\xA3\x95\xE8\x94\xB5," +
+ 'L=aaa\=\"bbb\, ccc\",' +
+ 'L="aaa=\"bbb, ccc\"",' +
+ 'OU=,' +
+ 'OU="",' +
+ 'O=\,\=\+\<\>\#\;,' +
+ 'O=",=+<>#;",' +
+ "DC=ruby-lang," +
+ "DC=org")
+ )
+
+ [
+ "DC=org+DC=jp",
+ "DC=org,DC=ruby-lang+DC=rubyist,DC=www"
+ ].each{|dn|
+ ex = scanner.call(dn) rescue $!
+ dn_r = Regexp.escape(dn)
+ assert_match(/^multi-valued RDN is not supported: #{dn_r}/, ex.message)
+ }
+
+ [
+ ["DC=org,DC=exapmle,CN", "CN"],
+ ["DC=org,DC=example,", ""],
+ ["DC=org,DC=exapmle,CN=www.example.org;", "CN=www.example.org;"],
+ ["DC=org,DC=exapmle,CN=#www.example.org", "CN=#www.example.org"],
+ ["DC=org,DC=exapmle,CN=#777777.example.org", "CN=#777777.example.org"],
+ ["DC=org,DC=exapmle,CN=\"www.example\".org", "CN=\"www.example\".org"],
+ ["DC=org,DC=exapmle,CN=www.\"example.org\"", "CN=www.\"example.org\""],
+ ["DC=org,DC=exapmle,CN=www.\"example\".org", "CN=www.\"example\".org"],
+ ].each{|dn, msg|
+ ex = scanner.call(dn) rescue $!
+ assert_match(/^malformed RDN: .*=>#{Regexp.escape(msg)}/, ex.message)
+ }
+
+ dn = "CN=www.ruby-lang.org,DC=ruby-lang,DC=org"
+ name = OpenSSL::X509::Name.parse_rfc2253(dn)
+ assert_equal(dn, name.to_s(OpenSSL::X509::Name::RFC2253))
+ ary = name.to_a
+ assert_equal("DC", ary[0][0])
+ assert_equal("DC", ary[1][0])
+ assert_equal("CN", ary[2][0])
+ assert_equal("org", ary[0][1])
+ assert_equal("ruby-lang", ary[1][1])
+ assert_equal("www.ruby-lang.org", ary[2][1])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
+ end
+
+ def test_add_entry
+ dn = [
+ ["DC", "org"],
+ ["DC", "ruby-lang"],
+ ["CN", "GOTOU Yuuzou"],
+ ["emailAddress", "gotoyuzo@ruby-lang.org"],
+ ["serialNumber", "123"],
+ ]
+ name = OpenSSL::X509::Name.new
+ dn.each{|attr| name.add_entry(*attr) }
+ ary = name.to_a
+ assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
+ assert_equal("DC", ary[0][0])
+ assert_equal("DC", ary[1][0])
+ assert_equal("CN", ary[2][0])
+ assert_equal("emailAddress", ary[3][0])
+ assert_equal("serialNumber", ary[4][0])
+ assert_equal("org", ary[0][1])
+ assert_equal("ruby-lang", ary[1][1])
+ assert_equal("GOTOU Yuuzou", ary[2][1])
+ assert_equal("gotoyuzo@ruby-lang.org", ary[3][1])
+ assert_equal("123", ary[4][1])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
+ assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
+ assert_equal(OpenSSL::ASN1::IA5STRING, ary[3][2])
+ assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[4][2])
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_x509req.rb b/ruby_1_8_6/test/openssl/test_x509req.rb
new file mode 100644
index 0000000000..a37ed5c5ef
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_x509req.rb
@@ -0,0 +1,140 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestX509Request < Test::Unit::TestCase
+ def setup
+ @rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ @rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ @dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
+ @dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
+ @dn = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou")
+ end
+
+ def issue_csr(ver, dn, key, digest)
+ req = OpenSSL::X509::Request.new
+ req.version = ver
+ req.subject = dn
+ req.public_key = key.public_key
+ req.sign(key, digest)
+ req
+ end
+
+ def test_public_key
+ req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ assert_equal(@rsa1024.public_key.to_der, req.public_key.to_der)
+ req = OpenSSL::X509::Request.new(req.to_der)
+ assert_equal(@rsa1024.public_key.to_der, req.public_key.to_der)
+
+ req = issue_csr(0, @dn, @dsa512, OpenSSL::Digest::DSS1.new)
+ assert_equal(@dsa512.public_key.to_der, req.public_key.to_der)
+ req = OpenSSL::X509::Request.new(req.to_der)
+ assert_equal(@dsa512.public_key.to_der, req.public_key.to_der)
+ end
+
+ def test_version
+ req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ assert_equal(0, req.version)
+ req = OpenSSL::X509::Request.new(req.to_der)
+ assert_equal(0, req.version)
+
+ req = issue_csr(1, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ assert_equal(1, req.version)
+ req = OpenSSL::X509::Request.new(req.to_der)
+ assert_equal(1, req.version)
+ end
+
+ def test_subject
+ req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ assert_equal(@dn.to_der, req.subject.to_der)
+ req = OpenSSL::X509::Request.new(req.to_der)
+ assert_equal(@dn.to_der, req.subject.to_der)
+ end
+
+ def create_ext_req(exts)
+ ef = OpenSSL::X509::ExtensionFactory.new
+ exts = exts.collect{|e| ef.create_extension(*e) }
+ return OpenSSL::ASN1::Set([OpenSSL::ASN1::Sequence(exts)])
+ end
+
+ def get_ext_req(ext_req_value)
+ set = OpenSSL::ASN1.decode(ext_req_value)
+ seq = set.value[0]
+ seq.value.collect{|asn1ext|
+ OpenSSL::X509::Extension.new(asn1ext).to_a
+ }
+ end
+
+ def test_attr
+ exts = [
+ ["keyUsage", "Digital Signature, Key Encipherment", true],
+ ["subjectAltName", "email:gotoyuzo@ruby-lang.org", false],
+ ]
+ attrval = create_ext_req(exts)
+ attrs = [
+ OpenSSL::X509::Attribute.new("extReq", attrval),
+ OpenSSL::X509::Attribute.new("msExtReq", attrval),
+ ]
+
+ req0 = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ attrs.each{|attr| req0.add_attribute(attr) }
+ req1 = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ req1.attributes = attrs
+ assert_equal(req0.to_der, req1.to_der)
+
+ attrs = req0.attributes
+ assert_equal(2, attrs.size)
+ assert_equal("extReq", attrs[0].oid)
+ assert_equal("msExtReq", attrs[1].oid)
+ assert_equal(exts, get_ext_req(attrs[0].value))
+ assert_equal(exts, get_ext_req(attrs[1].value))
+
+ req = OpenSSL::X509::Request.new(req0.to_der)
+ attrs = req.attributes
+ assert_equal(2, attrs.size)
+ assert_equal("extReq", attrs[0].oid)
+ assert_equal("msExtReq", attrs[1].oid)
+ assert_equal(exts, get_ext_req(attrs[0].value))
+ assert_equal(exts, get_ext_req(attrs[1].value))
+ end
+
+ def test_sign_and_verify
+ req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
+ assert_equal(true, req.verify(@rsa1024))
+ assert_equal(false, req.verify(@rsa2048))
+ assert_equal(false, req.verify(@dsa256))
+ assert_equal(false, req.verify(@dsa512))
+ req.version = 1
+ assert_equal(false, req.verify(@rsa1024))
+
+ req = issue_csr(0, @dn, @rsa2048, OpenSSL::Digest::MD5.new)
+ assert_equal(false, req.verify(@rsa1024))
+ assert_equal(true, req.verify(@rsa2048))
+ assert_equal(false, req.verify(@dsa256))
+ assert_equal(false, req.verify(@dsa512))
+ req.subject = OpenSSL::X509::Name.parse("/C=JP/CN=FooBar")
+ assert_equal(false, req.verify(@rsa2048))
+
+ req = issue_csr(0, @dn, @dsa512, OpenSSL::Digest::DSS1.new)
+ assert_equal(false, req.verify(@rsa1024))
+ assert_equal(false, req.verify(@rsa2048))
+ assert_equal(false, req.verify(@dsa256))
+ assert_equal(true, req.verify(@dsa512))
+ req.public_key = @rsa1024.public_key
+ assert_equal(false, req.verify(@dsa512))
+
+ assert_raise(OpenSSL::X509::RequestError){
+ issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::DSS1.new) }
+ assert_raise(OpenSSL::X509::RequestError){
+ issue_csr(0, @dn, @dsa512, OpenSSL::Digest::SHA1.new) }
+ assert_raise(OpenSSL::X509::RequestError){
+ issue_csr(0, @dn, @dsa512, OpenSSL::Digest::MD5.new) }
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/test_x509store.rb b/ruby_1_8_6/test/openssl/test_x509store.rb
new file mode 100644
index 0000000000..b0fe597262
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/test_x509store.rb
@@ -0,0 +1,218 @@
+begin
+ require "openssl"
+ require File.join(File.dirname(__FILE__), "utils.rb")
+rescue LoadError
+end
+require "test/unit"
+
+if defined?(OpenSSL)
+
+class OpenSSL::TestX509Store < Test::Unit::TestCase
+ def setup
+ @rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
+ @rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
+ @dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
+ @dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
+ @ca1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA1")
+ @ca2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA2")
+ @ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
+ @ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
+ end
+
+ def teardown
+ end
+
+ def issue_cert(*args)
+ OpenSSL::TestUtils.issue_cert(*args)
+ end
+
+ def issue_crl(*args)
+ OpenSSL::TestUtils.issue_crl(*args)
+ end
+
+ def test_verify
+ now = Time.at(Time.now.to_i)
+ ca_exts = [
+ ["basicConstraints","CA:TRUE",true],
+ ["keyUsage","cRLSign,keyCertSign",true],
+ ]
+ ee_exts = [
+ ["keyUsage","keyEncipherment,digitalSignature",true],
+ ]
+ ca1_cert = issue_cert(@ca1, @rsa2048, 1, now, now+3600, ca_exts,
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ ca2_cert = issue_cert(@ca2, @rsa1024, 2, now, now+1800, ca_exts,
+ ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ ee1_cert = issue_cert(@ee1, @dsa256, 10, now, now+1800, ee_exts,
+ ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
+ ee2_cert = issue_cert(@ee2, @dsa512, 20, now, now+1800, ee_exts,
+ ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
+ ee3_cert = issue_cert(@ee2, @dsa512, 30, now-100, now-1, ee_exts,
+ ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
+ ee4_cert = issue_cert(@ee2, @dsa512, 40, now+1000, now+2000, ee_exts,
+ ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
+
+ revoke_info = []
+ crl1 = issue_crl(revoke_info, 1, now, now+1800, [],
+ ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ revoke_info = [ [2, now, 1], ]
+ crl1_2 = issue_crl(revoke_info, 2, now, now+1800, [],
+ ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ revoke_info = [ [20, now, 1], ]
+ crl2 = issue_crl(revoke_info, 1, now, now+1800, [],
+ ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
+ revoke_info = []
+ crl2_2 = issue_crl(revoke_info, 2, now-100, now-1, [],
+ ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
+
+ assert(true, ca1_cert.verify(ca1_cert.public_key)) # self signed
+ assert(true, ca2_cert.verify(ca1_cert.public_key)) # issued by ca1
+ assert(true, ee1_cert.verify(ca2_cert.public_key)) # issued by ca2
+ assert(true, ee2_cert.verify(ca2_cert.public_key)) # issued by ca2
+ assert(true, ee3_cert.verify(ca2_cert.public_key)) # issued by ca2
+ assert(true, crl1.verify(ca1_cert.public_key)) # issued by ca1
+ assert(true, crl1_2.verify(ca1_cert.public_key)) # issued by ca1
+ assert(true, crl2.verify(ca2_cert.public_key)) # issued by ca2
+ assert(true, crl2_2.verify(ca2_cert.public_key)) # issued by ca2
+
+ store = OpenSSL::X509::Store.new
+ assert_equal(false, store.verify(ca1_cert))
+ assert_not_equal(OpenSSL::X509::V_OK, store.error)
+
+ assert_equal(false, store.verify(ca2_cert))
+ assert_not_equal(OpenSSL::X509::V_OK, store.error)
+
+ store.add_cert(ca1_cert)
+ assert_equal(true, store.verify(ca2_cert))
+ assert_equal(OpenSSL::X509::V_OK, store.error)
+ assert_equal("ok", store.error_string)
+ chain = store.chain
+ assert_equal(2, chain.size)
+ assert_equal(@ca2.to_der, chain[0].subject.to_der)
+ assert_equal(@ca1.to_der, chain[1].subject.to_der)
+
+ store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
+ assert_equal(false, store.verify(ca2_cert))
+ assert_not_equal(OpenSSL::X509::V_OK, store.error)
+
+ store.purpose = OpenSSL::X509::PURPOSE_CRL_SIGN
+ assert_equal(true, store.verify(ca2_cert))
+ assert_equal(OpenSSL::X509::V_OK, store.error)
+
+ store.add_cert(ca2_cert)
+ store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
+ assert_equal(true, store.verify(ee1_cert))
+ assert_equal(true, store.verify(ee2_cert))
+ assert_equal(OpenSSL::X509::V_OK, store.error)
+ assert_equal("ok", store.error_string)
+ chain = store.chain
+ assert_equal(3, chain.size)
+ assert_equal(@ee2.to_der, chain[0].subject.to_der)
+ assert_equal(@ca2.to_der, chain[1].subject.to_der)
+ assert_equal(@ca1.to_der, chain[2].subject.to_der)
+ assert_equal(false, store.verify(ee3_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
+ assert_match(/expire/i, store.error_string)
+ assert_equal(false, store.verify(ee4_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
+ assert_match(/not yet valid/i, store.error_string)
+
+ store = OpenSSL::X509::Store.new
+ store.add_cert(ca1_cert)
+ store.add_cert(ca2_cert)
+ store.time = now + 1500
+ assert_equal(true, store.verify(ca1_cert))
+ assert_equal(true, store.verify(ca2_cert))
+ assert_equal(true, store.verify(ee4_cert))
+ store.time = now + 1900
+ assert_equal(true, store.verify(ca1_cert))
+ assert_equal(false, store.verify(ca2_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
+ assert_equal(false, store.verify(ee4_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
+ store.time = now + 4000
+ assert_equal(false, store.verify(ee1_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
+ assert_equal(false, store.verify(ee4_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
+
+ # the underlying X509 struct caches the result of the last
+ # verification for signature and not-before. so the following code
+ # rebuilds new objects to avoid site effect.
+ store.time = Time.now - 4000
+ assert_equal(false, store.verify(OpenSSL::X509::Certificate.new(ca2_cert)))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
+ assert_equal(false, store.verify(OpenSSL::X509::Certificate.new(ee1_cert)))
+ assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
+
+ return unless defined?(OpenSSL::X509::V_FLAG_CRL_CHECK)
+
+ store = OpenSSL::X509::Store.new
+ store.purpose = OpenSSL::X509::PURPOSE_ANY
+ store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK
+ store.add_cert(ca1_cert)
+ store.add_crl(crl1) # revoke no cert
+ store.add_crl(crl2) # revoke ee2_cert
+ assert_equal(true, store.verify(ca1_cert))
+ assert_equal(true, store.verify(ca2_cert))
+ assert_equal(true, store.verify(ee1_cert, [ca2_cert]))
+ assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
+
+ store = OpenSSL::X509::Store.new
+ store.purpose = OpenSSL::X509::PURPOSE_ANY
+ store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK
+ store.add_cert(ca1_cert)
+ store.add_crl(crl1_2) # revoke ca2_cert
+ store.add_crl(crl2) # revoke ee2_cert
+ assert_equal(true, store.verify(ca1_cert))
+ assert_equal(false, store.verify(ca2_cert))
+ assert_equal(true, store.verify(ee1_cert, [ca2_cert]),
+ "This test is expected to be success with OpenSSL 0.9.7c or later.")
+ assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
+
+ store.flags =
+ OpenSSL::X509::V_FLAG_CRL_CHECK|OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
+ assert_equal(true, store.verify(ca1_cert))
+ assert_equal(false, store.verify(ca2_cert))
+ assert_equal(false, store.verify(ee1_cert, [ca2_cert]))
+ assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
+
+ store = OpenSSL::X509::Store.new
+ store.purpose = OpenSSL::X509::PURPOSE_ANY
+ store.flags =
+ OpenSSL::X509::V_FLAG_CRL_CHECK|OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
+ store.add_cert(ca1_cert)
+ store.add_cert(ca2_cert)
+ store.add_crl(crl1)
+ store.add_crl(crl2_2) # issued by ca2 but expired.
+ assert_equal(true, store.verify(ca1_cert))
+ assert_equal(true, store.verify(ca2_cert))
+ assert_equal(false, store.verify(ee1_cert))
+ assert_equal(OpenSSL::X509::V_ERR_CRL_HAS_EXPIRED, store.error)
+ assert_equal(false, store.verify(ee2_cert))
+ end
+
+ def test_set_errors
+ now = Time.now
+ ca1_cert = issue_cert(@ca1, @rsa2048, 1, now, now+3600, [],
+ nil, nil, OpenSSL::Digest::SHA1.new)
+ store = OpenSSL::X509::Store.new
+ store.add_cert(ca1_cert)
+ assert_raises(OpenSSL::X509::StoreError){
+ store.add_cert(ca1_cert) # add same certificate twice
+ }
+
+ revoke_info = []
+ crl1 = issue_crl(revoke_info, 1, now, now+1800, [],
+ ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ revoke_info = [ [2, now, 1], ]
+ crl2 = issue_crl(revoke_info, 2, now+1800, now+3600, [],
+ ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
+ store.add_crl(crl1)
+ assert_raises(OpenSSL::X509::StoreError){
+ store.add_crl(crl2) # add CRL issued by same CA twice.
+ }
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/openssl/utils.rb b/ruby_1_8_6/test/openssl/utils.rb
new file mode 100644
index 0000000000..c923705b86
--- /dev/null
+++ b/ruby_1_8_6/test/openssl/utils.rb
@@ -0,0 +1,135 @@
+require "openssl"
+require "test/unit"
+
+module OpenSSL::TestUtils
+ TEST_KEY_RSA1024 = OpenSSL::PKey::RSA.new <<-_end_of_pem_
+-----BEGIN RSA PRIVATE KEY-----
+MIICXgIBAAKBgQDLwsSw1ECnPtT+PkOgHhcGA71nwC2/nL85VBGnRqDxOqjVh7Cx
+aKPERYHsk4BPCkE3brtThPWc9kjHEQQ7uf9Y1rbCz0layNqHyywQEVLFmp1cpIt/
+Q3geLv8ZD9pihowKJDyMDiN6ArYUmZczvW4976MU3+l54E6lF/JfFEU5hwIDAQAB
+AoGBAKSl/MQarye1yOysqX6P8fDFQt68VvtXkNmlSiKOGuzyho0M+UVSFcs6k1L0
+maDE25AMZUiGzuWHyaU55d7RXDgeskDMakD1v6ZejYtxJkSXbETOTLDwUWTn618T
+gnb17tU1jktUtU67xK/08i/XodlgnQhs6VoHTuCh3Hu77O6RAkEA7+gxqBuZR572
+74/akiW/SuXm0SXPEviyO1MuSRwtI87B02D0qgV8D1UHRm4AhMnJ8MCs1809kMQE
+JiQUCrp9mQJBANlt2ngBO14us6NnhuAseFDTBzCHXwUUu1YKHpMMmxpnGqaldGgX
+sOZB3lgJsT9VlGf3YGYdkLTNVbogQKlKpB8CQQDiSwkb4vyQfDe8/NpU5Not0fII
+8jsDUCb+opWUTMmfbxWRR3FBNu8wnym/m19N4fFj8LqYzHX4KY0oVPu6qvJxAkEA
+wa5snNekFcqONLIE4G5cosrIrb74sqL8GbGb+KuTAprzj5z1K8Bm0UW9lTjVDjDi
+qRYgZfZSL+x1P/54+xTFSwJAY1FxA/N3QPCXCjPh5YqFxAMQs2VVYTfg+t0MEcJD
+dPMQD5JX6g5HKnHFg2mZtoXQrWmJSn7p8GJK8yNTopEErA==
+-----END RSA PRIVATE KEY-----
+ _end_of_pem_
+
+ TEST_KEY_RSA2048 = OpenSSL::PKey::RSA.new <<-_end_of_pem_
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpAIBAAKCAQEAuV9ht9J7k4NBs38jOXvvTKY9gW8nLICSno5EETR1cuF7i4pN
+s9I1QJGAFAX0BEO4KbzXmuOvfCpD3CU+Slp1enenfzq/t/e/1IRW0wkJUJUFQign
+4CtrkJL+P07yx18UjyPlBXb81ApEmAB5mrJVSrWmqbjs07JbuS4QQGGXLc+Su96D
+kYKmSNVjBiLxVVSpyZfAY3hD37d60uG+X8xdW5v68JkRFIhdGlb6JL8fllf/A/bl
+NwdJOhVr9mESHhwGjwfSeTDPfd8ZLE027E5lyAVX9KZYcU00mOX+fdxOSnGqS/8J
+DRh0EPHDL15RcJjV2J6vZjPb0rOYGDoMcH+94wIDAQABAoIBAAzsamqfYQAqwXTb
+I0CJtGg6msUgU7HVkOM+9d3hM2L791oGHV6xBAdpXW2H8LgvZHJ8eOeSghR8+dgq
+PIqAffo4x1Oma+FOg3A0fb0evyiACyrOk+EcBdbBeLo/LcvahBtqnDfiUMQTpy6V
+seSoFCwuN91TSCeGIsDpRjbG1vxZgtx+uI+oH5+ytqJOmfCksRDCkMglGkzyfcl0
+Xc5CUhIJ0my53xijEUQl19rtWdMnNnnkdbG8PT3LZlOta5Do86BElzUYka0C6dUc
+VsBDQ0Nup0P6rEQgy7tephHoRlUGTYamsajGJaAo1F3IQVIrRSuagi7+YpSpCqsW
+wORqorkCgYEA7RdX6MDVrbw7LePnhyuaqTiMK+055/R1TqhB1JvvxJ1CXk2rDL6G
+0TLHQ7oGofd5LYiemg4ZVtWdJe43BPZlVgT6lvL/iGo8JnrncB9Da6L7nrq/+Rvj
+XGjf1qODCK+LmreZWEsaLPURIoR/Ewwxb9J2zd0CaMjeTwafJo1CZvcCgYEAyCgb
+aqoWvUecX8VvARfuA593Lsi50t4MEArnOXXcd1RnXoZWhbx5rgO8/ATKfXr0BK/n
+h2GF9PfKzHFm/4V6e82OL7gu/kLy2u9bXN74vOvWFL5NOrOKPM7Kg+9I131kNYOw
+Ivnr/VtHE5s0dY7JChYWE1F3vArrOw3T00a4CXUCgYEA0SqY+dS2LvIzW4cHCe9k
+IQqsT0yYm5TFsUEr4sA3xcPfe4cV8sZb9k/QEGYb1+SWWZ+AHPV3UW5fl8kTbSNb
+v4ng8i8rVVQ0ANbJO9e5CUrepein2MPL0AkOATR8M7t7dGGpvYV0cFk8ZrFx0oId
+U0PgYDotF/iueBWlbsOM430CgYEAqYI95dFyPI5/AiSkY5queeb8+mQH62sdcCCr
+vd/w/CZA/K5sbAo4SoTj8dLk4evU6HtIa0DOP63y071eaxvRpTNqLUOgmLh+D6gS
+Cc7TfLuFrD+WDBatBd5jZ+SoHccVrLR/4L8jeodo5FPW05A+9gnKXEXsTxY4LOUC
+9bS4e1kCgYAqVXZh63JsMwoaxCYmQ66eJojKa47VNrOeIZDZvd2BPVf30glBOT41
+gBoDG3WMPZoQj9pb7uMcrnvs4APj2FIhMU8U15LcPAj59cD6S6rWnAxO8NFK7HQG
+4Jxg3JNNf8ErQoCHb1B3oVdXJkmbJkARoDpBKmTCgKtP8ADYLmVPQw==
+-----END RSA PRIVATE KEY-----
+ _end_of_pem_
+
+ TEST_KEY_DSA256 = OpenSSL::PKey::DSA.new <<-_end_of_pem_
+-----BEGIN DSA PRIVATE KEY-----
+MIH3AgEAAkEAhk2libbY2a8y2Pt21+YPYGZeW6wzaW2yfj5oiClXro9XMR7XWLkE
+9B7XxLNFCS2gmCCdMsMW1HulaHtLFQmB2wIVAM43JZrcgpu6ajZ01VkLc93gu/Ed
+AkAOhujZrrKV5CzBKutKLb0GVyVWmdC7InoNSMZEeGU72rT96IjM59YzoqmD0pGM
+3I1o4cGqg1D1DfM1rQlnN1eSAkBq6xXfEDwJ1mLNxF6q8Zm/ugFYWR5xcX/3wFiT
+b4+EjHP/DbNh9Vm5wcfnDBJ1zKvrMEf2xqngYdrV/3CiGJeKAhRvL57QvJZcQGvn
+ISNX5cMzFHRW3Q==
+-----END DSA PRIVATE KEY-----
+ _end_of_pem_
+
+ TEST_KEY_DSA512 = OpenSSL::PKey::DSA.new <<-_end_of_pem_
+-----BEGIN DSA PRIVATE KEY-----
+MIH4AgEAAkEA5lB4GvEwjrsMlGDqGsxrbqeFRh6o9OWt6FgTYiEEHaOYhkIxv0Ok
+RZPDNwOG997mDjBnvDJ1i56OmS3MbTnovwIVAJgub/aDrSDB4DZGH7UyarcaGy6D
+AkB9HdFw/3td8K4l1FZHv7TCZeJ3ZLb7dF3TWoGUP003RCqoji3/lHdKoVdTQNuR
+S/m6DlCwhjRjiQ/lBRgCLCcaAkEAjN891JBjzpMj4bWgsACmMggFf57DS0Ti+5++
+Q1VB8qkJN7rA7/2HrCR3gTsWNb1YhAsnFsoeRscC+LxXoXi9OAIUBG98h4tilg6S
+55jreJD3Se3slps=
+-----END DSA PRIVATE KEY-----
+ _end_of_pem_
+
+ module_function
+
+ def issue_cert(dn, key, serial, not_before, not_after, extensions,
+ issuer, issuer_key, digest)
+ cert = OpenSSL::X509::Certificate.new
+ issuer = cert unless issuer
+ issuer_key = key unless issuer_key
+ cert.version = 2
+ cert.serial = serial
+ cert.subject = dn
+ cert.issuer = issuer.subject
+ cert.public_key = key.public_key
+ cert.not_before = not_before
+ cert.not_after = not_after
+ ef = OpenSSL::X509::ExtensionFactory.new
+ ef.subject_certificate = cert
+ ef.issuer_certificate = issuer
+ extensions.each{|oid, value, critical|
+ cert.add_extension(ef.create_extension(oid, value, critical))
+ }
+ cert.sign(issuer_key, digest)
+ cert
+ end
+
+ def issue_crl(revoke_info, serial, lastup, nextup, extensions,
+ issuer, issuer_key, digest)
+ crl = OpenSSL::X509::CRL.new
+ crl.issuer = issuer.subject
+ crl.version = 1
+ crl.last_update = lastup
+ crl.next_update = nextup
+ revoke_info.each{|serial, time, reason_code|
+ revoked = OpenSSL::X509::Revoked.new
+ revoked.serial = serial
+ revoked.time = time
+ enum = OpenSSL::ASN1::Enumerated(reason_code)
+ ext = OpenSSL::X509::Extension.new("CRLReason", enum)
+ revoked.add_extension(ext)
+ crl.add_revoked(revoked)
+ }
+ ef = OpenSSL::X509::ExtensionFactory.new
+ ef.issuer_certificate = issuer
+ ef.crl = crl
+ crlnum = OpenSSL::ASN1::Integer(serial)
+ crl.add_extension(OpenSSL::X509::Extension.new("crlNumber", crlnum))
+ extensions.each{|oid, value, critical|
+ crl.add_extension(ef.create_extension(oid, value, critical))
+ }
+ crl.sign(issuer_key, digest)
+ crl
+ end
+
+ def get_subject_key_id(cert)
+ asn1_cert = OpenSSL::ASN1.decode(cert)
+ tbscert = asn1_cert.value[0]
+ pkinfo = tbscert.value[6]
+ publickey = pkinfo.value[1]
+ pkvalue = publickey.value
+ OpenSSL::Digest::SHA1.hexdigest(pkvalue).scan(/../).join(":").upcase
+ end
+end
diff --git a/ruby_1_8_6/test/optparse/test_getopts.rb b/ruby_1_8_6/test/optparse/test_getopts.rb
new file mode 100644
index 0000000000..fdefe5f3e5
--- /dev/null
+++ b/ruby_1_8_6/test/optparse/test_getopts.rb
@@ -0,0 +1,31 @@
+require 'test/unit'
+
+class TestOptionParserGetopts < Test::Unit::TestCase
+ def setup
+ @opt = OptionParser.new
+ end
+
+ def test_short_noarg
+ o = @opt.getopts(%w[-a], "ab")
+ assert_equal(true, o['a'])
+ assert_equal(false, o['b'])
+ end
+
+ def test_short_arg
+ o = @opt.getopts(%w[-a1], "a:b:")
+ assert_equal("1", o['a'])
+ assert_equal(nil, o['b'])
+ end
+
+ def test_long_noarg
+ o = @opt.getopts(%w[--foo], "", "foo", "bar")
+ assert_equal(true, o['foo'])
+ assert_equal(false, o['bar'])
+ end
+
+ def test_long_arg
+ o = @opt.getopts(%w[--bar ZOT], "", "foo:FOO", "bar:BAR")
+ assert_equal("FOO", o['foo'])
+ assert_equal("ZOT", o['bar'])
+ end
+end
diff --git a/ruby_1_8_6/test/optparse/test_noarg.rb b/ruby_1_8_6/test/optparse/test_noarg.rb
new file mode 100644
index 0000000000..28c469093d
--- /dev/null
+++ b/ruby_1_8_6/test/optparse/test_noarg.rb
@@ -0,0 +1,57 @@
+require 'test_optparse'
+
+module TestOptionParser::NoArg
+ class Def1 < TestOptionParser
+ include NoArg
+ def setup
+ super
+ @opt.def_option("-x") {|x| @flag = x}
+ @opt.def_option("--option") {|x| @flag = x}
+ end
+ end
+ class Def2 < TestOptionParser
+ include NoArg
+ def setup
+ super
+ @opt.def_option("-x", "--option") {|x| @flag = x}
+ end
+ end
+
+ def test_short
+ assert_raises(OptionParser::InvalidOption) {@opt.parse!(%w"-xq")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x")})
+ assert_equal(true, @flag)
+ @flag = nil
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"-x foo")})
+ assert_equal(true, @flag)
+ end
+
+ def test_abbrev
+ assert_raises(OptionParser::InvalidOption) {@opt.parse!(%w"-oq")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o")})
+ assert_equal(true, @flag)
+ @flag = nil
+ assert_raises(OptionParser::InvalidOption) {@opt.parse!(%w"-O")}
+ assert_nil(@flag)
+ @flag = nil
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"-o foo")})
+ assert_equal(true, @flag)
+ end
+
+ def test_long
+ assert_raises(OptionParser::NeedlessArgument) {@opt.parse!(%w"--option=x")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt")})
+ assert_equal(true, @flag)
+ @flag = nil
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt foo")})
+ assert_equal(true, @flag)
+ end
+
+ def test_ambiguous
+ @opt.def_option("--open") {|x|}
+ assert_raises(OptionParser::AmbiguousOption) {@opt.parse!(%w"--op")}
+ assert_raises(OptionParser::AmbiguousOption) {@opt.parse!(%w"-o")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt")})
+ assert_equal(true, @flag)
+ end
+end
diff --git a/ruby_1_8_6/test/optparse/test_optarg.rb b/ruby_1_8_6/test/optparse/test_optarg.rb
new file mode 100644
index 0000000000..49cb1b93ec
--- /dev/null
+++ b/ruby_1_8_6/test/optparse/test_optarg.rb
@@ -0,0 +1,44 @@
+require 'test_optparse'
+
+class TestOptionParser::OptArg < TestOptionParser
+ def setup
+ super
+ @opt.def_option("-x[VAL]") {|x| @flag = x}
+ @opt.def_option("--option[=VAL]") {|x| @flag = x}
+ end
+
+ def test_short
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x")})
+ assert_equal(nil, @flag)
+ @flag = false
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"-x foo")})
+ assert_equal(nil, @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-xfoo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x=")})
+ assert_equal("=", @flag)
+ end
+
+ def test_abbrev
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o")})
+ assert_equal(nil, @flag)
+ @flag = false
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"-o foo")})
+ assert_equal(nil, @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-ofoo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o=")})
+ assert_equal("=", @flag)
+ end
+
+ def test_long
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt")})
+ assert_equal(nil, @flag)
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt= foo")})
+ assert_equal("", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt=foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt foo")})
+ assert_equal(nil, @flag)
+ end
+end
diff --git a/ruby_1_8_6/test/optparse/test_optparse.rb b/ruby_1_8_6/test/optparse/test_optparse.rb
new file mode 100644
index 0000000000..9c73399f5b
--- /dev/null
+++ b/ruby_1_8_6/test/optparse/test_optparse.rb
@@ -0,0 +1,46 @@
+require 'test/unit'
+require 'optparse'
+
+class TestOptionParser < Test::Unit::TestCase
+ def setup
+ @opt = OptionParser.new
+ @flag = self.class # cannot set by option
+ end
+ def no_error(*args)
+ assert_nothing_raised(*args) {return yield}
+ end
+
+ def test_permute
+ assert_equal(%w"", no_error {@opt.permute!(%w"")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo bar", no_error {@opt.permute!(%w"foo bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"- foo bar", no_error {@opt.permute!(%w"- foo bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo bar", no_error {@opt.permute!(%w"-- foo bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo - bar", no_error {@opt.permute!(%w"foo - bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo bar", no_error {@opt.permute!(%w"foo -- bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo --help bar", no_error {@opt.permute!(%w"foo -- --help bar")})
+ assert_equal(self.class, @flag)
+ end
+
+ def test_order
+ assert_equal(%w"", no_error {@opt.order!(%w"")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo bar", no_error {@opt.order!(%w"foo bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"- foo bar", no_error {@opt.order!(%w"- foo bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo bar", no_error {@opt.permute!(%w"-- foo bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo - bar", no_error {@opt.order!(%w"foo - bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo -- bar", no_error {@opt.order!(%w"foo -- bar")})
+ assert_equal(self.class, @flag)
+ assert_equal(%w"foo -- --help bar", no_error {@opt.order!(%w"foo -- --help bar")})
+ assert_equal(self.class, @flag)
+ end
+end
diff --git a/ruby_1_8_6/test/optparse/test_placearg.rb b/ruby_1_8_6/test/optparse/test_placearg.rb
new file mode 100644
index 0000000000..f4fd249b7f
--- /dev/null
+++ b/ruby_1_8_6/test/optparse/test_placearg.rb
@@ -0,0 +1,45 @@
+require 'test_optparse'
+
+class TestOptionParser::PlaceArg < TestOptionParser
+ def setup
+ super
+ @opt.def_option("-x [VAL]") {|x| @flag = x}
+ @opt.def_option("--option [VAL]") {|x| @flag = x}
+ @opt.def_option("-n") {}
+ end
+
+ def test_short
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x -n")})
+ assert_equal(nil, @flag)
+ @flag = false
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-xbar")})
+ assert_equal("bar", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x=")})
+ assert_equal("=", @flag)
+ end
+
+ def test_abbrev
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o -n")})
+ assert_equal(nil, @flag)
+ @flag = false
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-obar")})
+ assert_equal("bar", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o=")})
+ assert_equal("=", @flag)
+ end
+
+ def test_long
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt -n")})
+ assert_equal(nil, @flag)
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt= foo")})
+ assert_equal("", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt=foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt bar")})
+ assert_equal("bar", @flag)
+ end
+end
diff --git a/ruby_1_8_6/test/optparse/test_reqarg.rb b/ruby_1_8_6/test/optparse/test_reqarg.rb
new file mode 100644
index 0000000000..0999e5e603
--- /dev/null
+++ b/ruby_1_8_6/test/optparse/test_reqarg.rb
@@ -0,0 +1,63 @@
+require 'test_optparse'
+
+module TestOptionParser::ReqArg
+ class Def1 < TestOptionParser
+ include ReqArg
+ def setup
+ super
+ @opt.def_option("-xVAL") {|x| @flag = x}
+ @opt.def_option("--option=VAL") {|x| @flag = x}
+ end
+ end
+ class Def2 < TestOptionParser
+ include ReqArg
+ def setup
+ super
+ @opt.def_option("-x", "--option=VAL") {|x| @flag = x}
+ end
+ end
+ class Def3 < TestOptionParser
+ include ReqArg
+ def setup
+ super
+ @opt.def_option("--option=VAL", "-x") {|x| @flag = x}
+ end
+ end
+ class Def4 < TestOptionParser
+ include ReqArg
+ def setup
+ super
+ @opt.def_option("-xVAL", "--option=VAL") {|x| @flag = x}
+ end
+ end
+
+ def test_short
+ assert_raises(OptionParser::MissingArgument) {@opt.parse!(%w"-x")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-xbar")})
+ assert_equal("bar", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-x=")})
+ assert_equal("=", @flag)
+ end
+
+ def test_abbrev
+ assert_raises(OptionParser::MissingArgument) {@opt.parse!(%w"-o")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-obar")})
+ assert_equal("bar", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"-o=")})
+ assert_equal("=", @flag)
+ end
+
+ def test_long
+ assert_raises(OptionParser::MissingArgument) {@opt.parse!(%w"--opt")}
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt foo")})
+ assert_equal("foo", @flag)
+ assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt= foo")})
+ assert_equal("", @flag)
+ assert_equal(%w"", no_error {@opt.parse!(%w"--opt=foo")})
+ assert_equal("foo", @flag)
+ end
+end
diff --git a/ruby_1_8_6/test/ostruct/test_ostruct.rb b/ruby_1_8_6/test/ostruct/test_ostruct.rb
new file mode 100644
index 0000000000..24ed17f800
--- /dev/null
+++ b/ruby_1_8_6/test/ostruct/test_ostruct.rb
@@ -0,0 +1,23 @@
+require 'test/unit'
+require 'ostruct'
+
+class TC_OpenStruct < Test::Unit::TestCase
+ def test_equality
+ o1 = OpenStruct.new
+ o2 = OpenStruct.new
+ assert_equal(o1, o2)
+
+ o1.a = 'a'
+ assert_not_equal(o1, o2)
+
+ o2.a = 'a'
+ assert_equal(o1, o2)
+
+ o1.a = 'b'
+ assert_not_equal(o1, o2)
+
+ o2 = Object.new
+ o2.instance_eval{@table = {:a => 'b'}}
+ assert_not_equal(o1, o2)
+ end
+end
diff --git a/ruby_1_8_6/test/pathname/test_pathname.rb b/ruby_1_8_6/test/pathname/test_pathname.rb
new file mode 100644
index 0000000000..ecf7a71be5
--- /dev/null
+++ b/ruby_1_8_6/test/pathname/test_pathname.rb
@@ -0,0 +1,486 @@
+#!/usr/bin/env ruby
+
+require 'test/unit'
+require 'pathname'
+
+require 'fileutils'
+require 'tmpdir'
+require 'enumerator'
+
+class TestPathname < Test::Unit::TestCase
+
+ if RUBY_VERSION < "1.9"
+ FUNCALL = :__send__
+ else
+ FUNCALL = :funcall
+ end
+
+ def self.define_assertion(name, &block)
+ @defassert_num ||= {}
+ @defassert_num[name] ||= 0
+ @defassert_num[name] += 1
+ define_method("test_#{name}_#{@defassert_num[name]}", &block)
+ end
+
+ def self.defassert(name, result, *args)
+ define_assertion(name) {
+ assert_equal(result, self.send(name, *args), "#{name}(#{args.map {|a| a.inspect }.join(', ')})")
+ }
+ end
+
+ DOSISH = File::ALT_SEPARATOR != nil
+ DOSISH_DRIVE_LETTER = File.dirname("A:") == "A:."
+ DOSISH_UNC = File.dirname("//") == "//"
+
+ def cleanpath_aggressive(path)
+ Pathname.new(path).cleanpath.to_s
+ end
+
+ defassert(:cleanpath_aggressive, '/', '/')
+ defassert(:cleanpath_aggressive, '.', '')
+ defassert(:cleanpath_aggressive, '.', '.')
+ defassert(:cleanpath_aggressive, '..', '..')
+ defassert(:cleanpath_aggressive, 'a', 'a')
+ defassert(:cleanpath_aggressive, '/', '/.')
+ defassert(:cleanpath_aggressive, '/', '/..')
+ defassert(:cleanpath_aggressive, '/a', '/a')
+ defassert(:cleanpath_aggressive, '.', './')
+ defassert(:cleanpath_aggressive, '..', '../')
+ defassert(:cleanpath_aggressive, 'a', 'a/')
+ defassert(:cleanpath_aggressive, 'a/b', 'a//b')
+ defassert(:cleanpath_aggressive, 'a', 'a/.')
+ defassert(:cleanpath_aggressive, 'a', 'a/./')
+ defassert(:cleanpath_aggressive, '.', 'a/..')
+ defassert(:cleanpath_aggressive, '.', 'a/../')
+ defassert(:cleanpath_aggressive, '/a', '/a/.')
+ defassert(:cleanpath_aggressive, '..', './..')
+ defassert(:cleanpath_aggressive, '..', '../.')
+ defassert(:cleanpath_aggressive, '..', './../')
+ defassert(:cleanpath_aggressive, '..', '.././')
+ defassert(:cleanpath_aggressive, '/', '/./..')
+ defassert(:cleanpath_aggressive, '/', '/../.')
+ defassert(:cleanpath_aggressive, '/', '/./../')
+ defassert(:cleanpath_aggressive, '/', '/.././')
+ defassert(:cleanpath_aggressive, 'a/b/c', 'a/b/c')
+ defassert(:cleanpath_aggressive, 'b/c', './b/c')
+ defassert(:cleanpath_aggressive, 'a/c', 'a/./c')
+ defassert(:cleanpath_aggressive, 'a/b', 'a/b/.')
+ defassert(:cleanpath_aggressive, '.', 'a/../.')
+ defassert(:cleanpath_aggressive, '/a', '/../.././../a')
+ defassert(:cleanpath_aggressive, '../../d', 'a/b/../../../../c/../d')
+
+ if DOSISH_UNC
+ defassert(:cleanpath_aggressive, '//a/b/c', '//a/b/c/')
+ else
+ defassert(:cleanpath_aggressive, '/', '///')
+ defassert(:cleanpath_aggressive, '/a', '///a')
+ defassert(:cleanpath_aggressive, '/', '///..')
+ defassert(:cleanpath_aggressive, '/', '///.')
+ defassert(:cleanpath_aggressive, '/', '///a/../..')
+ end
+
+ def cleanpath_conservative(path)
+ Pathname.new(path).cleanpath(true).to_s
+ end
+
+ defassert(:cleanpath_conservative, '/', '/')
+ defassert(:cleanpath_conservative, '.', '')
+ defassert(:cleanpath_conservative, '.', '.')
+ defassert(:cleanpath_conservative, '..', '..')
+ defassert(:cleanpath_conservative, 'a', 'a')
+ defassert(:cleanpath_conservative, '/', '/.')
+ defassert(:cleanpath_conservative, '/', '/..')
+ defassert(:cleanpath_conservative, '/a', '/a')
+ defassert(:cleanpath_conservative, '.', './')
+ defassert(:cleanpath_conservative, '..', '../')
+ defassert(:cleanpath_conservative, 'a/', 'a/')
+ defassert(:cleanpath_conservative, 'a/b', 'a//b')
+ defassert(:cleanpath_conservative, 'a/.', 'a/.')
+ defassert(:cleanpath_conservative, 'a/.', 'a/./')
+ defassert(:cleanpath_conservative, 'a/..', 'a/../')
+ defassert(:cleanpath_conservative, '/a/.', '/a/.')
+ defassert(:cleanpath_conservative, '..', './..')
+ defassert(:cleanpath_conservative, '..', '../.')
+ defassert(:cleanpath_conservative, '..', './../')
+ defassert(:cleanpath_conservative, '..', '.././')
+ defassert(:cleanpath_conservative, '/', '/./..')
+ defassert(:cleanpath_conservative, '/', '/../.')
+ defassert(:cleanpath_conservative, '/', '/./../')
+ defassert(:cleanpath_conservative, '/', '/.././')
+ defassert(:cleanpath_conservative, 'a/b/c', 'a/b/c')
+ defassert(:cleanpath_conservative, 'b/c', './b/c')
+ defassert(:cleanpath_conservative, 'a/c', 'a/./c')
+ defassert(:cleanpath_conservative, 'a/b/.', 'a/b/.')
+ defassert(:cleanpath_conservative, 'a/..', 'a/../.')
+ defassert(:cleanpath_conservative, '/a', '/../.././../a')
+ defassert(:cleanpath_conservative, 'a/b/../../../../c/../d', 'a/b/../../../../c/../d')
+
+ if DOSISH_UNC
+ defassert(:cleanpath_conservative, '//', '//')
+ else
+ defassert(:cleanpath_conservative, '/', '//')
+ end
+
+ # has_trailing_separator?(path) -> bool
+ def has_trailing_separator?(path)
+ Pathname.allocate.send(FUNCALL, :has_trailing_separator?, path)
+ end
+
+ defassert(:has_trailing_separator?, false, "/")
+ defassert(:has_trailing_separator?, false, "///")
+ defassert(:has_trailing_separator?, false, "a")
+ defassert(:has_trailing_separator?, true, "a/")
+
+ def add_trailing_separator(path)
+ Pathname.allocate.send(FUNCALL, :add_trailing_separator, path)
+ end
+
+ def del_trailing_separator(path)
+ Pathname.allocate.send(FUNCALL, :del_trailing_separator, path)
+ end
+
+ defassert(:del_trailing_separator, "/", "/")
+ defassert(:del_trailing_separator, "/a", "/a")
+ defassert(:del_trailing_separator, "/a", "/a/")
+ defassert(:del_trailing_separator, "/a", "/a//")
+ defassert(:del_trailing_separator, ".", ".")
+ defassert(:del_trailing_separator, ".", "./")
+ defassert(:del_trailing_separator, ".", ".//")
+
+ if DOSISH_DRIVE_LETTER
+ defassert(:del_trailing_separator, "A:", "A:")
+ defassert(:del_trailing_separator, "A:/", "A:/")
+ defassert(:del_trailing_separator, "A:/", "A://")
+ defassert(:del_trailing_separator, "A:.", "A:.")
+ defassert(:del_trailing_separator, "A:.", "A:./")
+ defassert(:del_trailing_separator, "A:.", "A:.//")
+ end
+
+ if DOSISH_UNC
+ defassert(:del_trailing_separator, "//", "//")
+ defassert(:del_trailing_separator, "//a", "//a")
+ defassert(:del_trailing_separator, "//a", "//a/")
+ defassert(:del_trailing_separator, "//a", "//a//")
+ defassert(:del_trailing_separator, "//a/b", "//a/b")
+ defassert(:del_trailing_separator, "//a/b", "//a/b/")
+ defassert(:del_trailing_separator, "//a/b", "//a/b//")
+ defassert(:del_trailing_separator, "//a/b/c", "//a/b/c")
+ defassert(:del_trailing_separator, "//a/b/c", "//a/b/c/")
+ defassert(:del_trailing_separator, "//a/b/c", "//a/b/c//")
+ else
+ defassert(:del_trailing_separator, "/", "///")
+ defassert(:del_trailing_separator, "///a", "///a/")
+ end
+
+ if DOSISH
+ defassert(:del_trailing_separator, "a", "a\\")
+ defassert(:del_trailing_separator, "\225\\", "\225\\\\") # SJIS
+ end
+
+ def plus(path1, path2) # -> path
+ (Pathname.new(path1) + Pathname.new(path2)).to_s
+ end
+
+ defassert(:plus, '/', '/', '/')
+ defassert(:plus, 'a/b', 'a', 'b')
+ defassert(:plus, 'a', 'a', '.')
+ defassert(:plus, 'b', '.', 'b')
+ defassert(:plus, '.', '.', '.')
+ defassert(:plus, '/b', 'a', '/b')
+
+ defassert(:plus, '/', '/', '..')
+ defassert(:plus, '.', 'a', '..')
+ defassert(:plus, 'a', 'a/b', '..')
+ defassert(:plus, '../..', '..', '..')
+ defassert(:plus, '/c', '/', '../c')
+ defassert(:plus, 'c', 'a', '../c')
+ defassert(:plus, 'a/c', 'a/b', '../c')
+ defassert(:plus, '../../c', '..', '../c')
+
+ defassert(:plus, 'a//b/d//e', 'a//b/c', '../d//e')
+
+ def relative?(path)
+ Pathname.new(path).relative?
+ end
+
+ defassert(:relative?, false, '/')
+ defassert(:relative?, false, '/a')
+ defassert(:relative?, false, '/..')
+ defassert(:relative?, true, 'a')
+ defassert(:relative?, true, 'a/b')
+
+ if DOSISH_DRIVE_LETTER
+ defassert(:relative?, false, 'A:')
+ defassert(:relative?, false, 'A:/')
+ defassert(:relative?, false, 'A:/a')
+ end
+
+ if File.dirname('//') == '//'
+ defassert(:relative?, false, '//')
+ defassert(:relative?, false, '//a')
+ defassert(:relative?, false, '//a/')
+ defassert(:relative?, false, '//a/b')
+ defassert(:relative?, false, '//a/b/')
+ defassert(:relative?, false, '//a/b/c')
+ end
+
+ def relative_path_from(dest_directory, base_directory)
+ Pathname.new(dest_directory).relative_path_from(Pathname.new(base_directory)).to_s
+ end
+
+ defassert(:relative_path_from, "../a", "a", "b")
+ defassert(:relative_path_from, "../a", "a", "b/")
+ defassert(:relative_path_from, "../a", "a/", "b")
+ defassert(:relative_path_from, "../a", "a/", "b/")
+ defassert(:relative_path_from, "../a", "/a", "/b")
+ defassert(:relative_path_from, "../a", "/a", "/b/")
+ defassert(:relative_path_from, "../a", "/a/", "/b")
+ defassert(:relative_path_from, "../a", "/a/", "/b/")
+
+ defassert(:relative_path_from, "../b", "a/b", "a/c")
+ defassert(:relative_path_from, "../a", "../a", "../b")
+
+ defassert(:relative_path_from, "a", "a", ".")
+ defassert(:relative_path_from, "..", ".", "a")
+
+ defassert(:relative_path_from, ".", ".", ".")
+ defassert(:relative_path_from, ".", "..", "..")
+ defassert(:relative_path_from, "..", "..", ".")
+
+ defassert(:relative_path_from, "c/d", "/a/b/c/d", "/a/b")
+ defassert(:relative_path_from, "../..", "/a/b", "/a/b/c/d")
+ defassert(:relative_path_from, "../../../../e", "/e", "/a/b/c/d")
+ defassert(:relative_path_from, "../b/c", "a/b/c", "a/d")
+
+ defassert(:relative_path_from, "../a", "/../a", "/b")
+ defassert(:relative_path_from, "../../a", "../a", "b")
+ defassert(:relative_path_from, ".", "/a/../../b", "/b")
+ defassert(:relative_path_from, "..", "a/..", "a")
+ defassert(:relative_path_from, ".", "a/../b", "b")
+
+ defassert(:relative_path_from, "a", "a", "b/..")
+ defassert(:relative_path_from, "b/c", "b/c", "b/..")
+
+ def self.defassert_raise(name, exc, *args)
+ define_assertion(name) {
+ message = "#{name}(#{args.map {|a| a.inspect }.join(', ')})"
+ assert_raise(exc, message) { self.send(name, *args) }
+ }
+ end
+
+ defassert_raise(:relative_path_from, ArgumentError, "/", ".")
+ defassert_raise(:relative_path_from, ArgumentError, ".", "/")
+ defassert_raise(:relative_path_from, ArgumentError, "a", "..")
+ defassert_raise(:relative_path_from, ArgumentError, ".", "..")
+
+ def realpath(path)
+ Pathname.new(path).realpath.to_s
+ end
+
+ def test_realpath
+ begin
+ File.symlink(nil, nil)
+ rescue NotImplementedError
+ return
+ rescue TypeError
+ end
+ dir = "#{Dir.tmpdir}/tst-pathname-#$$"
+ Dir.mkdir(dir)
+ begin
+ File.symlink("not-exist-target", "#{dir}/not-exist")
+ assert_raise(Errno::ENOENT) { realpath("#{dir}/not-exist") }
+ File.symlink("loop", "#{dir}/loop")
+ assert_raise(Errno::ELOOP) { realpath("#{dir}/loop") }
+ ensure
+ FileUtils.rmtree(dir)
+ end
+ end
+
+ def descend(path)
+ Pathname.new(path).enum_for(:descend).map {|v| v.to_s }
+ end
+
+ defassert(:descend, %w[/ /a /a/b /a/b/c], "/a/b/c")
+ defassert(:descend, %w[a a/b a/b/c], "a/b/c")
+ defassert(:descend, %w[. ./a ./a/b ./a/b/c], "./a/b/c")
+ defassert(:descend, %w[a/], "a/")
+
+ def ascend(path)
+ Pathname.new(path).enum_for(:ascend).map {|v| v.to_s }
+ end
+
+ defassert(:ascend, %w[/a/b/c /a/b /a /], "/a/b/c")
+ defassert(:ascend, %w[a/b/c a/b a], "a/b/c")
+ defassert(:ascend, %w[./a/b/c ./a/b ./a .], "./a/b/c")
+ defassert(:ascend, %w[a/], "a/")
+
+ def test_initialize
+ p1 = Pathname.new('a')
+ assert_equal('a', p1.to_s)
+ p2 = Pathname.new(p1)
+ assert_equal(p1, p2)
+ end
+
+ def test_initialize_nul
+ assert_raise(ArgumentError) { Pathname.new("a\0") }
+ end
+
+ class AnotherStringLike # :nodoc:
+ def initialize(s) @s = s end
+ def to_str() @s end
+ def ==(other) @s == other end
+ end
+
+ def test_equality
+ obj = Pathname.new("a")
+ str = "a"
+ sym = :a
+ ano = AnotherStringLike.new("a")
+ assert_equal(false, obj == str)
+ assert_equal(false, str == obj)
+ assert_equal(false, obj == ano)
+ assert_equal(false, ano == obj)
+ assert_equal(false, obj == sym)
+ assert_equal(false, sym == obj)
+
+ obj2 = Pathname.new("a")
+ assert_equal(true, obj == obj2)
+ assert_equal(true, obj === obj2)
+ assert_equal(true, obj.eql?(obj2))
+ end
+
+ def test_hashkey
+ h = {}
+ h[Pathname.new("a")] = 1
+ h[Pathname.new("a")] = 2
+ assert_equal(1, h.size)
+ end
+
+ def assert_pathname_cmp(e, s1, s2)
+ p1 = Pathname.new(s1)
+ p2 = Pathname.new(s2)
+ r = p1 <=> p2
+ assert(e == r,
+ "#{p1.inspect} <=> #{p2.inspect}: <#{e}> expected but was <#{r}>")
+ end
+ def test_comparison
+ assert_pathname_cmp( 0, "a", "a")
+ assert_pathname_cmp( 1, "b", "a")
+ assert_pathname_cmp(-1, "a", "b")
+ ss = %w(
+ a
+ a/
+ a/b
+ a.
+ a0
+ )
+ s1 = ss.shift
+ ss.each {|s2|
+ assert_pathname_cmp(-1, s1, s2)
+ s1 = s2
+ }
+ end
+
+ def test_comparison_string
+ assert_equal(nil, Pathname.new("a") <=> "a")
+ assert_equal(nil, "a" <=> Pathname.new("a"))
+ end
+
+ def pathsub(path, pat, repl) Pathname.new(path).sub(pat, repl).to_s end
+ defassert(:pathsub, "a.o", "a.c", /\.c\z/, ".o")
+
+ def root?(path)
+ Pathname.new(path).root?
+ end
+
+ defassert(:root?, true, "/")
+ defassert(:root?, true, "//")
+ defassert(:root?, true, "///")
+ defassert(:root?, false, "")
+ defassert(:root?, false, "a")
+
+ def test_destructive_update
+ path = Pathname.new("a")
+ path.to_s.replace "b"
+ assert_equal(Pathname.new("a"), path)
+ end
+
+ def test_null_character
+ assert_raise(ArgumentError) { Pathname.new("\0") }
+ end
+
+ def test_taint
+ obj = Pathname.new("a"); assert_same(obj, obj.taint)
+ obj = Pathname.new("a"); assert_same(obj, obj.untaint)
+
+ assert_equal(false, Pathname.new("a" ) .tainted?)
+ assert_equal(false, Pathname.new("a" ) .to_s.tainted?)
+ assert_equal(true, Pathname.new("a" ).taint .tainted?)
+ assert_equal(true, Pathname.new("a" ).taint.to_s.tainted?)
+ assert_equal(true, Pathname.new("a".taint) .tainted?)
+ assert_equal(true, Pathname.new("a".taint) .to_s.tainted?)
+ assert_equal(true, Pathname.new("a".taint).taint .tainted?)
+ assert_equal(true, Pathname.new("a".taint).taint.to_s.tainted?)
+
+ str = "a"
+ path = Pathname.new(str)
+ str.taint
+ assert_equal(false, path .tainted?)
+ assert_equal(false, path.to_s.tainted?)
+ end
+
+ def test_untaint
+ obj = Pathname.new("a"); assert_same(obj, obj.untaint)
+
+ assert_equal(false, Pathname.new("a").taint.untaint .tainted?)
+ assert_equal(false, Pathname.new("a").taint.untaint.to_s.tainted?)
+
+ str = "a".taint
+ path = Pathname.new(str)
+ str.untaint
+ assert_equal(true, path .tainted?)
+ assert_equal(true, path.to_s.tainted?)
+ end
+
+ def test_freeze
+ obj = Pathname.new("a"); assert_same(obj, obj.freeze)
+
+ assert_equal(false, Pathname.new("a" ) .frozen?)
+ assert_equal(false, Pathname.new("a".freeze) .frozen?)
+ assert_equal(true, Pathname.new("a" ).freeze .frozen?)
+ assert_equal(true, Pathname.new("a".freeze).freeze .frozen?)
+ assert_equal(false, Pathname.new("a" ) .to_s.frozen?)
+ assert_equal(false, Pathname.new("a".freeze) .to_s.frozen?)
+ assert_equal(false, Pathname.new("a" ).freeze.to_s.frozen?)
+ assert_equal(false, Pathname.new("a".freeze).freeze.to_s.frozen?)
+ end
+
+ def test_to_s
+ str = "a"
+ obj = Pathname.new(str)
+ assert_equal(str, obj.to_s)
+ assert_not_same(str, obj.to_s)
+ assert_not_same(obj.to_s, obj.to_s)
+ end
+
+ def test_kernel_open
+ count = 0
+ result = Kernel.open(Pathname.new(__FILE__)) {|f|
+ assert(File.identical?(__FILE__, f))
+ count += 1
+ 2
+ }
+ assert_equal(1, count)
+ assert_equal(2, result)
+ end
+
+ def test_each_filename
+ result = []
+ Pathname.new("/usr/bin/ruby").each_filename {|f| result << f }
+ assert_equal(%w[usr bin ruby], result)
+ end
+
+ def test_kernel_pathname
+ assert_equal(Pathname.new("a"), Pathname("a"))
+ end
+end
diff --git a/ruby_1_8_6/test/rdoc/parsers/test_parse_c.rb b/ruby_1_8_6/test/rdoc/parsers/test_parse_c.rb
new file mode 100644
index 0000000000..6157a9e1d4
--- /dev/null
+++ b/ruby_1_8_6/test/rdoc/parsers/test_parse_c.rb
@@ -0,0 +1,261 @@
+require 'stringio'
+require 'tempfile'
+require 'test/unit'
+require 'rdoc/parsers/parse_c'
+
+class RDoc::C_Parser
+ attr_accessor :classes
+
+ public :do_classes, :do_constants
+end
+
+class TestRdocC_Parser < Test::Unit::TestCase
+
+ def setup
+ @tempfile = Tempfile.new self.class.name
+ filename = @tempfile.path
+
+ @top_level = RDoc::TopLevel.new filename
+ @fn = filename
+ @options = Options.instance
+ @stats = RDoc::Stats.new
+
+ @progress = StringIO.new
+ end
+
+ def teardown
+ @tempfile.unlink
+ end
+
+ def test_do_classes_boot_class
+ content = <<-EOF
+/* Document-class: Foo
+ * this is the Foo boot class
+ */
+VALUE cFoo = boot_defclass("Foo", 0);
+ EOF
+
+ klass = util_get_class content, 'cFoo'
+ assert_equal " this is the Foo boot class\n ", klass.comment
+ end
+
+ def test_do_classes_class
+ content = <<-EOF
+/* Document-class: Foo
+ * this is the Foo class
+ */
+VALUE cFoo = rb_define_class("Foo", rb_cObject);
+ EOF
+
+ klass = util_get_class content, 'cFoo'
+ assert_equal " this is the Foo class\n ", klass.comment
+ end
+
+ def test_do_classes_class_under
+ content = <<-EOF
+/* Document-class: Kernel::Foo
+ * this is the Foo class under Kernel
+ */
+VALUE cFoo = rb_define_class_under(rb_mKernel, "Foo", rb_cObject);
+ EOF
+
+ klass = util_get_class content, 'cFoo'
+ assert_equal " this is the Foo class under Kernel\n ", klass.comment
+ end
+
+ def test_do_classes_module
+ content = <<-EOF
+/* Document-module: Foo
+ * this is the Foo module
+ */
+VALUE mFoo = rb_define_module("Foo");
+ EOF
+
+ klass = util_get_class content, 'mFoo'
+ assert_equal " this is the Foo module\n ", klass.comment
+ end
+
+ def test_do_classes_module_under
+ content = <<-EOF
+/* Document-module: Kernel::Foo
+ * this is the Foo module under Kernel
+ */
+VALUE mFoo = rb_define_module_under(rb_mKernel, "Foo");
+ EOF
+
+ klass = util_get_class content, 'mFoo'
+ assert_equal " this is the Foo module under Kernel\n ", klass.comment
+ end
+
+ def test_do_constants
+ content = <<-EOF
+#include <ruby.h>
+
+void Init_foo(){
+ VALUE cFoo = rb_define_class("Foo", rb_cObject);
+
+ /* 300: The highest possible score in bowling */
+ rb_define_const(cFoo, "PERFECT", INT2FIX(300));
+
+ /* Huzzah!: What you cheer when you roll a perfect game */
+ rb_define_const(cFoo, "CHEER", rb_str_new2("Huzzah!"));
+
+ /* TEST\:TEST: Checking to see if escaped semicolon works */
+ rb_define_const(cFoo, "TEST", rb_str_new2("TEST:TEST"));
+
+ /* \\: The file separator on MS Windows */
+ rb_define_const(cFoo, "MSEPARATOR", rb_str_new2("\\"));
+
+ /* /: The file separator on Unix */
+ rb_define_const(cFoo, "SEPARATOR", rb_str_new2("/"));
+
+ /* C:\\Program Files\\Stuff: A directory on MS Windows */
+ rb_define_const(cFoo, "STUFF", rb_str_new2("C:\\Program Files\\Stuff"));
+
+ /* Default definition */
+ rb_define_const(cFoo, "NOSEMI", INT2FIX(99));
+
+ rb_define_const(cFoo, "NOCOMMENT", rb_str_new2("No comment"));
+
+ /*
+ * Multiline comment goes here because this comment spans multiple lines.
+ * Multiline comment goes here because this comment spans multiple lines.
+ */
+ rb_define_const(cFoo, "MULTILINE", INT2FIX(1));
+
+ /*
+ * 1: Multiline comment goes here because this comment spans multiple lines.
+ * Multiline comment goes here because this comment spans multiple lines.
+ */
+ rb_define_const(cFoo, "MULTILINE_VALUE", INT2FIX(1));
+
+ /* Multiline comment goes here because this comment spans multiple lines.
+ * Multiline comment goes here because this comment spans multiple lines.
+ */
+ rb_define_const(cFoo, "MULTILINE_NOT_EMPTY", INT2FIX(1));
+
+}
+ EOF
+
+ parser = util_parser content
+
+ parser.do_classes
+ parser.do_constants
+
+ klass = parser.classes['cFoo']
+ assert klass
+
+ constants = klass.constants
+ assert !klass.constants.empty?
+
+ constants = constants.map { |c| [c.name, c.value, c.comment] }
+
+ assert_equal ['PERFECT', '300',
+ "\n The highest possible score in bowling \n "],
+ constants.shift
+ assert_equal ['CHEER', 'Huzzah!',
+ "\n What you cheer when you roll a perfect game \n "],
+ constants.shift
+ assert_equal ['TEST', 'TEST:TEST',
+ "\n Checking to see if escaped semicolon works \n "],
+ constants.shift
+ assert_equal ['MSEPARATOR', '\\',
+ "\n The file separator on MS Windows \n "],
+ constants.shift
+ assert_equal ['SEPARATOR', '/',
+ "\n The file separator on Unix \n "],
+ constants.shift
+ assert_equal ['STUFF', 'C:\\Program Files\\Stuff',
+ "\n A directory on MS Windows \n "],
+ constants.shift
+ assert_equal ['NOSEMI', 'INT2FIX(99)',
+ "\n Default definition \n "],
+ constants.shift
+ assert_equal ['NOCOMMENT', 'rb_str_new2("No comment")', nil],
+ constants.shift
+
+ comment = <<-EOF.chomp
+
+
+ Multiline comment goes here because this comment spans multiple lines.
+ Multiline comment goes here because this comment spans multiple lines.
+
+
+ EOF
+ assert_equal ['MULTILINE', 'INT2FIX(1)', comment], constants.shift
+ assert_equal ['MULTILINE_VALUE', '1', comment], constants.shift
+
+ comment = <<-EOF.chomp
+
+ Multiline comment goes here because this comment spans multiple lines.
+ Multiline comment goes here because this comment spans multiple lines.
+
+
+ EOF
+ assert_equal ['MULTILINE_NOT_EMPTY', 'INT2FIX(1)', comment], constants.shift
+
+ assert constants.empty?, constants.inspect
+ end
+
+ def test_find_class_comment_init
+ content = <<-EOF
+/*
+ * a comment for class Foo
+ */
+void
+Init_Foo(void) {
+ VALUE foo = rb_define_class("Foo", rb_cObject);
+}
+ EOF
+
+ klass = util_get_class content, 'foo'
+
+ assert_equal " \n a comment for class Foo\n \n", klass.comment
+ end
+
+ def test_find_class_comment_define_class
+ content = <<-EOF
+/*
+ * a comment for class Foo
+ */
+VALUE foo = rb_define_class("Foo", rb_cObject);
+ EOF
+
+ klass = util_get_class content, 'foo'
+
+ assert_equal " \n a comment for class Foo\n ", klass.comment
+ end
+
+ def test_find_class_comment_define_class
+ content = <<-EOF
+/*
+ * a comment for class Foo on Init
+ */
+void
+Init_Foo(void) {
+ /*
+ * a comment for class Foo on rb_define_class
+ */
+ VALUE foo = rb_define_class("Foo", rb_cObject);
+}
+ EOF
+
+ klass = util_get_class content, 'foo'
+
+ assert_equal " \n a comment for class Foo on Init\n \n", klass.comment
+ end
+
+ def util_get_class(content, name)
+ parser = util_parser content
+ parser.do_classes
+ parser.classes[name]
+ end
+
+ def util_parser(content)
+ parser = RDoc::C_Parser.new @top_level, @fn, content, @options, @stats
+ parser.progress = @progress
+ parser
+ end
+
+end
+
diff --git a/ruby_1_8_6/test/readline/test_readline.rb b/ruby_1_8_6/test/readline/test_readline.rb
new file mode 100644
index 0000000000..edc3aa09b9
--- /dev/null
+++ b/ruby_1_8_6/test/readline/test_readline.rb
@@ -0,0 +1,84 @@
+begin
+ require "readline"
+rescue LoadError
+end
+
+if defined?(Readline) && !/EditLine/n.match(Readline::VERSION)
+
+require "test/unit"
+require "tempfile"
+
+class TestReadline < Test::Unit::TestCase
+ def test_readline
+ stdin = Tempfile.new("test_readline_stdin")
+ stdout = Tempfile.new("test_readline_stdout")
+ begin
+ stdin.write("hello\n")
+ stdin.close
+ stdout.close
+ line = replace_stdio(stdin.path, stdout.path) {
+ Readline.readline("> ", true)
+ }
+ assert_equal("hello", line)
+ assert_equal(true, line.tainted?)
+ stdout.open
+ assert_equal("> ", stdout.read(2))
+ assert_equal(1, Readline::HISTORY.length)
+ assert_equal("hello", Readline::HISTORY[0])
+ assert_raises(SecurityError) do
+ Thread.start {
+ $SAFE = 1
+ replace_stdio(stdin.path, stdout.path) do
+ Readline.readline("> ".taint)
+ end
+ }.join
+ end
+ assert_raises(SecurityError) do
+ Thread.start {
+ $SAFE = 4
+ replace_stdio(stdin.path, stdout.path) { Readline.readline("> ") }
+ }.join
+ end
+ ensure
+ stdin.close(true)
+ stdout.close(true)
+ end
+ end
+
+ def test_completion_append_character
+ begin
+ Readline.completion_append_character = "x"
+ assert_equal("x", Readline.completion_append_character)
+ Readline.completion_append_character = "xyz"
+ assert_equal("x", Readline.completion_append_character)
+ Readline.completion_append_character = nil
+ assert_equal(nil, Readline.completion_append_character)
+ Readline.completion_append_character = ""
+ assert_equal(nil, Readline.completion_append_character)
+ rescue NotImplementedError
+ end
+ end
+
+ private
+
+ def replace_stdio(stdin_path, stdout_path)
+ open(stdin_path, "r"){|stdin|
+ open(stdout_path, "w"){|stdout|
+ orig_stdin = STDIN.dup
+ orig_stdout = STDOUT.dup
+ STDIN.reopen(stdin)
+ STDOUT.reopen(stdout)
+ begin
+ yield
+ ensure
+ STDIN.reopen(orig_stdin)
+ STDOUT.reopen(orig_stdout)
+ orig_stdin.close
+ orig_stdout.close
+ end
+ }
+ }
+ end
+end
+
+end
diff --git a/ruby_1_8_6/test/rinda/test_rinda.rb b/ruby_1_8_6/test/rinda/test_rinda.rb
new file mode 100644
index 0000000000..d663e0446d
--- /dev/null
+++ b/ruby_1_8_6/test/rinda/test_rinda.rb
@@ -0,0 +1,525 @@
+require 'test/unit'
+
+require 'drb/drb'
+require 'drb/eq'
+require 'rinda/tuplespace'
+
+require 'singleton'
+
+module Rinda
+
+class MockClock
+ include Singleton
+
+ class MyTS < Rinda::TupleSpace
+ def keeper
+ nil
+ end
+ end
+
+ def initialize
+ @now = 2
+ @reso = 0.1
+ @ts = MyTS.new
+ @ts.write([2, :now])
+ @inf = 2**31 - 1
+ end
+
+ def now
+ @now.to_f
+ end
+
+ def at(n)
+ n
+ end
+
+ def _forward(n=nil)
+ now ,= @ts.take([nil, :now])
+ @now = now + n
+ n = @reso if n.nil?
+ @ts.write([@now, :now])
+ end
+
+ def forward(n=nil)
+ while n > 0
+ _forward(@reso)
+ n -= @reso
+ end
+ end
+
+ def rewind
+ now ,= @ts.take([nil, :now])
+ @ts.write([@inf, :now])
+ @ts.take([nil, :now])
+ @now = 2
+ @ts.write([2, :now])
+ end
+
+ def sleep(n=nil)
+ while will_deadlock?
+ n -= @reso
+ forward
+ return 0 if n <= 0
+ end
+ now ,= @ts.read([nil, :now])
+ @ts.read([(now + n)..@inf, :now])
+ 0
+ end
+
+ def will_deadlock?
+ sz = Thread.current.group.list.find_all {|x| x.status != 'sleep'}.size
+ sz <= 1
+ end
+end
+
+module Time
+ def sleep(n)
+ @m.sleep(n)
+ end
+ module_function :sleep
+
+ def at(n)
+ n
+ end
+ module_function :at
+
+ def now
+ @m ? @m.now : 2
+ end
+ module_function :now
+
+ def rewind
+ @m.rewind
+ end
+ module_function :rewind
+
+ def forward(n)
+ @m.forward(n)
+ end
+ module_function :forward
+
+ @m = MockClock.instance
+end
+
+class TupleSpace
+ def sleep(n)
+ Time.sleep(n)
+ end
+end
+
+module TupleSpaceTestModule
+ def sleep(n)
+ if Thread.current == Thread.main
+ Time.forward(n)
+ else
+ Time.sleep(n)
+ end
+ end
+
+ def test_00_tuple
+ tuple = Rinda::TupleEntry.new([1,2,3])
+ assert(!tuple.canceled?)
+ assert(!tuple.expired?)
+ assert(tuple.alive?)
+ end
+
+ def test_00_template
+ tmpl = Rinda::Template.new([1,2,3])
+ assert_equal(3, tmpl.size)
+ assert_equal(3, tmpl[2])
+ assert(tmpl.match([1,2,3]))
+ assert(!tmpl.match([1,nil,3]))
+
+ tmpl = Rinda::Template.new([/^rinda/i, nil, :hello])
+ assert_equal(3, tmpl.size)
+ assert(tmpl.match(['Rinda', 2, :hello]))
+ assert(!tmpl.match(['Rinda', 2, Symbol]))
+ assert(!tmpl.match([1, 2, :hello]))
+ assert(tmpl.match([/^rinda/i, 2, :hello]))
+
+ tmpl = Rinda::Template.new([Symbol])
+ assert_equal(1, tmpl.size)
+ assert(tmpl.match([:hello]))
+ assert(tmpl.match([Symbol]))
+ assert(!tmpl.match(['Symbol']))
+
+ tmpl = Rinda::Template.new({"message"=>String, "name"=>String})
+ assert_equal(2, tmpl.size)
+ assert(tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
+ assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
+ assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
+ assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
+
+ assert_raises(Rinda::InvalidHashTupleKey) do
+ tmpl = Rinda::Template.new({:message=>String, "name"=>String})
+ end
+ tmpl = Rinda::Template.new({"name"=>String})
+ assert_equal(1, tmpl.size)
+ assert(tmpl.match({"name"=>"Foo"}))
+ assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
+ assert(!tmpl.match({"message"=>:symbol, "name"=>"Foo", "1"=>2}))
+ assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
+ assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
+
+ tmpl = Rinda::Template.new({"message"=>String, "name"=>String})
+ assert_equal(2, tmpl.size)
+ assert(tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
+ assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
+ assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
+ assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
+
+ tmpl = Rinda::Template.new({"message"=>String})
+ assert_equal(1, tmpl.size)
+ assert(tmpl.match({"message"=>"Hello"}))
+ assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
+ assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
+ assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
+ assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
+
+ tmpl = Rinda::Template.new({"message"=>String, "name"=>nil})
+ assert_equal(2, tmpl.size)
+ assert(tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
+ assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
+ assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
+ assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
+
+ assert_raises(Rinda::InvalidHashTupleKey) do
+ @ts.write({:message=>String, "name"=>String})
+ end
+
+ @ts.write([1, 2, 3])
+ assert_equal([1, 2, 3], @ts.take([1, 2, 3]))
+
+ @ts.write({'1'=>1, '2'=>2, '3'=>3})
+ assert_equal({'1'=>1, '2'=>2, '3'=>3}, @ts.take({'1'=>1, '2'=>2, '3'=>3}))
+
+ entry = @ts.write(['1'=>1, '2'=>2, '3'=>3])
+ assert_raises(Rinda::RequestExpiredError) do
+ assert_equal({'1'=>1, '2'=>2, '3'=>3}, @ts.read({'1'=>1}, 0))
+ end
+ entry.cancel
+ end
+
+ def test_00_DRbObject
+ ro = DRbObject.new(nil, "druby://host:1234")
+ tmpl = Rinda::DRbObjectTemplate.new
+ assert(tmpl === ro)
+
+ tmpl = Rinda::DRbObjectTemplate.new("druby://host:1234")
+ assert(tmpl === ro)
+
+ tmpl = Rinda::DRbObjectTemplate.new("druby://host:12345")
+ assert(!(tmpl === ro))
+
+ tmpl = Rinda::DRbObjectTemplate.new(/^druby:\/\/host:/)
+ assert(tmpl === ro)
+
+ ro = DRbObject.new_with(12345, 1234)
+ assert(!(tmpl === ro))
+
+ ro = DRbObject.new_with("druby://foo:12345", 1234)
+ assert(!(tmpl === ro))
+
+ tmpl = Rinda::DRbObjectTemplate.new(/^druby:\/\/(foo|bar):/)
+ assert(tmpl === ro)
+
+ ro = DRbObject.new_with("druby://bar:12345", 1234)
+ assert(tmpl === ro)
+
+ ro = DRbObject.new_with("druby://baz:12345", 1234)
+ assert(!(tmpl === ro))
+ end
+
+ def test_inp_rdp
+ assert_raises(Rinda::RequestExpiredError) do
+ @ts.take([:empty], 0)
+ end
+
+ assert_raises(Rinda::RequestExpiredError) do
+ @ts.read([:empty], 0)
+ end
+ end
+
+ def test_core_01
+ 5.times do |n|
+ @ts.write([:req, 2])
+ end
+
+ assert_equal([[:req, 2], [:req, 2], [:req, 2], [:req, 2], [:req, 2]],
+ @ts.read_all([nil, nil]))
+
+ taker = Thread.new do
+ s = 0
+ while true
+ begin
+ tuple = @ts.take([:req, Integer], 0.5)
+ assert_equal(2, tuple[1])
+ s += tuple[1]
+ rescue Rinda::RequestExpiredError
+ break
+ end
+ end
+ @ts.write([:ans, s])
+ s
+ end
+
+ sleep(20)
+ tuple = @ts.take([:ans, nil])
+ assert_equal(10, tuple[1])
+ assert_equal(10, taker.value)
+ end
+
+ def test_core_02
+ taker = Thread.new do
+ s = 0
+ while true
+ begin
+ tuple = @ts.take([:req, Integer], 1.0)
+ assert_equal(2, tuple[1])
+ s += tuple[1]
+ rescue Rinda::RequestExpiredError
+ break
+ end
+ end
+ @ts.write([:ans, s])
+ s
+ end
+
+ 5.times do |n|
+ @ts.write([:req, 2])
+ end
+
+ sleep(20)
+ tuple = @ts.take([:ans, nil])
+ assert_equal(10, tuple[1])
+ assert_equal(10, taker.value)
+ assert_equal([], @ts.read_all([nil, nil]))
+ end
+
+ def test_core_03_notify
+ notify1 = @ts.notify(nil, [:req, Integer])
+ notify2 = @ts.notify(nil, [:ans, Integer], 5)
+ notify3 = @ts.notify(nil, {"message"=>String, "name"=>String}, 5)
+
+ @ts.write({"message"=>"first", "name"=>"3"}, 3)
+ @ts.write({"message"=>"second", "name"=>"1"}, 1)
+ @ts.write({"message"=>"third", "name"=>"0"})
+ @ts.take({"message"=>"third", "name"=>"0"})
+
+ listener1 = Thread.new do
+ lv = 0
+ n = 0
+ notify1.each do |ev, tuple|
+ n += 1
+ if ev == 'write'
+ lv = lv + 1
+ elsif ev == 'take'
+ lv = lv - 1
+ else
+ break
+ end
+ assert(lv >= 0)
+ assert_equal([:req, 2], tuple)
+ end
+ [lv, n]
+ end
+
+ listener2 = Thread.new do
+ result = nil
+ lv = 0
+ n = 0
+ notify2.each do |ev|
+ n += 1
+ if ev[0] == 'write'
+ lv = lv + 1
+ elsif ev[0] == 'take'
+ lv = lv - 1
+ elsif ev[0] == 'close'
+ result = [lv, n]
+ else
+ break
+ end
+ assert(lv >= 0)
+ assert_equal([:ans, 10], ev[1])
+ end
+ result
+ end
+
+ taker = Thread.new do
+ s = 0
+ while true
+ begin
+ tuple = @ts.take([:req, Integer], 1.0)
+ s += tuple[1]
+ rescue Rinda::RequestExpiredError
+ break
+ end
+ end
+ @ts.write([:ans, s])
+ s
+ end
+
+ writer = Thread.new do
+ 5.times do |n|
+ @ts.write([:req, 2])
+ sleep 0.1
+ end
+ end
+
+ @ts.take({"message"=>"first", "name"=>"3"})
+
+ sleep(4)
+ tuple = @ts.take([:ans, nil])
+ assert_equal(10, tuple[1])
+ assert_equal(10, taker.value)
+ assert_equal([], @ts.read_all([nil, nil]))
+
+ notify1.cancel
+ sleep(3) # notify2 expired
+
+ assert_equal([0, 11], listener1.value)
+ assert_equal([0, 3], listener2.value)
+
+ ary = []
+ ary.push(["write", {"message"=>"first", "name"=>"3"}])
+ ary.push(["write", {"message"=>"second", "name"=>"1"}])
+ ary.push(["write", {"message"=>"third", "name"=>"0"}])
+ ary.push(["take", {"message"=>"third", "name"=>"0"}])
+ ary.push(["take", {"message"=>"first", "name"=>"3"}])
+ ary.push(["delete", {"message"=>"second", "name"=>"1"}])
+ ary.push(["close"])
+
+ notify3.each do |ev|
+ assert_equal(ary.shift, ev)
+ end
+ assert_equal([], ary)
+ end
+
+ def test_cancel_01
+ entry = @ts.write([:removeme, 1])
+ assert_equal([[:removeme, 1]], @ts.read_all([nil, nil]))
+ entry.cancel
+ assert_equal([], @ts.read_all([nil, nil]))
+
+ template = nil
+ taker = Thread.new do
+ @ts.take([:take, nil], 10) do |template|
+ Thread.new do
+ sleep 0.2
+ template.cancel
+ end
+ end
+ end
+
+ sleep(1)
+ assert(template.canceled?)
+
+ @ts.write([:take, 1])
+
+ assert_raises(Rinda::RequestCanceledError) do
+ assert_nil(taker.value)
+ end
+
+ assert_equal([[:take, 1]], @ts.read_all([nil, nil]))
+ end
+
+ def test_cancel_02
+ entry = @ts.write([:removeme, 1])
+ assert_equal([[:removeme, 1]], @ts.read_all([nil, nil]))
+ entry.cancel
+ assert_equal([], @ts.read_all([nil, nil]))
+
+ template = nil
+ reader = Thread.new do
+ @ts.read([:take, nil], 10) do |template|
+ Thread.new do
+ sleep 0.2
+ template.cancel
+ end
+ end
+ end
+
+ sleep(1)
+ assert(template.canceled?)
+
+ @ts.write([:take, 1])
+
+ assert_raises(Rinda::RequestCanceledError) do
+ assert_nil(reader.value)
+ end
+
+ assert_equal([[:take, 1]], @ts.read_all([nil, nil]))
+ end
+
+ class SimpleRenewer
+ def initialize(sec, n = 1)
+ @sec = sec
+ @n = n
+ end
+
+ def renew
+ return -1 if @n <= 0
+ @n -= 1
+ return @sec
+ end
+ end
+
+ def test_00_renewer
+ tuple = Rinda::TupleEntry.new([1,2,3], true)
+ assert(!tuple.canceled?)
+ assert(tuple.expired?)
+ assert(!tuple.alive?)
+
+ tuple = Rinda::TupleEntry.new([1,2,3], 1)
+ assert(!tuple.canceled?)
+ assert(!tuple.expired?)
+ assert(tuple.alive?)
+ sleep(2)
+ assert(tuple.expired?)
+ assert(!tuple.alive?)
+
+ tuple = Rinda::TupleEntry.new([1,2,3], SimpleRenewer.new(1,2))
+ assert(!tuple.canceled?)
+ assert(!tuple.expired?)
+ assert(tuple.alive?)
+ sleep(1.5)
+ assert(!tuple.canceled?)
+ assert(!tuple.expired?)
+ assert(tuple.alive?)
+ sleep(1.5)
+ assert(tuple.expired?)
+ assert(!tuple.alive?)
+ end
+end
+
+class TupleSpaceTest < Test::Unit::TestCase
+ include TupleSpaceTestModule
+
+ def setup
+ ThreadGroup.new.add(Thread.current)
+ @ts = Rinda::TupleSpace.new(1)
+ end
+end
+
+class TupleSpaceProxyTest < Test::Unit::TestCase
+ include TupleSpaceTestModule
+
+ def setup
+ ThreadGroup.new.add(Thread.current)
+ @ts_base = Rinda::TupleSpace.new(1)
+ @ts = Rinda::TupleSpaceProxy.new(@ts_base)
+ end
+
+ def test_remote_array_and_hash
+ @ts.write(DRbObject.new([1, 2, 3]))
+ assert_equal([1, 2, 3], @ts.take([1, 2, 3], 0))
+ @ts.write(DRbObject.new({'head' => 1, 'tail' => 2}))
+ assert_equal({'head' => 1, 'tail' => 2},
+ @ts.take({'head' => 1, 'tail' => 2}, 0))
+ end
+
+ @server = DRb.primary_server || DRb.start_service
+end
+
+end
+
diff --git a/ruby_1_8_6/test/rss/rss-assertions.rb b/ruby_1_8_6/test/rss/rss-assertions.rb
new file mode 100644
index 0000000000..1e926bb84d
--- /dev/null
+++ b/ruby_1_8_6/test/rss/rss-assertions.rb
@@ -0,0 +1,506 @@
+module Test
+ module Unit
+ module Assertions
+ # For backward compatibility
+ unless instance_methods.include?("assert_raise")
+ def assert_raise(*args, &block)
+ assert_raises(*args, &block)
+ end
+ end
+ end
+ end
+end
+
+module RSS
+ module Assertions
+
+ def assert_parse(rss, assert_method, *args)
+ __send__("assert_#{assert_method}", *args) do
+ ::RSS::Parser.parse(rss)
+ end
+ __send__("assert_#{assert_method}", *args) do
+ ::RSS::Parser.parse(rss, false).validate
+ end
+ end
+
+ def assert_ns(prefix, uri)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise NSError")
+ rescue ::RSS::NSError => e
+ assert_equal(prefix, e.prefix)
+ assert_equal(uri, e.uri)
+ end
+ end
+ end
+
+ def assert_missing_tag(tag, parent)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise MissingTagError")
+ rescue ::RSS::MissingTagError => e
+ assert_equal(tag, e.tag)
+ assert_equal(parent, e.parent)
+ end
+ end
+ end
+
+ def assert_too_much_tag(tag, parent)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise TooMuchTagError")
+ rescue ::RSS::TooMuchTagError => e
+ assert_equal(tag, e.tag)
+ assert_equal(parent, e.parent)
+ end
+ end
+ end
+
+ def assert_missing_attribute(tag, attrname)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise MissingAttributeError")
+ rescue ::RSS::MissingAttributeError => e
+ assert_equal(tag, e.tag)
+ assert_equal(attrname, e.attribute)
+ end
+ end
+ end
+
+ def assert_not_expected_tag(tag, uri, parent)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise NotExpectedTagError")
+ rescue ::RSS::NotExpectedTagError => e
+ assert_equal(tag, e.tag)
+ assert_equal(uri, e.uri)
+ assert_equal(parent, e.parent)
+ end
+ end
+ end
+
+ def assert_not_available_value(tag, value, attribute=nil)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise NotAvailableValueError")
+ rescue ::RSS::NotAvailableValueError => e
+ assert_equal(tag, e.tag)
+ assert_equal(value, e.value)
+ assert_equal(attribute, e.attribute)
+ end
+ end
+ end
+
+ def assert_not_set_error(name, variables)
+ _wrap_assertion do
+ begin
+ yield
+ flunk("Not raise NotSetError")
+ rescue ::RSS::NotSetError => e
+ assert_equal(name, e.name)
+ assert_equal(variables.sort, e.variables.sort)
+ end
+ end
+ end
+
+ def assert_xml_declaration(version, encoding, standalone, rss)
+ _wrap_assertion do
+ assert_equal(version, rss.version)
+ assert_equal(encoding, rss.encoding)
+ assert_equal(standalone, rss.standalone)
+ end
+ end
+
+ def assert_xml_stylesheet_attrs(attrs, xsl)
+ _wrap_assertion do
+ n_attrs = normalized_attrs(attrs)
+ ::RSS::XMLStyleSheet::ATTRIBUTES.each do |name|
+ assert_equal(n_attrs[name], xsl.__send__(name))
+ end
+ end
+ end
+
+ def assert_xml_stylesheet(target, attrs, xsl)
+ _wrap_assertion do
+ if attrs.has_key?(:href)
+ if !attrs.has_key?(:type) and attrs.has_key?(:guess_type)
+ attrs[:type] = attrs[:guess_type]
+ end
+ assert_equal("xml-stylesheet", target)
+ assert_xml_stylesheet_attrs(attrs, xsl)
+ else
+ assert_nil(target)
+ assert_equal("", xsl.to_s)
+ end
+ end
+ end
+
+ def assert_xml_stylesheet_pis(attrs_ary, rss=nil)
+ _wrap_assertion do
+ rss ||= ::RSS::RDF.new()
+ xss_strs = []
+ attrs_ary.each do |attrs|
+ xss = ::RSS::XMLStyleSheet.new(*attrs)
+ xss_strs.push(xss.to_s)
+ rss.xml_stylesheets.push(xss)
+ end
+ pi_str = rss.to_s.gsub(/<\?xml .*\n/, "").gsub(/\s*<[^\?].*\z/m, "")
+ assert_equal(xss_strs.join("\n"), pi_str)
+ end
+ end
+
+ def assert_xml_stylesheets(attrs, xss)
+ _wrap_assertion do
+ xss.each_with_index do |xs, i|
+ assert_xml_stylesheet_attrs(attrs[i], xs)
+ end
+ end
+ end
+
+
+ def assert_channel10(attrs, channel)
+ _wrap_assertion do
+ n_attrs = normalized_attrs(attrs)
+
+ names = %w(about title link description)
+ assert_attributes(attrs, names, channel)
+
+ %w(image items textinput).each do |name|
+ value = n_attrs[name]
+ if value
+ target = channel.__send__(name)
+ __send__("assert_channel10_#{name}", value, target)
+ end
+ end
+ end
+ end
+
+ def assert_channel10_image(attrs, image)
+ _wrap_assertion do
+ assert_attributes(attrs, %w(resource), image)
+ end
+ end
+
+ def assert_channel10_textinput(attrs, textinput)
+ _wrap_assertion do
+ assert_attributes(attrs, %w(resource), textinput)
+ end
+ end
+
+ def assert_channel10_items(attrs, items)
+ _wrap_assertion do
+ assert_equal(items.resources, items.Seq.lis.collect {|x| x.resource})
+ items.Seq.lis.each_with_index do |li, i|
+ assert_attributes(attrs[i], %w(resource), li)
+ end
+ end
+ end
+
+ def assert_image10(attrs, image)
+ _wrap_assertion do
+ names = %w(about title url link)
+ assert_attributes(attrs, names, image)
+ end
+ end
+
+ def assert_items10(attrs, items)
+ _wrap_assertion do
+ names = %w(about title link description)
+ items.each_with_index do |item, i|
+ assert_attributes(attrs[i], names, item)
+ end
+ end
+ end
+
+ def assert_textinput10(attrs, textinput)
+ _wrap_assertion do
+ names = %w(about title description name link)
+ assert_attributes(attrs, names, textinput)
+ end
+ end
+
+
+ def assert_channel09(attrs, channel)
+ _wrap_assertion do
+ n_attrs = normalized_attrs(attrs)
+
+ names = %w(title description link language rating
+ copyright pubDate lastBuildDate docs
+ managingEditor webMaster)
+ assert_attributes(attrs, names, channel)
+
+ %w(skipHours skipDays).each do |name|
+ value = n_attrs[name]
+ if value
+ target = channel.__send__(name)
+ __send__("assert_channel09_#{name}", value, target)
+ end
+ end
+ end
+ end
+
+ def assert_channel09_skipDays(contents, skipDays)
+ _wrap_assertion do
+ days = skipDays.days
+ contents.each_with_index do |content, i|
+ assert_equal(content, days[i].content)
+ end
+ end
+ end
+
+ def assert_channel09_skipHours(contents, skipHours)
+ _wrap_assertion do
+ hours = skipHours.hours
+ contents.each_with_index do |content, i|
+ assert_equal(content.to_i, hours[i].content)
+ end
+ end
+ end
+
+ def assert_image09(attrs, image)
+ _wrap_assertion do
+ names = %w(url link title description)
+ names << ["width", :integer]
+ names << ["height", :integer]
+ assert_attributes(attrs, names, image)
+ end
+ end
+
+ def assert_items09(attrs, items)
+ _wrap_assertion do
+ names = %w(title link description)
+ items.each_with_index do |item, i|
+ assert_attributes(attrs[i], names, item)
+ end
+ end
+ end
+
+ def assert_textinput09(attrs, textinput)
+ _wrap_assertion do
+ names = %w(title description name link)
+ assert_attributes(attrs, names, textinput)
+ end
+ end
+
+
+ def assert_channel20(attrs, channel)
+ _wrap_assertion do
+ n_attrs = normalized_attrs(attrs)
+
+ names = %w(title link description language copyright
+ managingEditor webMaster pubDate
+ lastBuildDate generator docs rating)
+ names << ["ttl", :integer]
+ assert_attributes(attrs, names, channel)
+
+ %w(cloud categories skipHours skipDays).each do |name|
+ value = n_attrs[name]
+ if value
+ target = channel.__send__(name)
+ __send__("assert_channel20_#{name}", value, target)
+ end
+ end
+ end
+ end
+
+ def assert_channel20_skipDays(contents, skipDays)
+ assert_channel09_skipDays(contents, skipDays)
+ end
+
+ def assert_channel20_skipHours(contents, skipHours)
+ assert_channel09_skipHours(contents, skipHours)
+ end
+
+ def assert_channel20_cloud(attrs, cloud)
+ _wrap_assertion do
+ names = %w(domain path registerProcedure protocol)
+ names << ["port", :integer]
+ assert_attributes(attrs, names, cloud)
+ end
+ end
+
+ def assert_channel20_categories(attrs, categories)
+ _wrap_assertion do
+ names = %w(domain content)
+ categories.each_with_index do |category, i|
+ assert_attributes(attrs[i], names, category)
+ end
+ end
+ end
+
+ def assert_image20(attrs, image)
+ _wrap_assertion do
+ names = %w(url link title description)
+ names << ["width", :integer]
+ names << ["height", :integer]
+ assert_attributes(attrs, names, image)
+ end
+ end
+
+ def assert_items20(attrs, items)
+ _wrap_assertion do
+ names = %w(about title link description)
+ items.each_with_index do |item, i|
+ assert_attributes(attrs[i], names, item)
+
+ n_attrs = normalized_attrs(attrs[i])
+
+ %w(source enclosure categories guid).each do |name|
+ value = n_attrs[name]
+ if value
+ target = item.__send__(name)
+ __send__("assert_items20_#{name}", value, target)
+ end
+ end
+ end
+ end
+ end
+
+ def assert_items20_source(attrs, source)
+ _wrap_assertion do
+ assert_attributes(attrs, %w(url content), source)
+ end
+ end
+
+ def assert_items20_enclosure(attrs, enclosure)
+ _wrap_assertion do
+ names = ["url", ["length", :integer], "type"]
+ assert_attributes(attrs, names, enclosure)
+ end
+ end
+
+ def assert_items20_categories(attrs, categories)
+ _wrap_assertion do
+ assert_channel20_categories(attrs, categories)
+ end
+ end
+
+ def assert_items20_guid(attrs, guid)
+ _wrap_assertion do
+ names = [["isPermaLink", :boolean], ["content"]]
+ assert_attributes(attrs, names, guid)
+ end
+ end
+
+ def assert_textinput20(attrs, textinput)
+ _wrap_assertion do
+ names = %w(title description name link)
+ assert_attributes(attrs, names, textinput)
+ end
+ end
+
+
+ def assert_dublin_core(elems, target)
+ _wrap_assertion do
+ elems.each do |name, value|
+ assert_equal(value, target.__send__("dc_#{name}"))
+ end
+ end
+ end
+
+ def assert_multiple_dublin_core(elems, target)
+ _wrap_assertion do
+ elems.each do |name, values, plural|
+ plural ||= "#{name}s"
+ actual = target.__send__("dc_#{plural}").collect{|x| x.value}
+ assert_equal(values, actual)
+ end
+ end
+ end
+
+ def assert_syndication(elems, target)
+ _wrap_assertion do
+ elems.each do |name, value|
+ meth = "sy_#{name}"
+ value = value.to_i if meth == "sy_updateFrequency"
+ assert_equal(value, target.__send__(meth ))
+ end
+ end
+ end
+
+ def assert_content(elems, target)
+ _wrap_assertion do
+ elems.each do |name, value|
+ assert_equal(value, target.__send__("content_#{name}"))
+ end
+ end
+ end
+
+ def assert_trackback(attrs, target)
+ _wrap_assertion do
+ n_attrs = normalized_attrs(attrs)
+ if n_attrs["ping"]
+ assert_equal(n_attrs["ping"], target.trackback_ping)
+ end
+ if n_attrs["abouts"]
+ n_attrs["abouts"].each_with_index do |about, i|
+ assert_equal(about, target.trackback_abouts[i].value)
+ end
+ end
+ end
+ end
+
+ def assert_taxo_topic(topics, target)
+ _wrap_assertion do
+ topics.each_with_index do |topic, i|
+ taxo_topic = target.taxo_topics[i]
+ topic.each do |name, value|
+ case name
+ when :link
+ assert_equal(value, taxo_topic.about)
+ assert_equal(value, taxo_topic.taxo_link)
+ when :topics
+ assert_equal(value, taxo_topic.taxo_topics.resources)
+ else
+ assert_equal(value, taxo_topic.__send__("dc_#{name}"))
+ end
+ end
+ end
+ end
+ end
+
+
+ def assert_attributes(attrs, names, target)
+ _wrap_assertion do
+ n_attrs = normalized_attrs(attrs)
+ names.each do |info|
+ if info.is_a?(String)
+ name = info
+ type = nil
+ else
+ name, type = info
+ end
+ value = n_attrs[name]
+ if value.is_a?(Time)
+ actual = target.__send__(name)
+ assert_instance_of(Time, actual)
+ assert_equal(value.to_i, actual.to_i)
+ elsif value
+ case type
+ when :integer
+ value = value.to_i
+ when :boolean
+ value = value == "true" if value.is_a?(String)
+ end
+ assert_equal(value, target.__send__(name))
+ end
+ end
+ end
+ end
+
+ def normalized_attrs(attrs)
+ n_attrs = {}
+ attrs.each do |name, value|
+ n_attrs[name.to_s] = value
+ end
+ n_attrs
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/rss-testcase.rb b/ruby_1_8_6/test/rss/rss-testcase.rb
new file mode 100644
index 0000000000..21670bc05c
--- /dev/null
+++ b/ruby_1_8_6/test/rss/rss-testcase.rb
@@ -0,0 +1,286 @@
+require "erb"
+
+require "test/unit"
+require 'rss-assertions'
+
+module RSS
+ class TestCase < Test::Unit::TestCase
+ include ERB::Util
+
+ include RSS
+ include Assertions
+
+ XMLDECL_VERSION = "1.0"
+ XMLDECL_ENCODING = "UTF-8"
+ XMLDECL_STANDALONE = "no"
+
+ RDF_ABOUT = "http://www.xml.com/xml/news.rss"
+ RDF_RESOURCE = "http://xml.com/universal/images/xml_tiny.gif"
+ TITLE_VALUE = "XML.com"
+ LINK_VALUE = "http://xml.com/pub"
+ URL_VALUE = "http://xml.com/universal/images/xml_tiny.gif"
+ NAME_VALUE = "hogehoge"
+ LANGUAGE_VALUE = "ja"
+ DESCRIPTION_VALUE = "
+ XML.com features a rich mix of information and services
+ for the XML community.
+ "
+ RESOURCES = [
+ "http://xml.com/pub/2000/08/09/xslt/xslt.html",
+ "http://xml.com/pub/2000/08/09/rdfdb/index.html",
+ ]
+
+ CLOUD_DOMAIN = "data.ourfavoritesongs.com"
+ CLOUD_PORT = "80"
+ CLOUD_PATH = "/RPC2"
+ CLOUD_REGISTER_PROCEDURE = "ourFavoriteSongs.rssPleaseNotify"
+ CLOUD_PROTOCOL = "xml-rpc"
+
+ ENCLOSURE_URL = "http://www.scripting.com/mp3s/weatherReportSuite.mp3"
+ ENCLOSURE_LENGTH = "12216320"
+ ENCLOSURE_TYPE = "audio/mpeg"
+
+ CATEGORY_DOMAIN = "http://www.superopendirectory.com/"
+
+ def default_test
+ # This class isn't tested
+ end
+
+ private
+ def make_xmldecl(v=XMLDECL_VERSION, e=XMLDECL_ENCODING, s=XMLDECL_STANDALONE)
+ rv = "<?xml version='#{v}'"
+ rv << " encoding='#{e}'" if e
+ rv << " standalone='#{s}'" if s
+ rv << "?>"
+ rv
+ end
+
+ def make_RDF(content=nil, xmlns=[])
+ <<-EORSS
+#{make_xmldecl}
+<rdf:RDF xmlns="#{URI}" xmlns:rdf="#{RDF::URI}"
+#{xmlns.collect {|pre, uri| "xmlns:#{pre}='#{uri}'"}.join(' ')}>
+#{block_given? ? yield : content}
+</rdf:RDF>
+EORSS
+ end
+
+ def make_channel(content=nil)
+ <<-EOC
+<channel rdf:about="#{RDF_ABOUT}">
+ <title>#{TITLE_VALUE}</title>
+ <link>#{LINK_VALUE}</link>
+ <description>#{DESCRIPTION_VALUE}</description>
+
+ <image rdf:resource="#{RDF_RESOURCE}" />
+
+ <items>
+ <rdf:Seq>
+#{RESOURCES.collect do |res| '<rdf:li resource="' + res + '" />' end.join("\n")}
+ </rdf:Seq>
+ </items>
+
+ <textinput rdf:resource="#{RDF_RESOURCE}" />
+
+#{block_given? ? yield : content}
+</channel>
+EOC
+ end
+
+ def make_image(content=nil)
+ <<-EOI
+<image rdf:about="#{RDF_ABOUT}">
+ <title>#{TITLE_VALUE}</title>
+ <url>#{URL_VALUE}</url>
+ <link>#{LINK_VALUE}</link>
+#{block_given? ? yield : content}
+</image>
+EOI
+ end
+
+ def make_item(content=nil)
+ <<-EOI
+<item rdf:about="#{RDF_ABOUT}">
+ <title>#{TITLE_VALUE}</title>
+ <link>#{LINK_VALUE}</link>
+ <description>#{DESCRIPTION_VALUE}</description>
+#{block_given? ? yield : content}
+</item>
+EOI
+ end
+
+ def make_textinput(content=nil)
+ <<-EOT
+<textinput rdf:about="#{RDF_ABOUT}">
+ <title>#{TITLE_VALUE}</title>
+ <description>#{DESCRIPTION_VALUE}</description>
+ <name>#{NAME_VALUE}</name>
+ <link>#{LINK_VALUE}</link>
+#{block_given? ? yield : content}
+</textinput>
+EOT
+ end
+
+ def make_sample_RDF
+ make_RDF(<<-EOR)
+#{make_channel}
+#{make_image}
+#{make_item}
+#{make_textinput}
+EOR
+ end
+
+ def make_rss20(content=nil, xmlns=[])
+ <<-EORSS
+#{make_xmldecl}
+<rss version="2.0"
+#{xmlns.collect {|pre, uri| "xmlns:#{pre}='#{uri}'"}.join(' ')}>
+#{block_given? ? yield : content}
+</rss>
+EORSS
+ end
+
+ def make_sample_items20
+ RESOURCES.collect do |res|
+ elems = ["<link>#{res}</link>"]
+ elems << "<title>title of #{res}</title>"
+ elems = elems.join("\n")
+ item = "<item>\n#{elems}\n</item>"
+ end.join("\n")
+ end
+
+ def make_channel20(content=nil)
+ <<-EOC
+<channel>
+ <title>#{TITLE_VALUE}</title>
+ <link>#{LINK_VALUE}</link>
+ <description>#{DESCRIPTION_VALUE}</description>
+ <language>#{LANGUAGE_VALUE}</language>
+
+ <image>
+ <url>#{RDF_RESOURCE}</url>
+ <title>#{TITLE_VALUE}</title>
+ <link>#{LINK_VALUE}</link>
+ </image>
+
+#{make_sample_items20}
+
+ <textInput>
+ <title>#{TITLE_VALUE}</title>
+ <description>#{DESCRIPTION_VALUE}</description>
+ <name>#{NAME_VALUE}</name>
+ <link>#{RDF_RESOURCE}</link>
+ </textInput>
+
+#{block_given? ? yield : content}
+</channel>
+EOC
+ end
+
+ def make_item20(content=nil)
+ <<-EOI
+<item>
+ <title>#{TITLE_VALUE}</title>
+ <link>#{LINK_VALUE}</link>
+ <description>#{DESCRIPTION_VALUE}</description>
+#{block_given? ? yield : content}
+</item>
+EOI
+ end
+
+ def make_cloud20
+ <<-EOC
+<cloud
+ domain="#{CLOUD_DOMAIN}"
+ port="#{CLOUD_PORT}"
+ path="#{CLOUD_PATH}"
+ registerProcedure="#{CLOUD_REGISTER_PROCEDURE}"
+ protocol="#{CLOUD_PROTOCOL}" />
+EOC
+ end
+
+ def make_sample_rss20
+ make_rss20(<<-EOR)
+#{make_channel20}
+EOR
+ end
+
+ def make_element(elem_name, attrs, contents)
+ attrs_str = attrs.collect do |name, value|
+ "#{h name}='#{h value}'"
+ end.join(" ")
+ contents_str = contents.collect do |name, value|
+ "#{Element::INDENT}<#{h name}>#{h value}</#{h name}>"
+ end.join("\n")
+
+ "<#{h elem_name} #{attrs_str}>\n#{contents_str}\n</#{h elem_name}>"
+ end
+
+ private
+ def setup_dummy_channel(maker)
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+
+ maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ end
+
+ def setup_dummy_image(maker)
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+
+ maker.channel.link = link if maker.channel.link.nil?
+
+ maker.image.title = title
+ maker.image.url = url
+ end
+
+ def setup_dummy_textinput(maker)
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com/search.cgi"
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+
+ def setup_dummy_item(maker)
+ title = "TITLE"
+ link = "http://hoge.com/"
+
+ item = maker.items.new_item
+ item.title = title
+ item.link = link
+ end
+
+ def setup_taxo_topic(target, topics)
+ topics.each do |topic|
+ taxo_topic = target.taxo_topics.new_taxo_topic
+ topic.each do |name, value|
+ case name
+ when :link
+ taxo_topic.taxo_link = value
+ when :topics
+ value.each do |t|
+ taxo_topic.taxo_topics << t
+ end
+ else
+ dc_elems = taxo_topic.__send__("dc_#{name}s")
+ dc_elem = dc_elems.__send__("new_#{name}")
+ dc_elem.value = value
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_1.0.rb b/ruby_1_8_6/test/rss/test_1.0.rb
new file mode 100644
index 0000000000..ff3c8a402e
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_1.0.rb
@@ -0,0 +1,249 @@
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+
+module RSS
+ class TestRSS10Core < TestCase
+
+ def setup
+ @rdf_prefix = "rdf"
+ @rdf_uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ @uri = "http://purl.org/rss/1.0/"
+ end
+
+ def test_RDF
+ version = "1.0"
+ encoding = "UTF-8"
+ standalone = false
+
+ rdf = RDF.new(version, encoding, standalone)
+
+ doc = REXML::Document.new(rdf.to_s(false))
+
+ xmldecl = doc.xml_decl
+
+ %w(version encoding).each do |x|
+ assert_equal(instance_eval(x), xmldecl.__send__(x))
+ end
+ assert_equal(standalone, !xmldecl.standalone.nil?)
+
+ assert_equal(@rdf_uri, doc.root.namespace)
+ end
+
+ def test_not_displayed_xml_stylesheets
+ rdf = RDF.new()
+ plain_rdf = rdf.to_s
+ 3.times do
+ rdf.xml_stylesheets.push(XMLStyleSheet.new)
+ assert_equal(plain_rdf, rdf.to_s)
+ end
+ end
+
+ def test_xml_stylesheets
+ [
+ [{:href => "a.xsl", :type => "text/xsl"}],
+ [
+ {:href => "a.xsl", :type => "text/xsl"},
+ {:href => "a.css", :type => "text/css"},
+ ],
+ ].each do |attrs_ary|
+ assert_xml_stylesheet_pis(attrs_ary)
+ end
+ end
+
+ def test_channel
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ resource = "http://hoge.com/hoge.png"
+ image = RDF::Channel::Image.new(resource)
+ items = RDF::Channel::Items.new
+ textinput = RDF::Channel::Textinput.new(resource)
+
+ channel = RDF::Channel.new(about)
+ %w(title link description image items textinput).each do |x|
+ channel.__send__("#{x}=", instance_eval(x))
+ end
+
+ doc = REXML::Document.new(make_RDF(channel.to_s))
+ c = doc.root.elements[1]
+
+ assert_equal(about, c.attributes["about"])
+ %w(title link description image textinput).each do |x|
+ elem = c.elements[x]
+ assert_equal(x, elem.name)
+ assert_equal(@uri, elem.namespace)
+ if x == "image" or x == "textinput"
+ excepted = resource
+ res = elem.attributes.get_attribute("resource")
+ assert_equal(@rdf_uri, res.namespace)
+ value = res.value
+ else
+ excepted = instance_eval(x)
+ value = elem.text
+ end
+ assert_equal(excepted, value)
+ end
+ assert_equal(@uri, c.elements["items"].namespace)
+ assert_equal("items", c.elements["items"].name)
+ end
+
+ def test_channel_image
+ resource = "http://hoge.com/hoge.png"
+ image = RDF::Channel::Image.new(resource)
+
+ doc = REXML::Document.new(make_RDF(image.to_s))
+ i = doc.root.elements[1]
+
+ assert_equal("image", i.name)
+ assert_equal(@uri, i.namespace)
+
+ res = i.attributes.get_attribute("resource")
+
+ assert_equal(@rdf_uri, res.namespace)
+ assert_equal(resource, res.value)
+ end
+
+ def test_channel_textinput
+ resource = "http://hoge.com/hoge.png"
+ textinput = RDF::Channel::Textinput.new(resource)
+
+ doc = REXML::Document.new(make_RDF(textinput.to_s))
+ t = doc.root.elements[1]
+
+ assert_equal("textinput", t.name)
+ assert_equal(@uri, t.namespace)
+
+ res = t.attributes.get_attribute("resource")
+
+ assert_equal(@rdf_uri, res.namespace)
+ assert_equal(resource, res.value)
+ end
+
+ def test_items
+ items = RDF::Channel::Items.new
+
+ doc = REXML::Document.new(make_RDF(items.to_s))
+ i = doc.root.elements[1]
+
+ assert_equal("items", i.name)
+ assert_equal(@uri, i.namespace)
+
+ assert_equal(1, i.elements.size)
+ assert_equal("Seq", i.elements[1].name)
+ assert_equal(@rdf_uri, i.elements[1].namespace)
+ end
+
+ def test_seq
+ seq = RDF::Seq.new
+
+ doc = REXML::Document.new(make_RDF(seq.to_s))
+ s = doc.root.elements[1]
+
+ assert_equal("Seq", s.name)
+ assert_equal(@rdf_uri, s.namespace)
+ end
+
+ def test_li
+ resource = "http://hoge.com/"
+ li = RDF::Li.new(resource)
+
+ doc = REXML::Document.new(make_RDF(li.to_s))
+ l = doc.root.elements[1]
+
+ assert_equal("li", l.name)
+ assert_equal(@rdf_uri, l.namespace(l.prefix))
+
+ res = l.attributes.get_attribute("resource")
+
+ assert_equal('', res.instance_eval("@prefix"))
+ assert_equal(resource, res.value)
+ end
+
+ def test_image
+ about = "http://hoge.com"
+ title = "fugafuga"
+ url = "http://hoge.com/hoge"
+ link = "http://hoge.com/fuga"
+
+ image = RDF::Image.new(about)
+ %w(title url link).each do |x|
+ image.__send__("#{x}=", instance_eval(x))
+ end
+
+ doc = REXML::Document.new(make_RDF(image.to_s))
+ i = doc.root.elements[1]
+
+ assert_equal(about, i.attributes["about"])
+ %w(title url link).each do |x|
+ elem = i.elements[x]
+ assert_equal(x, elem.name)
+ assert_equal(@uri, elem.namespace)
+ assert_equal(instance_eval(x), elem.text)
+ end
+ end
+
+ def test_item
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com/fuga"
+ description = "hogehogehoge"
+
+ item = RDF::Item.new(about)
+ %w(title link description).each do |x|
+ item.__send__("#{x}=", instance_eval(x))
+ end
+
+ doc = REXML::Document.new(make_RDF(item.to_s))
+ i = doc.root.elements[1]
+
+ assert_equal(about, i.attributes["about"])
+ %w(title link description).each do |x|
+ elem = i.elements[x]
+ assert_equal(x, elem.name)
+ assert_equal(@uri, elem.namespace)
+ assert_equal(instance_eval(x), elem.text)
+ end
+ end
+
+ def test_textinput
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com/fuga"
+ name = "foo"
+ description = "hogehogehoge"
+
+ textinput = RDF::Textinput.new(about)
+ %w(title link name description).each do |x|
+ textinput.__send__("#{x}=", instance_eval(x))
+ end
+
+ doc = REXML::Document.new(make_RDF(textinput.to_s))
+ t = doc.root.elements[1]
+
+ assert_equal(about, t.attributes["about"])
+ %w(title link name description).each do |x|
+ elem = t.elements[x]
+ assert_equal(x, elem.name)
+ assert_equal(@uri, elem.namespace)
+ assert_equal(instance_eval(x), elem.text)
+ end
+ end
+
+ def test_to_xml
+ rss = RSS::Parser.parse(make_sample_RDF)
+ assert_equal(rss.to_s, rss.to_xml)
+ assert_equal(rss.to_s, rss.to_xml("1.0"))
+ rss09 = rss.to_xml("0.91") do |maker|
+ maker.channel.language = "en-us"
+ end
+ rss09 = RSS::Parser.parse(rss09)
+ assert_equal("0.91", rss09.rss_version)
+ rss20 = RSS::Parser.parse(rss.to_xml("2.0"))
+ assert_equal("2.0", rss20.rss_version)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_2.0.rb b/ruby_1_8_6/test/rss/test_2.0.rb
new file mode 100644
index 0000000000..d39c297ab7
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_2.0.rb
@@ -0,0 +1,390 @@
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/2.0"
+
+module RSS
+ class TestRSS20Core < TestCase
+
+ def setup
+ @rss_version = "2.0"
+ end
+
+ def test_Rss
+ version = "1.0"
+ encoding = "UTF-8"
+ standalone = false
+
+ rss = Rss.new(@rss_version, version, encoding, standalone)
+
+ doc = REXML::Document.new(rss.to_s(false))
+
+ xmldecl = doc.xml_decl
+
+ %w(version encoding).each do |x|
+ assert_equal(instance_eval(x), xmldecl.__send__(x))
+ end
+ assert_equal(standalone, !xmldecl.standalone.nil?)
+
+ assert_equal("", doc.root.namespace)
+ assert_equal(@rss_version, doc.root.attributes["version"])
+ end
+
+ def test_not_displayed_xml_stylesheets
+ rss = Rss.new(@rss_version)
+ plain_rss = rss.to_s
+ 3.times do
+ rss.xml_stylesheets.push(XMLStyleSheet.new)
+ assert_equal(plain_rss, rss.to_s)
+ end
+ end
+
+ def test_xml_stylesheets
+ [
+ [{:href => "a.xsl", :type => "text/xsl"}],
+ [
+ {:href => "a.xsl", :type => "text/xsl"},
+ {:href => "a.css", :type => "text/css"},
+ ],
+ ].each do |attrs_ary|
+ assert_xml_stylesheet_pis(attrs_ary, Rss.new(@rss_version))
+ end
+ end
+
+ def test_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+
+ language = "en-us"
+ copyright = "Copyright 2002, Spartanburg Herald-Journal"
+ managingEditor = "geo@herald.com (George Matesky)"
+ webMaster = "betty@herald.com (Betty Guernsey)"
+ pubDate = Time.parse("Sat, 07 Sep 2002 00:00:01 GMT")
+ lastBuildDate = Time.parse("Sat, 07 Sep 2002 09:42:31 GMT")
+ categories = [
+ {
+ :content => "Newspapers",
+ },
+ {
+ :domain => "Syndic8",
+ :content => "1765",
+ }
+ ]
+ generator = "MightyInHouse Content System v2.3"
+ docs = "http://blogs.law.harvard.edu/tech/rss"
+
+ ttl = "60"
+
+ rating = '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))'
+
+ channel = Rss::Channel.new
+
+ elems = %w(title link description language copyright
+ managingEditor webMaster pubDate lastBuildDate
+ generator docs ttl rating)
+ elems.each do |x|
+ value = instance_eval(x)
+ value = value.rfc822 if %w(pubDate lastBuildDate).include?(x)
+ channel.__send__("#{x}=", value)
+ end
+ categories.each do |cat|
+ channel.categories << Rss::Channel::Category.new(cat[:domain],
+ cat[:content])
+ end
+
+ doc = REXML::Document.new(make_rss20(channel.to_s))
+ c = doc.root.elements[1]
+
+ elems.each do |x|
+ elem = c.elements[x]
+ assert_equal(x, elem.name)
+ assert_equal("", elem.namespace)
+ expected = instance_eval(x)
+ case x
+ when "pubDate", "lastBuildDate"
+ assert_equal(expected, Time.parse(elem.text))
+ when "ttl"
+ expected = channel.__send__(x)
+ assert_equal(expected, elem.text.to_i)
+ else
+ assert_equal(expected, elem.text)
+ end
+ end
+ categories.each_with_index do |cat, i|
+ cat = cat.dup
+ cat[:domain] ||= nil
+ category = c.elements["category[#{i+1}]"]
+ actual = {
+ :domain => category.attributes["domain"],
+ :content => category.text,
+ }
+ assert_equal(cat, actual)
+ end
+ end
+
+ def test_channel_cloud
+ cloud_params = {
+ :domain => "rpc.sys.com",
+ :port => "80",
+ :path => "/RPC2",
+ :registerProcedure => "myCloud.rssPleaseNotify",
+ :protocol => "xml-rpc",
+ }
+ cloud = Rss::Channel::Cloud.new(cloud_params[:domain],
+ cloud_params[:port],
+ cloud_params[:path],
+ cloud_params[:registerProcedure],
+ cloud_params[:protocol])
+ cloud_params[:port] = cloud.port
+
+ doc = REXML::Document.new(cloud.to_s)
+ cloud_elem = doc.root
+
+ actual = {}
+ cloud_elem.attributes.each do |name, value|
+ value = value.to_i if name == "port"
+ actual[name.intern] = value
+ end
+ assert_equal(cloud_params, actual)
+ end
+
+ def test_channel_image
+ image_params = {
+ :url => "http://hoge.com/hoge.png",
+ :title => "fugafuga",
+ :link => "http://hoge.com",
+ :width => "144",
+ :height => "400",
+ :description => "an image",
+ }
+ image = Rss::Channel::Image.new(image_params[:url],
+ image_params[:title],
+ image_params[:link],
+ image_params[:width],
+ image_params[:height],
+ image_params[:description])
+
+ doc = REXML::Document.new(image.to_s)
+ image_elem = doc.root
+
+ image_params.each do |name, value|
+ value = image.__send__(name)
+ actual = image_elem.elements[name.to_s].text
+ actual = actual.to_i if [:width, :height].include?(name)
+ assert_equal(value, actual)
+ end
+ end
+
+ def test_channel_textInput
+ textInput_params = {
+ :title => "fugafuga",
+ :description => "text hoge fuga",
+ :name => "hoge",
+ :link => "http://hoge.com",
+ }
+ textInput = Rss::Channel::TextInput.new(textInput_params[:title],
+ textInput_params[:description],
+ textInput_params[:name],
+ textInput_params[:link])
+
+ doc = REXML::Document.new(textInput.to_s)
+ input_elem = doc.root
+
+ textInput_params.each do |name, value|
+ actual = input_elem.elements[name.to_s].text
+ assert_equal(value, actual)
+ end
+ end
+
+ def test_channel_skip_days
+ skipDays_values = [
+ "Sunday",
+ "Monday",
+ ]
+ skipDays = Rss::Channel::SkipDays.new
+ skipDays_values.each do |value|
+ skipDays.days << Rss::Channel::SkipDays::Day.new(value)
+ end
+
+ doc = REXML::Document.new(skipDays.to_s)
+ days_elem = doc.root
+
+ skipDays_values.each_with_index do |value, i|
+ assert_equal(value, days_elem.elements[i + 1].text)
+ end
+ end
+
+ def test_channel_skip_hours
+ skipHours_values = [
+ "0",
+ "13",
+ ]
+ skipHours = Rss::Channel::SkipHours.new
+ skipHours_values.each do |value|
+ skipHours.hours << Rss::Channel::SkipHours::Hour.new(value)
+ end
+
+ doc = REXML::Document.new(skipHours.to_s)
+ hours_elem = doc.root
+
+ skipHours_values.each_with_index do |value, i|
+ expected = skipHours.hours[i].content
+ assert_equal(expected, hours_elem.elements[i + 1].text.to_i)
+ end
+ end
+
+ def test_item
+ title = "fugafuga"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+ author = "oprah@oxygen.net"
+ categories = [
+ {
+ :content => "Newspapers",
+ },
+ {
+ :domain => "Syndic8",
+ :content => "1765",
+ }
+ ]
+ comments = "http://www.myblog.org/cgi-local/mt/mt-comments.cgi?entry_id=290"
+ pubDate = Time.parse("Sat, 07 Sep 2002 00:00:01 GMT")
+
+ channel = Rss::Channel.new
+ item = Rss::Channel::Item.new
+ channel.items << item
+
+ elems = %w(title link description author comments pubDate)
+ elems.each do |x|
+ value = instance_eval(x)
+ value = value.rfc822 if x == "pubDate"
+ item.__send__("#{x}=", value)
+ end
+ categories.each do |cat|
+ item.categories << Rss::Channel::Category.new(cat[:domain],
+ cat[:content])
+ end
+
+ doc = REXML::Document.new(channel.to_s)
+ channel_elem = doc.root
+
+ item_elem = channel_elem.elements["item[1]"]
+ elems.each do |x|
+ elem = item_elem.elements[x]
+ assert_equal(x, elem.name)
+ assert_equal("", elem.namespace)
+ expected = instance_eval(x)
+ case x
+ when "pubDate"
+ assert_equal(expected, Time.parse(elem.text))
+ else
+ assert_equal(expected, elem.text)
+ end
+ end
+ categories.each_with_index do |cat, i|
+ cat = cat.dup
+ cat[:domain] ||= nil
+ category = item_elem.elements["category[#{i+1}]"]
+ actual = {
+ :domain => category.attributes["domain"],
+ :content => category.text,
+ }
+ assert_equal(cat, actual)
+ end
+ end
+
+ def test_item_enclosure
+ enclosure_params = {
+ :url => "http://www.scripting.com/mp3s/weatherReportSuite.mp3",
+ :length => "12216320",
+ :type => "audio/mpeg",
+ }
+
+ enclosure = Rss::Channel::Item::Enclosure.new(enclosure_params[:url],
+ enclosure_params[:length],
+ enclosure_params[:type])
+ enclosure_params[:length] = enclosure.length
+
+ doc = REXML::Document.new(enclosure.to_s)
+ enclosure_elem = doc.root
+
+ actual = {}
+ enclosure_elem.attributes.each do |name, value|
+ value = value.to_i if name == "length"
+ actual[name.intern] = value
+ end
+ assert_equal(enclosure_params, actual)
+ end
+
+ def test_item_guid
+ test_params = [
+ {
+ :content => "http://some.server.com/weblogItem3207",
+ },
+ {
+ :isPermaLink => "true",
+ :content => "http://inessential.com/2002/09/01.php#a2",
+ },
+ ]
+
+ test_params.each do |guid_params|
+ guid = Rss::Channel::Item::Guid.new(guid_params[:isPermaLink],
+ guid_params[:content])
+ if guid_params.has_key?(:isPermaLink)
+ guid_params[:isPermaLink] = guid.isPermaLink
+ end
+ if guid.isPermaLink.nil?
+ assert_equal(true, guid.PermaLink?)
+ else
+ assert_equal(guid.isPermaLink, guid.PermaLink?)
+ end
+
+ doc = REXML::Document.new(guid.to_s)
+ guid_elem = doc.root
+
+ actual = {}
+ actual[:content] = guid_elem.text if guid_elem.text
+ guid_elem.attributes.each do |name, value|
+ value = value == "true" if name == "isPermaLink"
+ actual[name.intern] = value
+ end
+ assert_equal(guid_params, actual)
+ end
+ end
+
+ def test_item_source
+ source_params = {
+ :url => "http://www.tomalak.org/links2.xml",
+ :content => "Tomalak's Realm",
+ }
+
+ source = Rss::Channel::Item::Source.new(source_params[:url],
+ source_params[:content])
+
+ doc = REXML::Document.new(source.to_s)
+ source_elem = doc.root
+
+ actual = {}
+ actual[:content] = source_elem.text
+ source_elem.attributes.each do |name, value|
+ actual[name.intern] = value
+ end
+ assert_equal(source_params, actual)
+ end
+
+ def test_to_xml
+ rss = RSS::Parser.parse(make_sample_rss20)
+ assert_equal(rss.to_s, rss.to_xml)
+ assert_equal(rss.to_s, rss.to_xml("2.0"))
+ rss09 = RSS::Parser.parse(rss.to_xml("0.91"))
+ assert_equal("0.91", rss09.rss_version)
+ rss10 = rss.to_xml("1.0") do |maker|
+ maker.channel.about = "http://www.example.com/index.rdf"
+ end
+ rss10 = RSS::Parser.parse(rss10)
+ assert_equal("1.0", rss10.rss_version)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_accessor.rb b/ruby_1_8_6/test/rss/test_accessor.rb
new file mode 100644
index 0000000000..ceb31fc9c2
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_accessor.rb
@@ -0,0 +1,103 @@
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/2.0"
+require "rss/syndication"
+require "rss/image"
+
+module RSS
+ class TestAccessor < TestCase
+ def test_date
+ channel = Rss::Channel.new
+ channel.pubDate = nil
+ assert_nil(channel.pubDate)
+
+ time = Time.now
+ channel.pubDate = time
+ assert_equal(time, channel.pubDate)
+
+ time = Time.parse(Time.now.rfc822)
+ channel.pubDate = time.rfc822
+ assert_equal(time, channel.pubDate)
+
+ time = Time.parse(Time.now.iso8601)
+ value = time.iso8601
+ assert_not_available_value("pubDate", value) do
+ channel.pubDate = value
+ end
+
+ channel.do_validate = false
+ time = Time.parse(Time.now.iso8601)
+ value = time.iso8601
+ channel.pubDate = value
+ assert_equal(time, channel.pubDate)
+
+ channel.pubDate = nil
+ assert_nil(channel.pubDate)
+ end
+
+ def test_integer
+ image_item = RDF::Item::ImageItem.new
+
+ image_item.width = nil
+ assert_nil(image_item.width)
+
+ width = 10
+ image_item.width = width
+ assert_equal(width, image_item.width)
+
+ width = 10.0
+ image_item.width = width
+ assert_equal(width, image_item.width)
+
+ width = "10"
+ image_item.width = width
+ assert_equal(width.to_i, image_item.width)
+
+ width = "10.0"
+ assert_not_available_value("image:width", width) do
+ image_item.width = width
+ end
+
+ image_item.do_validate = false
+ width = "10.0"
+ image_item.width = width
+ assert_equal(width.to_i, image_item.width)
+
+ image_item.width = nil
+ assert_nil(image_item.width)
+ end
+
+ def test_positive_integer
+ channel = RDF::Channel.new
+
+ channel.sy_updateFrequency = nil
+ assert_nil(channel.sy_updateFrequency)
+
+ freq = 10
+ channel.sy_updateFrequency = freq
+ assert_equal(freq, channel.sy_updateFrequency)
+
+ freq = 10.0
+ channel.sy_updateFrequency = freq
+ assert_equal(freq, channel.sy_updateFrequency)
+
+ freq = "10"
+ channel.sy_updateFrequency = freq
+ assert_equal(freq.to_i, channel.sy_updateFrequency)
+
+ freq = "10.0"
+ assert_not_available_value("sy:updateFrequency", freq) do
+ channel.sy_updateFrequency = freq
+ end
+
+ channel.do_validate = false
+ freq = "10.0"
+ channel.sy_updateFrequency = freq
+ assert_equal(freq.to_i, channel.sy_updateFrequency)
+
+ channel.sy_updateFrequency = nil
+ assert_nil(channel.sy_updateFrequency)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_content.rb b/ruby_1_8_6/test/rss/test_content.rb
new file mode 100644
index 0000000000..70d456fa2f
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_content.rb
@@ -0,0 +1,94 @@
+require "cgi"
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/content"
+
+module RSS
+ class TestContent < TestCase
+
+ def setup
+ @prefix = "content"
+ @uri = "http://purl.org/rss/1.0/modules/content/"
+
+ @parents = %w(item)
+
+ @elems = {
+ :encoded => "<em>ATTENTION</em>",
+ }
+
+ @content_nodes = @elems.collect do |name, value|
+ "<#{@prefix}:#{name}>#{CGI.escapeHTML(value.to_s)}</#{@prefix}:#{name}>"
+ end.join("\n")
+
+ @rss_source = make_RDF(<<-EOR, {@prefix => @uri})
+#{make_channel()}
+#{make_image()}
+#{make_item(@content_nodes)}
+#{make_textinput()}
+EOR
+
+ @rss = Parser.parse(@rss_source)
+ end
+
+ def test_parser
+
+ assert_nothing_raised do
+ Parser.parse(@rss_source)
+ end
+
+ @elems.each do |tag, value|
+ assert_too_much_tag(tag.to_s, "item") do
+ Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
+#{make_channel()}
+#{make_item(("<" + @prefix + ":" + tag.to_s + ">" +
+ CGI.escapeHTML(value.to_s) +
+ "</" + @prefix + ":" + tag.to_s + ">") * 2)}
+EOR
+ end
+ end
+
+ end
+
+ def test_accessor
+
+ new_value = {
+ :encoded => "<![CDATA[<it>hoge</it>]]>",
+ }
+
+ @elems.each do |name, value|
+ @parents.each do |parent|
+ meth = "#{RSS::CONTENT_PREFIX}_#{name}"
+ assert_equal(value, @rss.__send__(parent).__send__(meth))
+ @rss.__send__(parent).__send__("#{meth}=", new_value[name].to_s)
+ assert_equal(new_value[name], @rss.__send__(parent).__send__(meth))
+ end
+ end
+
+ end
+
+ def test_to_s
+ @elems.each do |name, value|
+ excepted = "<#{@prefix}:#{name}>#{CGI.escapeHTML(value)}</#{@prefix}:#{name}>"
+ @parents.each do |parent|
+ meth = "#{RSS::CONTENT_PREFIX}_#{name}_element"
+ assert_equal(excepted, @rss.__send__(parent).__send__(meth))
+ end
+ end
+
+ REXML::Document.new(@rss_source).root.each_element do |parent|
+ if @parents.include?(parent.name)
+ parent.each_element do |elem|
+ if elem.namespace == @uri
+ assert_equal(elem.text, @elems[elem.name.intern].to_s)
+ end
+ end
+ end
+ end
+
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_dublincore.rb b/ruby_1_8_6/test/rss/test_dublincore.rb
new file mode 100644
index 0000000000..e5a4919362
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_dublincore.rb
@@ -0,0 +1,189 @@
+require "cgi"
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/dublincore"
+
+module RSS
+ class TestDublinCore < TestCase
+
+ def setup
+ @prefix = "dc"
+ @uri = "http://purl.org/dc/elements/1.1/"
+
+ @parents = %w(channel image item textinput)
+
+ t = Time.iso8601("2000-01-01T12:00:05+00:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+
+ @elems = {
+ :title => "hoge",
+ :description =>
+ " XML is placing increasingly heavy loads on
+ the existing technical infrastructure of the Internet.",
+ :creator => "Rael Dornfest (mailto:rael@oreilly.com)",
+ :subject => "XML",
+ :publisher => "The O'Reilly Network",
+ :contributor => "hogehoge",
+ :type => "fugafuga",
+ :format => "hohoho",
+ :identifier => "fufufu",
+ :source => "barbar",
+ :language => "ja",
+ :relation => "cococo",
+ :rights => "Copyright (c) 2000 O'Reilly &amp; Associates, Inc.",
+ :date => t,
+ }
+
+ @dc_nodes = @elems.collect do |name, value|
+ "<#{@prefix}:#{name}>#{value}</#{@prefix}:#{name}>"
+ end.join("\n")
+
+ @rss_source = make_RDF(<<-EOR, {@prefix => @uri})
+#{make_channel(@dc_nodes)}
+#{make_image(@dc_nodes)}
+#{make_item(@dc_nodes)}
+#{make_textinput(@dc_nodes)}
+EOR
+
+ @rss = Parser.parse(@rss_source)
+ end
+
+ def test_parser
+ assert_nothing_raised do
+ Parser.parse(@rss_source)
+ end
+
+ @elems.each do |tag, value|
+ rss = nil
+ assert_nothing_raised do
+ rss = Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
+#{make_channel(("<" + @prefix + ":" + tag.to_s + ">" +
+ value.to_s +
+ "</" + @prefix + ":" + tag.to_s + ">") * 2)}
+#{make_item}
+EOR
+ end
+ plural_reader = "dc_#{tag}" + (tag == :rights ? "es" : "s")
+ values = rss.channel.__send__(plural_reader).collect do |x|
+ val = x.value
+ if val.kind_of?(String)
+ CGI.escapeHTML(val)
+ else
+ val
+ end
+ end
+ assert_equal([value, value], values)
+ end
+
+ end
+
+ def test_singular_accessor
+ new_value = "hoge"
+
+ @elems.each do |name, value|
+ @parents.each do |parent|
+ parsed_value = @rss.__send__(parent).__send__("dc_#{name}")
+ if parsed_value.kind_of?(String)
+ parsed_value = CGI.escapeHTML(parsed_value)
+ end
+ assert_equal(value, parsed_value)
+ if name == :date
+ t = Time.iso8601("2003-01-01T02:30:23+09:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+ @rss.__send__(parent).__send__("dc_#{name}=", t.iso8601)
+ assert_equal(t, @rss.__send__(parent).__send__("dc_#{name}"))
+ assert_equal(t, @rss.__send__(parent).date)
+
+ @rss.__send__(parent).date = value
+ assert_equal(value, @rss.__send__(parent).date)
+ assert_equal(value, @rss.__send__(parent).__send__("dc_#{name}"))
+ else
+ @rss.__send__(parent).__send__("dc_#{name}=", new_value)
+ assert_equal(new_value,
+ @rss.__send__(parent).__send__("dc_#{name}"))
+ end
+ end
+ end
+ end
+
+ def test_plural_accessor
+ new_value = "hoge"
+
+ @elems.each do |name, value|
+ @parents.each do |parent|
+ parsed_value = @rss.__send__(parent).__send__("dc_#{name}")
+ if parsed_value.kind_of?(String)
+ parsed_value = CGI.escapeHTML(parsed_value)
+ end
+ assert_equal(value, parsed_value)
+
+ plural_reader = "dc_#{name}" + (name == :rights ? "es" : "s")
+ klass_name = "DublinCore#{Utils.to_class_name(name.to_s)}"
+ klass = DublinCoreModel.const_get(klass_name)
+ if name == :date
+ t = Time.iso8601("2003-01-01T02:30:23+09:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+ elems = @rss.__send__(parent).__send__(plural_reader)
+ elems << klass.new(t.iso8601)
+ new_elems = @rss.__send__(parent).__send__(plural_reader)
+ values = new_elems.collect{|x| x.value}
+ assert_equal([@rss.__send__(parent).__send__("dc_#{name}"), t],
+ values)
+ else
+ elems = @rss.__send__(parent).__send__(plural_reader)
+ elems << klass.new(new_value)
+ new_elems = @rss.__send__(parent).__send__(plural_reader)
+ values = new_elems.collect{|x| x.value}
+ assert_equal([
+ @rss.__send__(parent).__send__("dc_#{name}"),
+ new_value
+ ],
+ values)
+ end
+ end
+ end
+ end
+
+ def test_to_s
+ @elems.each do |name, value|
+ excepted = "<#{@prefix}:#{name}>#{value}</#{@prefix}:#{name}>"
+ @parents.each do |parent|
+ assert_equal(excepted,
+ @rss.__send__(parent).__send__("dc_#{name}_elements"))
+ end
+
+ excepted = Array.new(2, excepted).join("\n")
+ @parents.each do |parent|
+ reader = "dc_#{name}" + (name == :rights ? "es" : "s")
+ elems = @rss.__send__(parent).__send__(reader)
+ klass_name = "DublinCore#{Utils.to_class_name(name.to_s)}"
+ klass = DublinCoreModel.const_get(klass_name)
+ elems << klass.new(@rss.__send__(parent).__send__("dc_#{name}"))
+ assert_equal(excepted,
+ @rss.__send__(parent).__send__("dc_#{name}_elements"))
+ end
+ end
+
+ REXML::Document.new(@rss_source).root.each_element do |parent|
+ if @parents.include?(parent.name)
+ parent.each_element do |elem|
+ if elem.namespace == @uri
+ assert_equal(CGI.escapeHTML(elem.text),
+ @elems[elem.name.intern].to_s)
+ end
+ end
+ end
+ end
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_image.rb b/ruby_1_8_6/test/rss/test_image.rb
new file mode 100644
index 0000000000..241fdafb7d
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_image.rb
@@ -0,0 +1,191 @@
+require "cgi"
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/image"
+
+module RSS
+ class TestImage < TestCase
+
+ def setup
+ @prefix = "image"
+ @uri = "http://web.resource.org/rss/1.0/modules/image/"
+
+ @favicon_attrs = {
+ "rdf:about" => "http://www.kuro5hin.org/favicon.ico",
+ "#{@prefix}:size" => "small",
+ }
+ @favicon_contents = {"dc:title" => "Kuro5hin",}
+ @items = [
+ [
+ {
+ "rdf:about" => "http://www.example.org/item.png",
+ "rdf:resource" => "http://www.example.org/item",
+ },
+ {
+ "dc:title" => "Example Image",
+ "#{@prefix}:width" => "100",
+ "#{@prefix}:height" => "65",
+ },
+ ],
+ [
+ {
+ "rdf:about" => "http://www.kuro5hin.org/images/topics/culture.jpg",
+ },
+ {
+ "dc:title" => "Culture",
+ "#{@prefix}:width" => "80",
+ "#{@prefix}:height" => "50",
+ },
+ ]
+ ]
+
+
+ @channel_nodes = make_element("#{@prefix}:favicon",
+ @favicon_attrs,
+ @favicon_contents)
+ items = ""
+ @items.each do |attrs, contents|
+ image_item = make_element("#{@prefix}:item", attrs, contents)
+ items << make_item(image_item)
+ end
+
+ @ns = {
+ @prefix => @uri,
+ DC_PREFIX => DC_URI,
+ }
+ @rss_source = make_RDF(<<-EOR, @ns)
+#{make_channel(@channel_nodes)}
+#{make_image}
+#{items}
+#{make_textinput}
+EOR
+
+ @rss = Parser.parse(@rss_source)
+ end
+
+ def test_parser
+ assert_nothing_raised do
+ Parser.parse(@rss_source)
+ end
+
+ assert_too_much_tag("favicon", "channel") do
+ Parser.parse(make_RDF(<<-EOR, @ns))
+#{make_channel(@channel_nodes * 2)}
+#{make_item}
+EOR
+ end
+ end
+
+ def test_favicon_accessor
+ favicon = @rss.channel.image_favicon
+ [
+ %w(about rdf:about http://example.com/favicon.ico),
+ %w(size image:size large),
+ %w(image_size image:size medium),
+ ].each do |name, full_name, new_value|
+ assert_equal(@favicon_attrs[full_name], favicon.__send__(name))
+ favicon.__send__("#{name}=", new_value)
+ assert_equal(new_value, favicon.__send__(name))
+ favicon.__send__("#{name}=", @favicon_attrs[full_name])
+ assert_equal(@favicon_attrs[full_name], favicon.__send__(name))
+ end
+
+ %w(small medium large).each do |value|
+ assert_nothing_raised do
+ favicon.size = value
+ favicon.image_size = value
+ end
+ end
+
+ %w(aaa AAA SMALL MEDIUM LARGE).each do |value|
+ args = ["#{@prefix}:favicon", value, "#{@prefix}:size"]
+ assert_not_available_value(*args) do
+ favicon.size = value
+ end
+ assert_not_available_value(*args) do
+ favicon.image_size = value
+ end
+ end
+
+ [
+ %w(dc_title dc:title sample-favicon),
+ ].each do |name, full_name, new_value|
+ assert_equal(@favicon_contents[full_name], favicon.__send__(name))
+ favicon.__send__("#{name}=", new_value)
+ assert_equal(new_value, favicon.__send__(name))
+ favicon.__send__("#{name}=", @favicon_contents[full_name])
+ assert_equal(@favicon_contents[full_name], favicon.__send__(name))
+ end
+ end
+
+ def test_item_accessor
+ @rss.items.each_with_index do |item, i|
+ image_item = item.image_item
+ attrs, contents = @items[i]
+ [
+ %w(about rdf:about http://example.com/image.png),
+ %w(resource rdf:resource http://example.com/),
+ ].each do |name, full_name, new_value|
+ assert_equal(attrs[full_name], image_item.__send__(name))
+ image_item.__send__("#{name}=", new_value)
+ assert_equal(new_value, image_item.__send__(name))
+ image_item.__send__("#{name}=", attrs[full_name])
+ assert_equal(attrs[full_name], image_item.__send__(name))
+ end
+
+ [
+ ["width", "image:width", "111"],
+ ["image_width", "image:width", "44"],
+ ["height", "image:height", "222"],
+ ["image_height", "image:height", "88"],
+ ].each do |name, full_name, new_value|
+ assert_equal(contents[full_name].to_i, image_item.__send__(name))
+ image_item.__send__("#{name}=", new_value)
+ assert_equal(new_value.to_i, image_item.__send__(name))
+ image_item.__send__("#{name}=", contents[full_name])
+ assert_equal(contents[full_name].to_i, image_item.__send__(name))
+ end
+
+ [
+ ["dc_title", "dc:title", "sample-image"],
+ ].each do |name, full_name, new_value|
+ assert_equal(contents[full_name], image_item.__send__(name))
+ image_item.__send__("#{name}=", new_value)
+ assert_equal(new_value, image_item.__send__(name))
+ image_item.__send__("#{name}=", contents[full_name])
+ assert_equal(contents[full_name], image_item.__send__(name))
+ end
+ end
+ end
+
+ def test_favicon_to_s
+ favicon = @rss.channel.image_favicon
+ expected = REXML::Document.new(make_element("#{@prefix}:favicon",
+ @favicon_attrs,
+ @favicon_contents))
+ actual = REXML::Document.new(favicon.to_s(false, ""))
+ assert_equal(expected.to_s, actual.to_s)
+ end
+
+ def test_item_to_s
+ @rss.items.each_with_index do |item, i|
+ attrs, contents = @items[i]
+ expected_s = make_element("#{@prefix}:item", attrs, contents)
+ expected = REXML::Document.new(expected_s)
+ actual = REXML::Document.new(item.image_item.to_s(false, ""))
+
+ assert_equal(expected[0].attributes, actual[0].attributes)
+
+ %w(image:height image:width dc:title).each do |name|
+ actual_target = actual.elements["//#{name}"]
+ expected_target = expected.elements["//#{name}"]
+ assert_equal(expected_target.to_s, actual_target.to_s)
+ end
+ end
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_inherit.rb b/ruby_1_8_6/test/rss/test_inherit.rb
new file mode 100644
index 0000000000..fc4bbbe76a
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_inherit.rb
@@ -0,0 +1,41 @@
+require "rss-testcase"
+
+require "rss/1.0"
+
+module RSS
+ class TestInherit < TestCase
+
+ class InheritedImage < RSS::RDF::Image
+ def self.indent_size; 1; end
+ def self.tag_name; 'image'; end
+ end
+
+ def setup
+ @rss = make_RDF(<<-EOR)
+#{make_channel}
+#{make_image}
+#{make_item}
+#{make_textinput}
+EOR
+ end
+
+ def test_inherit
+ rss = RSS::Parser.parse(@rss)
+ orig_image = rss.image
+ prefix = "[INHERIT]"
+ image = InheritedImage.new("#{prefix} #{orig_image.about}")
+ image.title = "#{prefix} #{orig_image.title}"
+ image.url = "#{prefix} #{orig_image.url}"
+ image.link = "#{prefix} #{orig_image.link}"
+ rss.image = image
+
+ new_rss = RSS::Parser.parse(rss.to_s)
+ new_image = new_rss.image
+ assert_equal("#{prefix} #{orig_image.about}", new_image.about)
+ assert_equal("#{prefix} #{orig_image.title}", new_image.title)
+ assert_equal("#{prefix} #{orig_image.url}", new_image.url)
+ assert_equal("#{prefix} #{orig_image.link}", new_image.link)
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_0.9.rb b/ruby_1_8_6/test/rss/test_maker_0.9.rb
new file mode 100644
index 0000000000..820d567289
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_0.9.rb
@@ -0,0 +1,399 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMaker09 < TestCase
+
+ def test_rss
+ rss = RSS::Maker.make("0.91")
+ assert_nil(rss)
+
+ rss = RSS::Maker.make("0.9") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert_equal("0.91", rss.rss_version)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert_equal("0.91", rss.rss_version)
+
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.encoding = "EUC-JP"
+ end
+ assert_equal("0.91", rss.rss_version)
+ assert_equal("EUC-JP", rss.encoding)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.standalone = "yes"
+ end
+ assert_equal("0.91", rss.rss_version)
+ assert_equal("yes", rss.standalone)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.encoding = "EUC-JP"
+ maker.standalone = "yes"
+ end
+ assert_equal("0.91", rss.rss_version)
+ assert_equal("EUC-JP", rss.encoding)
+ assert_equal("yes", rss.standalone)
+ end
+
+ def test_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+ copyright = "foo"
+ managingEditor = "bar"
+ webMaster = "web master"
+ rating = '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))'
+ docs = "http://foo.com/doc"
+ skipDays = [
+ "Sunday",
+ "Monday",
+ ]
+ skipHours = [
+ "0",
+ "13",
+ ]
+ pubDate = Time.now
+ lastBuildDate = Time.now
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ maker.channel.copyright = copyright
+ maker.channel.managingEditor = managingEditor
+ maker.channel.webMaster = webMaster
+ maker.channel.rating = rating
+ maker.channel.docs = docs
+ maker.channel.pubDate = pubDate
+ maker.channel.lastBuildDate = lastBuildDate
+
+ skipDays.each do |day|
+ maker.channel.skipDays.new_day do |new_day|
+ new_day.content = day
+ end
+ end
+ skipHours.each do |hour|
+ maker.channel.skipHours.new_hour do |new_hour|
+ new_hour.content = hour
+ end
+ end
+ end
+ channel = rss.channel
+
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert_equal(language, channel.language)
+ assert_equal(copyright, channel.copyright)
+ assert_equal(managingEditor, channel.managingEditor)
+ assert_equal(webMaster, channel.webMaster)
+ assert_equal(rating, channel.rating)
+ assert_equal(docs, channel.docs)
+ assert_equal(pubDate, channel.pubDate)
+ assert_equal(pubDate, channel.date)
+ assert_equal(lastBuildDate, channel.lastBuildDate)
+
+ skipDays.each_with_index do |day, i|
+ assert_equal(day, channel.skipDays.days[i].content)
+ end
+ skipHours.each_with_index do |hour, i|
+ assert_equal(hour.to_i, channel.skipHours.hours[i].content)
+ end
+
+ assert(channel.items.empty?)
+ assert_nil(channel.image)
+ assert_nil(channel.textInput)
+ end
+
+ def test_not_valid_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+
+ assert_not_set_error("maker.channel", %w(title)) do
+ RSS::Maker.make("0.91") do |maker|
+ # maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(link)) do
+ RSS::Maker.make("0.91") do |maker|
+ maker.channel.title = title
+ # maker.channel.link = link
+ maker.channel.link = nil
+ maker.channel.description = description
+ maker.channel.language = language
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(description)) do
+ RSS::Maker.make("0.91") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ # maker.channel.description = description
+ maker.channel.language = language
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(language)) do
+ RSS::Maker.make("0.91") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ # maker.channel.language = language
+ end
+ end
+ end
+
+ def test_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+ width = "144"
+ height = "400"
+ description = "an image"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ image = rss.image
+ assert_equal(title, image.title)
+ assert_equal(link, image.link)
+ assert_equal(url, image.url)
+ assert_equal(width.to_i, image.width)
+ assert_equal(height.to_i, image.height)
+ assert_equal(description, image.description)
+
+ assert_not_set_error("maker.channel", %w(description title language)) do
+ RSS::Maker.make("0.91") do |maker|
+ # setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ end
+ end
+
+ def test_not_valid_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+ width = "144"
+ height = "400"
+ description = "an image"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ # maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ assert_nil(rss.channel.image)
+
+ assert_not_set_error("maker.channel", %w(link)) do
+ RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ # maker.channel.link = link
+ maker.channel.link = nil
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ end
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ # maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ assert_nil(rss.channel.image)
+ end
+
+ def test_items
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert(rss.channel.items.empty?)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.items.new_item do |item|
+ item.title = title
+ item.link = link
+ # item.description = description
+ end
+ end
+ assert_equal(1, rss.channel.items.size)
+ item = rss.channel.items.first
+ assert_equal(title, item.title)
+ assert_equal(link, item.link)
+ assert_nil(item.description)
+
+
+ item_size = 5
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.do_sort = true
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.channel.items.each_with_index do |item, i|
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.do_sort = Proc.new do |x, y|
+ y.title[-1] <=> x.title[-1]
+ end
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.channel.items.reverse.each_with_index do |item, i|
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+ end
+
+ def test_textInput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ textInput = rss.channel.textInput
+ assert_equal(title, textInput.title)
+ assert_equal(description, textInput.description)
+ assert_equal(name, textInput.name)
+ assert_equal(link, textInput.link)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ # setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss)
+ end
+
+ def test_not_valid_textInput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ # maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ # maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ # maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ # maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_1.0.rb b/ruby_1_8_6/test/rss/test_maker_1.0.rb
new file mode 100644
index 0000000000..e15432146d
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_1.0.rb
@@ -0,0 +1,431 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMaker10 < TestCase
+
+ def test_rdf
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert_equal("1.0", rss.rss_version)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.encoding = "EUC-JP"
+ end
+ assert_equal("1.0", rss.rss_version)
+ assert_equal("EUC-JP", rss.encoding)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.standalone = "yes"
+ end
+ assert_equal("1.0", rss.rss_version)
+ assert_equal("yes", rss.standalone)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.encoding = "EUC-JP"
+ maker.standalone = "yes"
+ end
+ assert_equal("1.0", rss.rss_version)
+ assert_equal("EUC-JP", rss.encoding)
+ assert_equal("yes", rss.standalone)
+ end
+
+ def test_channel
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+
+ rss = RSS::Maker.make("1.0")
+ assert_nil(rss)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ end
+ channel = rss.channel
+ assert_equal(about, channel.about)
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert(channel.items.Seq.lis.empty?)
+ assert_nil(channel.image)
+ assert_nil(channel.textinput)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+
+ setup_dummy_image(maker)
+
+ setup_dummy_textinput(maker)
+ end
+ channel = rss.channel
+ assert_equal(about, channel.about)
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert(channel.items.Seq.lis.empty?)
+ assert_equal(rss.image.about, channel.image.resource)
+ assert_equal(rss.textinput.about, channel.textinput.resource)
+ end
+
+ def test_not_valid_channel
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+
+ assert_not_set_error("maker.channel", %w(about)) do
+ RSS::Maker.make("1.0") do |maker|
+ # maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(title)) do
+ RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ # maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(link)) do
+ RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ # maker.channel.link = link
+ maker.channel.description = description
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(description)) do
+ RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ # maker.channel.description = description
+ end
+ end
+ end
+
+
+ def test_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ end
+ image = rss.image
+ assert_equal(url, image.about)
+ assert_equal(url, rss.channel.image.resource)
+ assert_equal(title, image.title)
+ assert_equal(link, image.link)
+ assert_equal(url, image.url)
+
+ assert_not_set_error("maker.channel", %w(about title description)) do
+ RSS::Maker.make("1.0") do |maker|
+ # setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ end
+ end
+ end
+
+ def test_not_valid_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ # maker.image.url = url
+ maker.image.title = title
+ end
+ assert_nil(rss.channel.image)
+ assert_nil(rss.image)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.url = url
+ # maker.image.title = title
+ end
+ assert_nil(rss.channel.image)
+ assert_nil(rss.image)
+
+ assert_not_set_error("maker.channel", %w(link)) do
+ RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ # maker.channel.link = link
+ maker.channel.link = nil
+
+ maker.image.url = url
+ maker.image.title = title
+ end
+ end
+ end
+
+ def test_items
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert(rss.items.empty?)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.items.new_item do |item|
+ item.title = title
+ item.link = link
+ # item.description = description
+ end
+ end
+ assert_equal(1, rss.items.size)
+ item = rss.items.first
+ assert_equal(link, item.about)
+ assert_equal(title, item.title)
+ assert_equal(link, item.link)
+ assert_nil(item.description)
+
+
+ item_size = 5
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.do_sort = true
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.items.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.do_sort = Proc.new do |x, y|
+ y.title[-1] <=> x.title[-1]
+ end
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.items.reverse.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+
+ max_size = item_size / 2
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.max_size = max_size
+ end
+ assert_equal(max_size, rss.items.size)
+ rss.items.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+
+ max_size = 0
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.max_size = max_size
+ end
+ assert_equal(max_size, rss.items.size)
+
+ max_size = -2
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ maker.items.max_size = max_size
+ end
+ assert_equal(item_size + max_size + 1, rss.items.size)
+ rss.items.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+ end
+
+ def test_not_valid_items
+ title = "TITLE"
+ link = "http://hoge.com/"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.items.new_item do |item|
+ # item.title = title
+ item.link = link
+ end
+ end
+ assert(rss.items.empty?)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.items.new_item do |item|
+ item.title = title
+ # item.link = link
+ end
+ end
+ assert(rss.items.empty?)
+ end
+
+ def test_textinput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.link = link
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ end
+ textinput = rss.textinput
+ assert_equal(link, textinput.about)
+ assert_equal(link, rss.channel.textinput.resource)
+ assert_equal(title, textinput.title)
+ assert_equal(name, textinput.name)
+ assert_equal(description, textinput.description)
+ assert_equal(link, textinput.link)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ # setup_dummy_channel(maker)
+
+ maker.textinput.link = link
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ end
+ assert_nil(rss)
+ end
+
+ def test_not_valid_textinput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ # maker.textinput.link = link
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ end
+ assert_nil(rss.channel.textinput)
+ assert_nil(rss.textinput)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.link = link
+ # maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ end
+ assert_nil(rss.channel.textinput)
+ assert_nil(rss.textinput)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.link = link
+ maker.textinput.title = title
+ # maker.textinput.description = description
+ maker.textinput.name = name
+ end
+ assert_nil(rss.channel.textinput)
+ assert_nil(rss.textinput)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.link = link
+ maker.textinput.title = title
+ maker.textinput.description = description
+ # maker.textinput.name = name
+ end
+ assert_nil(rss.channel.textinput)
+ assert_nil(rss.textinput)
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_2.0.rb b/ruby_1_8_6/test/rss/test_maker_2.0.rb
new file mode 100644
index 0000000000..ec5f3abb8e
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_2.0.rb
@@ -0,0 +1,667 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMaker20 < TestCase
+
+ def test_rss
+ rss = RSS::Maker.make("2.0")
+ assert_nil(rss)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert_equal("2.0", rss.rss_version)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.encoding = "EUC-JP"
+ end
+ assert_equal("2.0", rss.rss_version)
+ assert_equal("EUC-JP", rss.encoding)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.standalone = "yes"
+ end
+ assert_equal("2.0", rss.rss_version)
+ assert_equal("yes", rss.standalone)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.encoding = "EUC-JP"
+ maker.standalone = "yes"
+ end
+ assert_equal("2.0", rss.rss_version)
+ assert_equal("EUC-JP", rss.encoding)
+ assert_equal("yes", rss.standalone)
+ end
+
+ def test_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+ copyright = "foo"
+ managingEditor = "bar"
+ webMaster = "web master"
+ rating = '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))'
+ docs = "http://foo.com/doc"
+ skipDays = [
+ "Sunday",
+ "Monday",
+ ]
+ skipHours = [
+ "0",
+ "13",
+ ]
+ pubDate = Time.now
+ lastBuildDate = Time.now
+ categories = [
+ "Nespapers",
+ "misc",
+ ]
+ generator = "RSS Maker"
+ ttl = "60"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ maker.channel.copyright = copyright
+ maker.channel.managingEditor = managingEditor
+ maker.channel.webMaster = webMaster
+ maker.channel.rating = rating
+ maker.channel.docs = docs
+ maker.channel.pubDate = pubDate
+ maker.channel.lastBuildDate = lastBuildDate
+
+ skipDays.each do |day|
+ maker.channel.skipDays.new_day do |new_day|
+ new_day.content = day
+ end
+ end
+ skipHours.each do |hour|
+ maker.channel.skipHours.new_hour do |new_hour|
+ new_hour.content = hour
+ end
+ end
+
+ categories.each do |category|
+ maker.channel.categories.new_category do |new_category|
+ new_category.content = category
+ end
+ end
+
+ maker.channel.generator = generator
+ maker.channel.ttl = ttl
+ end
+ channel = rss.channel
+
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert_equal(language, channel.language)
+ assert_equal(copyright, channel.copyright)
+ assert_equal(managingEditor, channel.managingEditor)
+ assert_equal(webMaster, channel.webMaster)
+ assert_equal(rating, channel.rating)
+ assert_equal(docs, channel.docs)
+ assert_equal(pubDate, channel.pubDate)
+ assert_equal(pubDate, channel.date)
+ assert_equal(lastBuildDate, channel.lastBuildDate)
+
+ skipDays.each_with_index do |day, i|
+ assert_equal(day, channel.skipDays.days[i].content)
+ end
+ skipHours.each_with_index do |hour, i|
+ assert_equal(hour.to_i, channel.skipHours.hours[i].content)
+ end
+
+ channel.categories.each_with_index do |category, i|
+ assert_equal(categories[i], category.content)
+ end
+
+ assert_equal(generator, channel.generator)
+ assert_equal(ttl.to_i, channel.ttl)
+
+ assert(channel.items.empty?)
+ assert_nil(channel.image)
+ assert_nil(channel.textInput)
+ end
+
+ def test_not_valid_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+
+ assert_not_set_error("maker.channel", %w(title)) do
+ RSS::Maker.make("2.0") do |maker|
+ # maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(link)) do
+ RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ # maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ end
+ end
+
+ assert_not_set_error("maker.channel", %w(description)) do
+ RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ # maker.channel.description = description
+ maker.channel.language = language
+ end
+ end
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ # maker.channel.language = language
+ end
+ assert_not_nil(rss)
+ end
+
+
+ def test_cloud
+ domain = "rpc.sys.com"
+ port = "80"
+ path = "/RPC2"
+ registerProcedure = "myCloud.rssPleaseNotify"
+ protocol = "xml-rpc"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.channel.cloud.domain = domain
+ maker.channel.cloud.port = port
+ maker.channel.cloud.path = path
+ maker.channel.cloud.registerProcedure = registerProcedure
+ maker.channel.cloud.protocol = protocol
+ end
+ cloud = rss.channel.cloud
+ assert_equal(domain, cloud.domain)
+ assert_equal(port.to_i, cloud.port)
+ assert_equal(path, cloud.path)
+ assert_equal(registerProcedure, cloud.registerProcedure)
+ assert_equal(protocol, cloud.protocol)
+ end
+
+ def test_not_valid_cloud
+ domain = "rpc.sys.com"
+ port = "80"
+ path = "/RPC2"
+ registerProcedure = "myCloud.rssPleaseNotify"
+ protocol = "xml-rpc"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ # maker.channel.cloud.domain = domain
+ maker.channel.cloud.port = port
+ maker.channel.cloud.path = path
+ maker.channel.cloud.registerProcedure = registerProcedure
+ maker.channel.cloud.protocol = protocol
+ end
+ assert_nil(rss.channel.cloud)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.channel.cloud.domain = domain
+ # maker.channel.cloud.port = port
+ maker.channel.cloud.path = path
+ maker.channel.cloud.registerProcedure = registerProcedure
+ maker.channel.cloud.protocol = protocol
+ end
+ assert_nil(rss.channel.cloud)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.channel.cloud.domain = domain
+ maker.channel.cloud.port = port
+ # maker.channel.cloud.path = path
+ maker.channel.cloud.registerProcedure = registerProcedure
+ maker.channel.cloud.protocol = protocol
+ end
+ assert_nil(rss.channel.cloud)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.channel.cloud.domain = domain
+ maker.channel.cloud.port = port
+ maker.channel.cloud.path = path
+ # maker.channel.cloud.registerProcedure = registerProcedure
+ maker.channel.cloud.protocol = protocol
+ end
+ assert_nil(rss.channel.cloud)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.channel.cloud.domain = domain
+ maker.channel.cloud.port = port
+ maker.channel.cloud.path = path
+ maker.channel.cloud.registerProcedure = registerProcedure
+ # maker.channel.cloud.protocol = protocol
+ end
+ assert_nil(rss.channel.cloud)
+ end
+
+
+ def test_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+ width = "144"
+ height = "400"
+ description = "an image"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ image = rss.image
+ assert_equal(title, image.title)
+ assert_equal(link, image.link)
+ assert_equal(url, image.url)
+ assert_equal(width.to_i, image.width)
+ assert_equal(height.to_i, image.height)
+ assert_equal(description, image.description)
+
+ assert_not_set_error("maker.channel", %w(title description)) do
+ RSS::Maker.make("2.0") do |maker|
+ # setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ end
+ end
+
+ def test_not_valid_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+ width = "144"
+ height = "400"
+ description = "an image"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ # maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ assert_nil(rss.image)
+
+ assert_not_set_error("maker.channel", %w(link)) do
+ RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ # maker.channel.link = link
+ maker.channel.link = nil
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ end
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ # maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+ assert_nil(rss.image)
+ end
+
+ def test_items
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+ author = "oprah@oxygen.net"
+ comments = "http://www.myblog.org/cgi-local/mt/mt-comments.cgi?entry_id=290"
+ pubDate = Time.now
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ end
+ assert(rss.channel.items.empty?)
+
+ item_size = 5
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ item.author = "#{author}#{i}"
+ item.comments = "#{comments}#{i}"
+ item.date = pubDate
+ end
+ end
+ maker.items.do_sort = true
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.channel.items.each_with_index do |item, i|
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ assert_equal("#{author}#{i}", item.author)
+ assert_equal("#{comments}#{i}", item.comments)
+ assert_equal(pubDate, item.pubDate)
+ assert_equal(pubDate, item.date)
+ end
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ item.author = "#{author}#{i}"
+ item.comments = "#{comments}#{i}"
+ item.date = pubDate
+ end
+ end
+ maker.items.do_sort = Proc.new do |x, y|
+ y.title[-1] <=> x.title[-1]
+ end
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.channel.items.reverse.each_with_index do |item, i|
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ assert_equal("#{author}#{i}", item.author)
+ assert_equal("#{comments}#{i}", item.comments)
+ assert_equal(pubDate, item.pubDate)
+ assert_equal(pubDate, item.date)
+ end
+ end
+
+ def test_guid
+ isPermaLink = "true"
+ content = "http://inessential.com/2002/09/01.php#a2"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ guid = maker.items.last.guid
+ guid.isPermaLink = isPermaLink
+ guid.content = content
+ end
+ guid = rss.channel.items.last.guid
+ assert_equal(isPermaLink == "true", guid.isPermaLink)
+ assert_equal(content, guid.content)
+ end
+
+ def test_not_valid_guid
+ content = "http://inessential.com/2002/09/01.php#a2"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ guid = maker.items.last.guid
+ # guid.content = content
+ end
+ assert_nil(rss.channel.items.last.guid)
+ end
+
+ def test_enclosure
+ url = "http://www.scripting.com/mp3s/weatherReportSuite.mp3"
+ length = "12216320"
+ type = "audio/mpeg"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ enclosure = maker.items.last.enclosure
+ enclosure.url = url
+ enclosure.length = length
+ enclosure.type = type
+ end
+ enclosure = rss.channel.items.last.enclosure
+ assert_equal(url, enclosure.url)
+ assert_equal(length.to_i, enclosure.length)
+ assert_equal(type, enclosure.type)
+ end
+
+ def test_not_valid_enclosure
+ url = "http://www.scripting.com/mp3s/weatherReportSuite.mp3"
+ length = "12216320"
+ type = "audio/mpeg"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ enclosure = maker.items.last.enclosure
+ # enclosure.url = url
+ enclosure.length = length
+ enclosure.type = type
+ end
+ assert_nil(rss.channel.items.last.enclosure)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ enclosure = maker.items.last.enclosure
+ enclosure.url = url
+ # enclosure.length = length
+ enclosure.type = type
+ end
+ assert_nil(rss.channel.items.last.enclosure)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ enclosure = maker.items.last.enclosure
+ enclosure.url = url
+ enclosure.length = length
+ # enclosure.type = type
+ end
+ assert_nil(rss.channel.items.last.enclosure)
+ end
+
+
+ def test_source
+ url = "http://static.userland.com/tomalak/links2.xml"
+ content = "Tomalak's Realm"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ source = maker.items.last.source
+ source.url = url
+ source.content = content
+ end
+ source = rss.channel.items.last.source
+ assert_equal(url, source.url)
+ assert_equal(content, source.content)
+ end
+
+ def test_not_valid_source
+ url = "http://static.userland.com/tomalak/links2.xml"
+ content = "Tomalak's Realm"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ source = maker.items.last.source
+ # source.url = url
+ source.content = content
+ end
+ assert_nil(rss.channel.items.last.source)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ source = maker.items.last.source
+ source.url = url
+ # source.content = content
+ end
+ assert_nil(rss.channel.items.last.source)
+ end
+
+ def test_category
+ domain = "http://www.fool.com/cusips"
+ content = "MSFT"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ maker.items.last.categories.new_category do |category|
+ category.domain = domain
+ category.content = content
+ end
+ end
+ category = rss.channel.items.last.categories.last
+ assert_equal(domain, category.domain)
+ assert_equal(content, category.content)
+ end
+
+ def test_not_valid_category
+ content = "Grateful Dead"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ setup_dummy_item(maker)
+
+ maker.items.last.categories.new_category do |category|
+ # category.content = content
+ end
+ end
+ assert(rss.channel.items.last.categories.empty?)
+ end
+
+ def test_textInput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ textInput = rss.channel.textInput
+ assert_equal(title, textInput.title)
+ assert_equal(description, textInput.description)
+ assert_equal(name, textInput.name)
+ assert_equal(link, textInput.link)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ # setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss)
+ end
+
+ def test_not_valid_textInput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ # maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ # maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ # maker.textinput.name = name
+ maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ # maker.textinput.link = link
+ end
+ assert_nil(rss.channel.textInput)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_content.rb b/ruby_1_8_6/test/rss/test_maker_content.rb
new file mode 100644
index 0000000000..c29d75a649
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_content.rb
@@ -0,0 +1,34 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerContent < TestCase
+
+ def setup
+ @uri = "http://purl.org/rss/1.0/modules/content/"
+
+ @elements = {
+ :encoded => "<em>ATTENTION</em>",
+ }
+ end
+
+ def test_rss10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ @elements.each do |name, value|
+ item.__send__("#{accessor_name(name)}=", value)
+ end
+ end
+ assert_content(@elements, rss.items.last)
+ end
+
+ private
+ def accessor_name(name)
+ "content_#{name}"
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_dc.rb b/ruby_1_8_6/test/rss/test_maker_dc.rb
new file mode 100644
index 0000000000..6266e953aa
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_dc.rb
@@ -0,0 +1,145 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerDublinCore < TestCase
+
+ def setup
+ @uri = "http://purl.org/dc/elements/1.1/"
+
+ t = Time.iso8601("2000-01-01T12:00:05+00:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+
+ @elements = {
+ :title => "hoge",
+ :description =>
+ " XML is placing increasingly heavy loads on
+ the existing technical infrastructure of the Internet.",
+ :creator => "Rael Dornfest (mailto:rael@oreilly.com)",
+ :subject => "XML",
+ :publisher => "The O'Reilly Network",
+ :contributor => "hogehoge",
+ :type => "fugafuga",
+ :format => "hohoho",
+ :identifier => "fufufu",
+ :source => "barbar",
+ :language => "ja",
+ :relation => "cococo",
+ :rights => "Copyright (c) 2000 O'Reilly &amp; Associates, Inc.",
+ :date => t,
+ }
+ end
+
+ def test_rss10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ set_elements(maker.channel)
+
+ setup_dummy_image(maker)
+ set_elements(maker.image)
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ @elements.each do |name, value|
+ item.__send__("#{accessor_name(name)}=", value)
+ end
+
+ setup_dummy_textinput(maker)
+ set_elements(maker.textinput)
+ end
+ assert_dublin_core(@elements, rss.channel)
+ assert_dublin_core(@elements, rss.image)
+ assert_dublin_core(@elements, rss.items.last)
+ assert_dublin_core(@elements, rss.textinput)
+ end
+
+ def test_rss10_multiple
+ elems = []
+ @elements.each do |name, value|
+ plural = name.to_s + (name == :rights ? "es" : "s")
+ values = [value]
+ if name == :date
+ values << value + 60
+ else
+ values << value * 2
+ end
+ elems << [name, values, plural]
+ end
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ set_multiple_elements(maker.channel, elems)
+
+ setup_dummy_image(maker)
+ set_multiple_elements(maker.image, elems)
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ elems.each do |name, values, plural|
+ dc_elems = item.__send__("dc_#{plural}")
+ values.each do |value|
+ dc_elems.__send__("new_#{name}") do |elem|
+ elem.value = value
+ end
+ end
+ end
+
+ setup_dummy_textinput(maker)
+ set_multiple_elements(maker.textinput, elems)
+ end
+ assert_multiple_dublin_core(elems, rss.channel)
+ assert_multiple_dublin_core(elems, rss.image)
+ assert_multiple_dublin_core(elems, rss.items.last)
+ assert_multiple_dublin_core(elems, rss.textinput)
+ end
+
+ def test_date
+ t1 = Time.iso8601("2000-01-01T12:00:05+00:00")
+ t2 = Time.iso8601("2005-01-01T12:00:05+00:00")
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.date = t1
+ maker.channel.dc_dates.new_date do |date|
+ date.value = t2
+ end
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ item.date = t2
+ item.dc_dates.new_date do |date|
+ date.value = t1
+ end
+ end
+ assert_equal([t1, t2], rss.channel.dc_dates.collect{|x| x.value})
+ assert_equal([t2, t1], rss.items.last.dc_dates.collect{|x| x.value})
+ end
+
+ private
+ def accessor_name(name)
+ "dc_#{name}"
+ end
+
+ def set_elements(target, elems=@elements)
+ elems.each do |name, value|
+ target.__send__("#{accessor_name(name)}=", value)
+ end
+ end
+
+ def set_multiple_elements(target, elems)
+ elems.each do |name, values, plural|
+ plural ||= "#{name}s"
+ dc_elems = target.__send__("dc_#{plural}")
+ values.each do |value|
+ dc_elems.__send__("new_#{name}") do |new_dc_elem|
+ new_dc_elem.value = value
+ end
+ end
+ end
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_image.rb b/ruby_1_8_6/test/rss/test_maker_image.rb
new file mode 100644
index 0000000000..1fc8076c46
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_image.rb
@@ -0,0 +1,62 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerImage < TestCase
+
+ def setup
+ @uri = "http://web.resource.org/rss/1.0/modules/image/"
+
+ @favicon_infos = {
+ "about" => "http://www.kuro5hin.org/favicon.ico",
+ "image_size" => "small",
+ "dc_title" => "example",
+ }
+ @item_infos = {
+ "about" => "http://www.example.org/item.png",
+ "resource" => "http://www.example.org/item",
+ "dc_title" => "Example Image",
+ "image_width" => "100",
+ "image_height" => "65",
+ }
+ end
+
+ def test_rss10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ @favicon_infos.each do |name, value|
+ maker.channel.image_favicon.__send__("#{name}=", value)
+ end
+
+ setup_dummy_image(maker)
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ @item_infos.each do |name, value|
+ item.image_item.__send__("#{name}=", value)
+ end
+
+ setup_dummy_textinput(maker)
+ end
+
+ setup_rss = RSS::Maker.make("1.0") do |maker|
+ rss.setup_maker(maker)
+ end
+
+ [rss, setup_rss].each_with_index do |target, i|
+ favicon = target.channel.image_favicon
+ assert_equal(@favicon_infos["about"], favicon.about)
+ assert_equal(@favicon_infos["image_size"], favicon.image_size)
+ assert_equal(@favicon_infos["dc_title"], favicon.dc_title)
+
+ item = target.items.last.image_item
+ assert_equal(@item_infos["about"], item.about)
+ assert_equal(@item_infos["resource"], item.resource)
+ assert_equal(@item_infos["image_width"].to_i, item.image_width)
+ assert_equal(@item_infos["image_height"].to_i, item.image_height)
+ assert_equal(@item_infos["dc_title"], item.dc_title)
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_sy.rb b/ruby_1_8_6/test/rss/test_maker_sy.rb
new file mode 100644
index 0000000000..fd6df9a0eb
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_sy.rb
@@ -0,0 +1,43 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerSyndication < TestCase
+
+ def setup
+ @uri = "http://purl.org/rss/1.0/modules/syndication/"
+
+ t = Time.iso8601("2000-01-01T12:00:05+00:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+
+ @elements = {
+ :updatePeriod => "hourly",
+ :updateFrequency => "2",
+ :updateBase => t,
+ }
+ end
+
+ def test_rss10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ set_elements(maker.channel)
+ end
+ assert_syndication(@elements, rss.channel)
+ end
+
+ private
+ def accessor_name(name)
+ "sy_#{name}"
+ end
+
+ def set_elements(target)
+ @elements.each do |name, value|
+ target.__send__("#{accessor_name(name)}=", value)
+ end
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_taxo.rb b/ruby_1_8_6/test/rss/test_maker_taxo.rb
new file mode 100644
index 0000000000..8feb4e1d33
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_taxo.rb
@@ -0,0 +1,81 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerTaxonomy < TestCase
+
+ def setup
+ @uri = "http://purl.org/rss/1.0/modules/taxonomy/"
+
+ @resources = [
+ "http://meerkat.oreillynet.com/?c=cat23",
+ "http://meerkat.oreillynet.com/?c=47",
+ "http://dmoz.org/Computers/Data_Formats/Markup_Languages/XML/",
+ ]
+
+ @topics = [
+ {
+ :link => "http://meerkat.oreillynet.com/?c=cat23",
+ :title => "Data: XML",
+ :description => "A Meerkat channel",
+ },
+ {
+ :link => "http://dmoz.org/Computers/Data_Formats/Markup_Languages/XML/",
+ :title => "XML",
+ :subject => "XML",
+ :description => "DMOZ category",
+ :topics => [
+ "http://meerkat.oreillynet.com/?c=cat23",
+ "http://dmoz.org/Computers/Data_Formats/Markup_Languages/SGML/",
+ "http://dmoz.org/Computers/Programming/Internet/",
+ ]
+ },
+ ]
+ end
+
+ def test_rss10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ set_topics(maker.channel)
+
+ setup_dummy_item(maker)
+ set_topics(maker.items.last)
+
+ setup_taxo_topic(maker, @topics)
+ end
+ assert_equal(@resources, rss.channel.taxo_topics.resources)
+ assert_equal(@resources, rss.items.last.taxo_topics.resources)
+ assert_taxo_topic(@topics, rss)
+ end
+
+ def _test_date
+ t1 = Time.iso8601("2000-01-01T12:00:05+00:00")
+ t2 = Time.iso8601("2005-01-01T12:00:05+00:00")
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.date = t1
+ maker.channel.dc_dates.new_date do |date|
+ date.value = t2
+ end
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ item.date = t2
+ item.dc_dates.new_date do |date|
+ date.value = t1
+ end
+ end
+ assert_equal([t1, t2], rss.channel.dc_dates.collect{|x| x.value})
+ assert_equal([t2, t1], rss.items.last.dc_dates.collect{|x| x.value})
+ end
+
+ private
+ def set_topics(target, resources=@resources)
+ resources.each do |value|
+ target.taxo_topics << value
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_trackback.rb b/ruby_1_8_6/test/rss/test_maker_trackback.rb
new file mode 100644
index 0000000000..58705c6f80
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_trackback.rb
@@ -0,0 +1,41 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerTrackBack < TestCase
+
+ def setup
+ @uri = "http://madskills.com/public/xml/rss/module/trackback/"
+
+ @elements = {
+ :ping => "http://bar.com/tb.cgi?tb_id=rssplustrackback",
+ :abouts => [
+ "http://foo.com/trackback/tb.cgi?tb_id=20020923",
+ "http://bar.com/trackback/tb.cgi?tb_id=20041114",
+ ],
+ }
+ end
+
+ def test_rss10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ setup_dummy_item(maker)
+ item = maker.items.last
+ item.trackback_ping = @elements[:ping]
+ @elements[:abouts].each do |about|
+ item.trackback_abouts.new_about do |new_about|
+ new_about.value = about
+ end
+ end
+ end
+ assert_trackback(@elements, rss.items.last)
+ end
+
+ private
+ def accessor_name(name)
+ "trackback_#{name}"
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_maker_xml-stylesheet.rb b/ruby_1_8_6/test/rss/test_maker_xml-stylesheet.rb
new file mode 100644
index 0000000000..c380f21dc3
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_maker_xml-stylesheet.rb
@@ -0,0 +1,79 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestMakerXMLStyleSheet < TestCase
+
+ def test_xml_stylesheet
+ href = 'a.xsl'
+ type = 'text/xsl'
+ title = 'sample'
+ media = 'printer'
+ charset = 'UTF-8'
+ alternate = 'yes'
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ xss.type = type
+ xss.title = title
+ xss.media = media
+ xss.charset = charset
+ xss.alternate = alternate
+ end
+
+ setup_dummy_channel(maker)
+ end
+
+ xss = rss.xml_stylesheets.first
+ assert_equal(href, xss.href)
+ assert_equal(type, xss.type)
+ assert_equal(title, xss.title)
+ assert_equal(media, xss.media)
+ assert_equal(charset, xss.charset)
+ assert_equal(alternate, xss.alternate)
+
+
+ href = 'http://example.com/index.xsl'
+ type = 'text/xsl'
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ end
+
+ setup_dummy_channel(maker)
+ end
+
+ xss = rss.xml_stylesheets.first
+ assert_equal(href, xss.href)
+ assert_equal(type, xss.type)
+ end
+
+ def test_not_valid_xml_stylesheet
+ href = 'xss.XXX'
+ type = "text/xsl"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ # xss.href = href
+ xss.type = type
+ end
+
+ setup_dummy_channel(maker)
+ end
+ assert(rss.xml_stylesheets.empty?)
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ # xss.type = type
+ end
+
+ setup_dummy_channel(maker)
+ end
+ assert(rss.xml_stylesheets.empty?)
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_parser.rb b/ruby_1_8_6/test/rss/test_parser.rb
new file mode 100644
index 0000000000..49b441bf96
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_parser.rb
@@ -0,0 +1,60 @@
+begin
+ require "fileutils"
+rescue LoadError
+ module FileUtils
+ module_function
+ def rm_f(target)
+ File.unlink(target)
+ rescue Errno::ENOENT
+ end
+ end
+end
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/dublincore"
+
+module RSS
+ class TestParser < TestCase
+ def setup
+ @_default_parser = Parser.default_parser
+ @rss10 = make_RDF(<<-EOR)
+#{make_channel}
+#{make_item}
+#{make_textinput}
+#{make_image}
+EOR
+ @rss_file = "rss10.rdf"
+ File.open(@rss_file, "w") {|f| f.print(@rss10)}
+ end
+
+ def teardown
+ Parser.default_parser = @_default_parser
+ FileUtils.rm_f(@rss_file)
+ end
+
+ def test_default_parser
+ assert_nothing_raised do
+ Parser.default_parser = RSS::AVAILABLE_PARSERS.first
+ end
+
+ assert_raise(RSS::NotValidXMLParser) do
+ Parser.default_parser = RSS::Parser
+ end
+ end
+
+ def test_parse
+ assert_not_nil(RSS::Parser.parse(@rss_file))
+
+ garbage_rss_file = @rss_file + "-garbage"
+ if RSS::Parser.default_parser.name == "RSS::XMLParserParser"
+ assert_raise(RSS::NotWellFormedError) do
+ RSS::Parser.parse(garbage_rss_file)
+ end
+ else
+ assert_nil(RSS::Parser.parse(garbage_rss_file))
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_parser_1.0.rb b/ruby_1_8_6/test/rss/test_parser_1.0.rb
new file mode 100644
index 0000000000..472602b04a
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_parser_1.0.rb
@@ -0,0 +1,503 @@
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/dublincore"
+
+module RSS
+ class TestParser10 < TestCase
+ def test_RDF
+ assert_ns("", RDF::URI) do
+ Parser.parse(<<-EOR)
+#{make_xmldecl}
+<RDF/>
+EOR
+ end
+
+ assert_ns("", RDF::URI) do
+ Parser.parse(<<-EOR)
+#{make_xmldecl}
+<RDF xmlns="hoge"/>
+EOR
+ end
+
+ assert_ns("rdf", RDF::URI) do
+ Parser.parse(<<-EOR)
+#{make_xmldecl}
+<rdf:RDF xmlns:rdf="hoge"/>
+EOR
+ end
+
+ assert_parse(<<-EOR, :missing_tag, "channel", "RDF")
+#{make_xmldecl}
+<rdf:RDF xmlns:rdf="#{RSS::RDF::URI}"/>
+EOR
+
+ assert_parse(<<-EOR, :missing_tag, "channel", "RDF")
+#{make_xmldecl}
+<RDF xmlns="#{RSS::RDF::URI}"/>
+EOR
+
+ assert_parse(<<-EOR, :missing_tag, "channel", "RDF")
+#{make_xmldecl}
+<RDF xmlns="#{RSS::RDF::URI}"/>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "item", "RDF")
+#{make_channel}
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "item", "RDF")
+#{make_channel}
+#{make_image}
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "item", "RDF")
+#{make_channel}
+#{make_textinput}
+EOR
+
+ assert_too_much_tag("image", "RDF") do
+ Parser.parse(make_RDF(<<-EOR))
+#{make_channel}
+#{make_image}
+#{make_image}
+#{make_item}
+#{make_textinput}
+EOR
+ end
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_item}
+#{make_image}
+#{make_textinput}
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_item}
+#{make_textinput}
+#{make_image}
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_image}
+#{make_item}
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_image}
+#{make_item}
+#{make_textinput}
+EOR
+
+ 1.step(15, 3) do |i|
+ rss = make_RDF() do
+ res = make_channel
+ i.times { res << make_item }
+ res
+ end
+ assert_parse(rss, :nothing_raised)
+ end
+ end
+
+ def test_undefined_entity
+ return unless RSS::Parser.default_parser.raise_for_undefined_entity?
+ assert_parse(make_RDF(<<-EOR), :raises, RSS::NotWellFormedError)
+#{make_channel}
+#{make_image}
+<item rdf:about="#{RDF_ABOUT}">
+ <title>#{TITLE_VALUE} &UNKNOWN_ENTITY;</title>
+ <link>#{LINK_VALUE}</link>
+ <description>#{DESCRIPTION_VALUE}</description>
+</item>
+#{make_textinput}
+EOR
+ end
+
+ def test_channel
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "channel", "rdf:about")
+<channel />
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "title", "channel")
+<channel rdf:about="http://example.com/"/>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "link", "channel")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+</channel>
+EOR
+
+ assert_parse(make_RDF(<<EOR), :missing_tag, "description", "channel")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+</channel>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "items", "channel")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+</channel>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "image", "rdf:resource")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image/>
+</channel>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "items", "channel")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image rdf:resource="http://example.com/hoge.png" />
+</channel>
+EOR
+
+ rss = make_RDF(<<-EOR)
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image rdf:resource="http://example.com/hoge.png" />
+ <items/>
+</channel>
+EOR
+
+ assert_missing_tag("Seq", "items") do
+ Parser.parse(rss)
+ end
+
+ assert_missing_tag("item", "RDF") do
+ Parser.parse(rss, false).validate
+ end
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "item", "RDF")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image rdf:resource="http://example.com/hoge.png" />
+ <items>
+ <rdf:Seq>
+ </rdf:Seq>
+ </items>
+</channel>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "textinput", "rdf:resource")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image rdf:resource="http://example.com/hoge.png" />
+ <items>
+ <rdf:Seq>
+ </rdf:Seq>
+ </items>
+ <textinput/>
+</channel>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "item", "RDF")
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image rdf:resource="http://example.com/hoge.png" />
+ <items>
+ <rdf:Seq>
+ </rdf:Seq>
+ </items>
+ <textinput rdf:resource="http://example.com/search" />
+</channel>
+EOR
+ end
+
+ def test_rdf_li
+ rss = make_RDF(<<-EOR)
+<channel rdf:about="http://example.com/">
+ <title>hoge</title>
+ <link>http://example.com/</link>
+ <description>hogehoge</description>
+ <image rdf:resource="http://example.com/hoge.png" />
+ <items>
+ <rdf:Seq>
+ <rdf:li \#{rdf_li_attr}/>
+ </rdf:Seq>
+ </items>
+ <textinput rdf:resource="http://example.com/search" />
+</channel>
+#{make_item}
+EOR
+
+ source = Proc.new do |rdf_li_attr|
+ eval(%Q[%Q[#{rss}]], binding)
+ end
+
+ attr = %q[resource="http://example.com/hoge"]
+ assert_parse(source.call(attr), :nothing_raised)
+
+ attr = %q[rdf:resource="http://example.com/hoge"]
+ assert_parse(source.call(attr), :nothing_raised)
+
+ assert_parse(source.call(""), :missing_attribute, "li", "resource")
+ end
+
+ def test_image
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "image", "rdf:about")
+#{make_channel}
+<image>
+</image>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "title", "image")
+#{make_channel}
+<image rdf:about="http://example.com/hoge.png">
+</image>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "url", "image")
+#{make_channel}
+<image rdf:about="http://example.com/hoge.png">
+ <title>hoge</title>
+</image>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "link", "image")
+#{make_channel}
+<image rdf:about="http://example.com/hoge.png">
+ <title>hoge</title>
+ <url>http://example.com/hoge.png</url>
+</image>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "item", "RDF")
+#{make_channel}
+<image rdf:about="http://example.com/hoge.png">
+ <title>hoge</title>
+ <url>http://example.com/hoge.png</url>
+ <link>http://example.com/</link>
+</image>
+EOR
+
+ rss = make_RDF(<<-EOR)
+#{make_channel}
+<image rdf:about="http://example.com/hoge.png">
+ <link>http://example.com/</link>
+ <url>http://example.com/hoge.png</url>
+ <title>hoge</title>
+</image>
+EOR
+
+ assert_missing_tag("item", "RDF") do
+ Parser.parse(rss)
+ end
+
+ assert_missing_tag("item", "RDF") do
+ Parser.parse(rss, false).validate
+ end
+ end
+
+ def test_item
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "item", "rdf:about")
+#{make_channel}
+#{make_image}
+<item>
+</item>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "title", "item")
+#{make_channel}
+#{make_image}
+<item rdf:about="http://example.com/hoge.html">
+</item>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "link", "item")
+#{make_channel}
+#{make_image}
+<item rdf:about="http://example.com/hoge.html">
+ <title>hoge</title>
+</item>
+EOR
+
+ assert_too_much_tag("title", "item") do
+ Parser.parse(make_RDF(<<-EOR))
+#{make_channel}
+#{make_image}
+<item rdf:about="http://example.com/hoge.html">
+ <title>hoge</title>
+ <title>hoge</title>
+ <link>http://example.com/hoge.html</link>
+</item>
+EOR
+ end
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_image}
+<item rdf:about="http://example.com/hoge.html">
+ <title>hoge</title>
+ <link>http://example.com/hoge.html</link>
+</item>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_image}
+<item rdf:about="http://example.com/hoge.html">
+ <title>hoge</title>
+ <link>http://example.com/hoge.html</link>
+ <description>hogehoge</description>
+</item>
+EOR
+ end
+
+ def test_textinput
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "textinput", "rdf:about")
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput>
+</textinput>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "title", "textinput")
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput rdf:about="http://example.com/search.html">
+</textinput>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "description", "textinput")
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput rdf:about="http://example.com/search.html">
+ <title>hoge</title>
+</textinput>
+EOR
+
+ assert_too_much_tag("title", "textinput") do
+ Parser.parse(make_RDF(<<-EOR))
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput rdf:about="http://example.com/search.html">
+ <title>hoge</title>
+ <title>hoge</title>
+ <description>hogehoge</description>
+</textinput>
+EOR
+ end
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "name", "textinput")
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput rdf:about="http://example.com/search.html">
+ <title>hoge</title>
+ <description>hogehoge</description>
+</textinput>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :missing_tag, "link", "textinput")
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput rdf:about="http://example.com/search.html">
+ <title>hoge</title>
+ <description>hogehoge</description>
+ <name>key</name>
+</textinput>
+EOR
+
+ assert_parse(make_RDF(<<-EOR), :nothing_raised)
+#{make_channel}
+#{make_image}
+#{make_item}
+<textinput rdf:about="http://example.com/search.html">
+ <title>hoge</title>
+ <description>hogehoge</description>
+ <name>key</name>
+ <link>http://example.com/search.html</link>
+</textinput>
+EOR
+ end
+
+ def test_ignore
+ name = "a"
+ rss = make_RDF(<<-EOR)
+#{make_channel}
+#{make_item}
+<#{name}/>
+EOR
+ assert_not_expected_tag(name, ::RSS::URI, "RDF") do
+ Parser.parse(rss, true, false)
+ end
+
+ uri = ""
+ name = "a"
+ rss = make_RDF(<<-EOR)
+#{make_channel}
+#{make_item}
+<#{name} xmlns=""/>
+EOR
+ assert_parse(rss, :nothing_raised)
+ assert_not_expected_tag(name, uri, "RDF") do
+ Parser.parse(rss, true, false)
+ end
+
+ uri = "http://example.com/"
+ name = "a"
+ rss = make_RDF(<<-EOR)
+#{make_channel}
+#{make_item}
+<x:#{name} xmlns:x="#{uri}"/>
+EOR
+ assert_parse(rss, :nothing_raised)
+ assert_not_expected_tag(name, uri, "RDF") do
+ Parser.parse(rss, true, false)
+ end
+
+ uri = ::RSS::URI
+ name = "a"
+ rss = make_RDF(<<-EOR)
+#{make_channel}
+#{make_item}
+#{make_image("<#{name}/>")}
+EOR
+ assert_parse(rss, :nothing_raised)
+ assert_not_expected_tag(name, uri, "image") do
+ Parser.parse(rss, true, false)
+ end
+
+ uri = CONTENT_URI
+ name = "encoded"
+ elem = "<#{name} xmlns='#{uri}'/>"
+ rss = make_RDF(<<-EOR)
+#{make_channel}
+#{make_item}
+#{make_image(elem)}
+EOR
+ assert_parse(rss, :nothing_raised)
+ assert_not_expected_tag(name, uri, "image") do
+ Parser.parse(rss, true, false)
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/rss/test_parser_2.0.rb b/ruby_1_8_6/test/rss/test_parser_2.0.rb
new file mode 100644
index 0000000000..249347d3dc
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_parser_2.0.rb
@@ -0,0 +1,122 @@
+require "rss-testcase"
+
+require "rss/2.0"
+
+module RSS
+ class TestParser20 < TestCase
+ def test_rss20
+ assert_parse(make_rss20(<<-EOR), :missing_tag, "channel", "rss")
+EOR
+
+ assert_parse(make_rss20(<<-EOR), :nothing_raised)
+#{make_channel20("")}
+EOR
+ end
+
+ def test_cloud20
+ attrs = [
+ ["domain", CLOUD_DOMAIN],
+ ["port", CLOUD_PORT],
+ ["path", CLOUD_PATH],
+ ["registerProcedure", CLOUD_REGISTER_PROCEDURE],
+ ["protocol", CLOUD_PROTOCOL],
+ ]
+
+ (attrs.size + 1).times do |i|
+ missing_attr = attrs[i]
+ if missing_attr
+ meth = :missing_attribute
+ args = ["cloud", missing_attr[0]]
+ else
+ meth = :nothing_raised
+ args = []
+ end
+
+ cloud_attrs = []
+ attrs.each_with_index do |attr, j|
+ unless i == j
+ cloud_attrs << %Q[#{attr[0]}="#{attr[1]}"]
+ end
+ end
+
+ assert_parse(make_rss20(<<-EOR), meth, *args)
+#{make_channel20(%Q[<cloud #{cloud_attrs.join("\n")}/>])}
+EOR
+ end
+ end
+
+ def test_source20
+ assert_parse(make_rss20(<<-EOR), :missing_attribute, "source", "url")
+#{make_channel20(make_item20(%Q[<source>Example</source>]))}
+EOR
+
+ assert_parse(make_rss20(<<-EOR), :nothing_raised)
+#{make_channel20(make_item20(%Q[<source url="http://example.com/" />]))}
+EOR
+
+ assert_parse(make_rss20(<<-EOR), :nothing_raised)
+#{make_channel20(make_item20(%Q[<source url="http://example.com/">Example</source>]))}
+EOR
+ end
+
+ def test_enclosure20
+ attrs = [
+ ["url", ENCLOSURE_URL],
+ ["length", ENCLOSURE_LENGTH],
+ ["type", ENCLOSURE_TYPE],
+ ]
+
+ (attrs.size + 1).times do |i|
+ missing_attr = attrs[i]
+ if missing_attr
+ meth = :missing_attribute
+ args = ["enclosure", missing_attr[0]]
+ else
+ meth = :nothing_raised
+ args = []
+ end
+
+ enclosure_attrs = []
+ attrs.each_with_index do |attr, j|
+ unless i == j
+ enclosure_attrs << %Q[#{attr[0]}="#{attr[1]}"]
+ end
+ end
+
+ assert_parse(make_rss20(<<-EOR), meth, *args)
+#{make_channel20(%Q[
+#{make_item20(%Q[
+<enclosure
+ #{enclosure_attrs.join("\n")} />
+ ])}
+ ])}
+EOR
+ end
+ end
+
+ def test_category20
+ values = [nil, CATEGORY_DOMAIN]
+ values.each do |value|
+ domain = ""
+ domain << %Q[domain="#{value}"] if value
+
+ ["", "Example Text"].each do |text|
+ rss_src = make_rss20(<<-EOR)
+#{make_channel20(%Q[
+#{make_item20(%Q[
+<category #{domain}>#{text}</category>
+ ])}
+ ])}
+EOR
+ assert_parse(rss_src, :nothing_raised)
+
+ rss = RSS::Parser.parse(rss_src)
+ category = rss.items.last.categories.first
+ assert_equal(value, category.domain)
+ assert_equal(text, category.content)
+ end
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/rss/test_setup_maker_0.9.rb b/ruby_1_8_6/test/rss/test_setup_maker_0.9.rb
new file mode 100644
index 0000000000..9408728371
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_setup_maker_0.9.rb
@@ -0,0 +1,233 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestSetupMaker09 < TestCase
+
+ def test_setup_maker_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+ copyright = "foo"
+ managingEditor = "bar"
+ webMaster = "web master"
+ rating = '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))'
+ docs = "http://foo.com/doc"
+ skipDays = [
+ "Sunday",
+ "Monday",
+ ]
+ skipHours = [
+ "0",
+ "13",
+ ]
+ pubDate = Time.now
+ lastBuildDate = Time.now
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ maker.channel.copyright = copyright
+ maker.channel.managingEditor = managingEditor
+ maker.channel.webMaster = webMaster
+ maker.channel.rating = rating
+ maker.channel.docs = docs
+ maker.channel.pubDate = pubDate
+ maker.channel.lastBuildDate = lastBuildDate
+
+ skipDays.each do |day|
+ maker.channel.skipDays.new_day do |new_day|
+ new_day.content = day
+ end
+ end
+ skipHours.each do |hour|
+ maker.channel.skipHours.new_hour do |new_hour|
+ new_hour.content = hour
+ end
+ end
+ end
+
+ new_rss = RSS::Maker.make("0.91") do |maker|
+ rss.channel.setup_maker(maker)
+ end
+ channel = new_rss.channel
+
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert_equal(language, channel.language)
+ assert_equal(copyright, channel.copyright)
+ assert_equal(managingEditor, channel.managingEditor)
+ assert_equal(webMaster, channel.webMaster)
+ assert_equal(rating, channel.rating)
+ assert_equal(docs, channel.docs)
+ assert_equal(pubDate, channel.pubDate)
+ assert_equal(lastBuildDate, channel.lastBuildDate)
+
+ skipDays.each_with_index do |day, i|
+ assert_equal(day, channel.skipDays.days[i].content)
+ end
+ skipHours.each_with_index do |hour, i|
+ assert_equal(hour.to_i, channel.skipHours.hours[i].content)
+ end
+
+ assert(channel.items.empty?)
+ assert_nil(channel.image)
+ assert_nil(channel.textInput)
+ end
+
+ def test_setup_maker_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+ width = "144"
+ height = "400"
+ description = "an image"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+
+ new_rss = RSS::Maker.make("0.91") do |maker|
+ rss.channel.setup_maker(maker)
+ rss.image.setup_maker(maker)
+ end
+
+ image = new_rss.image
+ assert_equal(title, image.title)
+ assert_equal(link, image.link)
+ assert_equal(url, image.url)
+ assert_equal(width.to_i, image.width)
+ assert_equal(height.to_i, image.height)
+ assert_equal(description, image.description)
+ end
+
+ def test_setup_maker_textinput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+
+ new_rss = RSS::Maker.make("0.91") do |maker|
+ rss.channel.setup_maker(maker)
+ rss.textinput.setup_maker(maker)
+ end
+
+ textInput = new_rss.channel.textInput
+ assert_equal(title, textInput.title)
+ assert_equal(description, textInput.description)
+ assert_equal(name, textInput.name)
+ assert_equal(link, textInput.link)
+ end
+
+ def test_setup_maker_items(for_backward_compatibility=false)
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+
+ item_size = 5
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ end
+ end
+ end
+
+ new_rss = RSS::Maker.make("0.91") do |maker|
+ rss.channel.setup_maker(maker)
+
+ rss.items.each do |item|
+ if for_backward_compatibility
+ item.setup_maker(maker)
+ else
+ item.setup_maker(maker.items)
+ end
+ end
+ end
+
+ assert_equal(item_size, new_rss.items.size)
+ new_rss.items.each_with_index do |item, i|
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+
+ end
+
+ def test_setup_maker_items_backward_compatibility
+ test_setup_maker_items(true)
+ end
+
+ def test_setup_maker
+ encoding = "EUC-JP"
+ standalone = true
+
+ href = 'a.xsl'
+ type = 'text/xsl'
+ title = 'sample'
+ media = 'printer'
+ charset = 'UTF-8'
+ alternate = 'yes'
+
+ rss = RSS::Maker.make("0.91") do |maker|
+ maker.encoding = encoding
+ maker.standalone = standalone
+
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ xss.type = type
+ xss.title = title
+ xss.media = media
+ xss.charset = charset
+ xss.alternate = alternate
+ end
+
+ setup_dummy_channel(maker)
+ end
+
+ new_rss = RSS::Maker.make("0.91") do |maker|
+ rss.setup_maker(maker)
+ end
+
+ assert_equal("0.91", new_rss.rss_version)
+ assert_equal(encoding, new_rss.encoding)
+ assert_equal(standalone, new_rss.standalone)
+
+ xss = rss.xml_stylesheets.first
+ assert_equal(1, rss.xml_stylesheets.size)
+ assert_equal(href, xss.href)
+ assert_equal(type, xss.type)
+ assert_equal(title, xss.title)
+ assert_equal(media, xss.media)
+ assert_equal(charset, xss.charset)
+ assert_equal(alternate, xss.alternate)
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_setup_maker_1.0.rb b/ruby_1_8_6/test/rss/test_setup_maker_1.0.rb
new file mode 100644
index 0000000000..51a4d146c7
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_setup_maker_1.0.rb
@@ -0,0 +1,534 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestSetupMaker10 < TestCase
+
+ def setup
+ t = Time.iso8601("2000-01-01T12:00:05+00:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+
+ @dc_elems = {
+ :title => "hoge",
+ :description =>
+ " XML is placing increasingly heavy loads on
+ the existing technical infrastructure of the Internet.",
+ :creator => "Rael Dornfest (mailto:rael@oreilly.com)",
+ :subject => "XML",
+ :publisher => "The O'Reilly Network",
+ :contributor => "hogehoge",
+ :type => "fugafuga",
+ :format => "hohoho",
+ :identifier => "fufufu",
+ :source => "barbar",
+ :language => "ja",
+ :relation => "cococo",
+ :rights => "Copyright (c) 2000 O'Reilly &amp; Associates, Inc.",
+ :date => t,
+ }
+
+ @sy_elems = {
+ :updatePeriod => "hourly",
+ :updateFrequency => "2",
+ :updateBase => t,
+ }
+
+ @content_elems = {
+ :encoded => "<em>ATTENTION</em>",
+ }
+
+ @trackback_elems = {
+ :ping => "http://bar.com/tb.cgi?tb_id=rssplustrackback",
+ :about => [
+ "http://foo.com/trackback/tb.cgi?tb_id=20020923",
+ "http://foo.com/trackback/tb.cgi?tb_id=20021010",
+ ],
+ }
+
+ @taxo_topic_elems = [
+ {
+ :link => "http://meerkat.oreillynet.com/?c=cat23",
+ :title => "Data: XML",
+ :description => "A Meerkat channel",
+ },
+ {
+ :link => "http://dmoz.org/Computers/Data_Formats/Markup_Languages/XML/",
+ :title => "XML",
+ :subject => "XML",
+ :description => "DMOZ category",
+ :topics => [
+ "http://meerkat.oreillynet.com/?c=cat23",
+ "http://dmoz.org/Computers/Data_Formats/Markup_Languages/SGML/",
+ "http://dmoz.org/Computers/Programming/Internet/",
+ ]
+ },
+ ]
+ end
+
+ def test_setup_maker_channel
+ about = "http://hoge.com"
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+
+ @dc_elems.each do |var, value|
+ maker.channel.__send__("dc_#{var}=", value)
+ end
+
+ @sy_elems.each do |var, value|
+ maker.channel.__send__("sy_#{var}=", value)
+ end
+ end
+
+ new_rss = RSS::Maker.make("1.0") do |maker|
+ rss.channel.setup_maker(maker)
+ end
+ channel = new_rss.channel
+
+ assert_equal(about, channel.about)
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert_equal(true, channel.items.Seq.lis.empty?)
+ assert_nil(channel.image)
+ assert_nil(channel.textinput)
+
+ @dc_elems.each do |var, value|
+ assert_equal(value, channel.__send__("dc_#{var}"))
+ end
+
+ @sy_elems.each do |var, value|
+ value = value.to_i if var == :updateFrequency
+ assert_equal(value, channel.__send__("sy_#{var}"))
+ end
+
+ end
+
+ def test_setup_maker_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+
+ @dc_elems.each do |var, value|
+ maker.image.__send__("dc_#{var}=", value)
+ end
+ end
+
+ new_rss = RSS::Maker.make("1.0") do |maker|
+ rss.channel.setup_maker(maker)
+ rss.image.setup_maker(maker)
+ end
+
+ image = new_rss.image
+ assert_equal(url, image.about)
+ assert_equal(url, new_rss.channel.image.resource)
+ assert_equal(title, image.title)
+ assert_equal(link, image.link)
+ assert_equal(url, image.url)
+
+ @dc_elems.each do |var, value|
+ assert_equal(image.__send__("dc_#{var}"), value)
+ end
+ end
+
+ def test_setup_maker_textinput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.link = link
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+
+ @dc_elems.each do |var, value|
+ maker.textinput.__send__("dc_#{var}=", value)
+ end
+ end
+
+ new_rss = RSS::Maker.make("1.0") do |maker|
+ rss.channel.setup_maker(maker)
+ rss.textinput.setup_maker(maker)
+ end
+
+ textinput = new_rss.textinput
+ assert_equal(link, textinput.about)
+ assert_equal(link, new_rss.channel.textinput.resource)
+ assert_equal(title, textinput.title)
+ assert_equal(name, textinput.name)
+ assert_equal(description, textinput.description)
+ assert_equal(link, textinput.link)
+
+ @dc_elems.each do |var, value|
+ assert_equal(textinput.__send__("dc_#{var}"), value)
+ end
+ end
+
+ def test_setup_maker_items(for_backward_compatibility=false)
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+
+ item_size = 5
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+
+ @dc_elems.each do |var, value|
+ item.__send__("dc_#{var}=", value)
+ end
+
+ @content_elems.each do |var, value|
+ item.__send__("content_#{var}=", value)
+ end
+
+ item.trackback_ping = @trackback_elems[:ping]
+ @trackback_elems[:about].each do |value|
+ item.trackback_abouts.new_about do |new_about|
+ new_about.value = value
+ end
+ end
+ end
+ end
+ end
+
+ new_rss = RSS::Maker.make("1.0") do |maker|
+ rss.channel.setup_maker(maker)
+
+ rss.items.each do |item|
+ if for_backward_compatibility
+ item.setup_maker(maker)
+ else
+ item.setup_maker(maker.items)
+ end
+ end
+ end
+
+ assert_equal(item_size, new_rss.items.size)
+ new_rss.items.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+
+ @dc_elems.each do |var, value|
+ assert_equal(item.__send__("dc_#{var}"), value)
+ end
+
+ @content_elems.each do |var, value|
+ assert_equal(item.__send__("content_#{var}"), value)
+ end
+
+ assert_equal(@trackback_elems[:ping], item.trackback_ping)
+ assert_equal(@trackback_elems[:about].size, item.trackback_abouts.size)
+ item.trackback_abouts.each_with_index do |about, i|
+ assert_equal(@trackback_elems[:about][i], about.value)
+ end
+ end
+ end
+
+ def test_setup_maker_items_sort
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+
+ item_size = 5
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ item = RSS::RDF::Item.new("#{link}#{i}")
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ item.dc_date = Time.now + i * 60
+ item.setup_maker(maker.items)
+ end
+ maker.items.do_sort = false
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.items.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ item = RSS::RDF::Item.new("#{link}#{i}")
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ item.dc_date = Time.now + i * 60
+ item.setup_maker(maker.items)
+ end
+ maker.items.do_sort = true
+ end
+ assert_equal(item_size, rss.items.size)
+ rss.items.reverse.each_with_index do |item, i|
+ assert_equal("#{link}#{i}", item.about)
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ end
+ end
+
+ def test_setup_maker_items_backward_compatibility
+ test_setup_maker_items(true)
+ end
+
+ def test_setup_maker
+ encoding = "EUC-JP"
+ standalone = true
+
+ href = 'a.xsl'
+ type = 'text/xsl'
+ title = 'sample'
+ media = 'printer'
+ charset = 'UTF-8'
+ alternate = 'yes'
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.encoding = encoding
+ maker.standalone = standalone
+
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ xss.type = type
+ xss.title = title
+ xss.media = media
+ xss.charset = charset
+ xss.alternate = alternate
+ end
+
+ setup_dummy_channel(maker)
+ end
+
+ new_rss = RSS::Maker.make("1.0") do |maker|
+ rss.setup_maker(maker)
+ end
+
+ assert_equal("1.0", new_rss.rss_version)
+ assert_equal(encoding, new_rss.encoding)
+ assert_equal(standalone, new_rss.standalone)
+
+ xss = new_rss.xml_stylesheets.first
+ assert_equal(1, new_rss.xml_stylesheets.size)
+ assert_equal(href, xss.href)
+ assert_equal(type, xss.type)
+ assert_equal(title, xss.title)
+ assert_equal(media, xss.media)
+ assert_equal(charset, xss.charset)
+ assert_equal(alternate, xss.alternate)
+ end
+
+ def test_setup_maker_full
+ encoding = "EUC-JP"
+ standalone = true
+
+ href = 'a.xsl'
+ type = 'text/xsl'
+ title = 'sample'
+ media = 'printer'
+ charset = 'UTF-8'
+ alternate = 'yes'
+
+ channel_about = "http://hoge.com"
+ channel_title = "fugafuga"
+ channel_link = "http://hoge.com"
+ channel_description = "fugafugafugafuga"
+
+ image_title = "fugafuga"
+ image_url = "http://hoge.com/hoge.png"
+
+ textinput_title = "fugafuga"
+ textinput_description = "text hoge fuga"
+ textinput_name = "hoge"
+ textinput_link = "http://hoge.com"
+
+ item_title = "TITLE"
+ item_link = "http://hoge.com/"
+ item_description = "text hoge fuga"
+
+ item_size = 5
+
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.encoding = encoding
+ maker.standalone = standalone
+
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ xss.type = type
+ xss.title = title
+ xss.media = media
+ xss.charset = charset
+ xss.alternate = alternate
+ end
+
+ maker.channel.about = channel_about
+ maker.channel.title = channel_title
+ maker.channel.link = channel_link
+ maker.channel.description = channel_description
+ @dc_elems.each do |var, value|
+ maker.channel.__send__("dc_#{var}=", value)
+ end
+ @sy_elems.each do |var, value|
+ maker.channel.__send__("sy_#{var}=", value)
+ end
+
+ maker.image.title = image_title
+ maker.image.url = image_url
+ @dc_elems.each do |var, value|
+ maker.image.__send__("dc_#{var}=", value)
+ end
+
+ maker.textinput.link = textinput_link
+ maker.textinput.title = textinput_title
+ maker.textinput.description = textinput_description
+ maker.textinput.name = textinput_name
+ @dc_elems.each do |var, value|
+ maker.textinput.__send__("dc_#{var}=", value)
+ end
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{item_title}#{i}"
+ item.link = "#{item_link}#{i}"
+ item.description = "#{item_description}#{i}"
+
+ @dc_elems.each do |var, value|
+ item.__send__("dc_#{var}=", value)
+ end
+
+ @content_elems.each do |var, value|
+ item.__send__("content_#{var}=", value)
+ end
+
+ item.trackback_ping = @trackback_elems[:ping]
+ @trackback_elems[:about].each do |value|
+ item.trackback_abouts.new_about do |new_about|
+ new_about.value = value
+ end
+ end
+ end
+ end
+
+ setup_taxo_topic(maker, @taxo_topic_elems)
+ end
+
+ new_rss = RSS::Maker.make("1.0") do |maker|
+ rss.setup_maker(maker)
+ end
+
+ assert_equal("1.0", new_rss.rss_version)
+ assert_equal(encoding, new_rss.encoding)
+ assert_equal(standalone, new_rss.standalone)
+
+ xss = new_rss.xml_stylesheets.first
+ assert_equal(1, new_rss.xml_stylesheets.size)
+ assert_equal(href, xss.href)
+ assert_equal(type, xss.type)
+ assert_equal(title, xss.title)
+ assert_equal(media, xss.media)
+ assert_equal(charset, xss.charset)
+ assert_equal(alternate, xss.alternate)
+
+ channel = new_rss.channel
+ assert_equal(channel_about, channel.about)
+ assert_equal(channel_title, channel.title)
+ assert_equal(channel_link, channel.link)
+ assert_equal(channel_description, channel.description)
+ item_resources = []
+ item_size.times do |i|
+ item_resources << "#{item_link}#{i}"
+ end
+ assert_equal(item_resources, channel.items.resources)
+ assert_equal(image_url, channel.image.resource)
+ assert_equal(textinput_link, channel.textinput.resource)
+ @dc_elems.each do |var, value|
+ assert_equal(value, channel.__send__("dc_#{var}"))
+ end
+ @sy_elems.each do |var, value|
+ value = value.to_i if var == :updateFrequency
+ assert_equal(value, channel.__send__("sy_#{var}"))
+ end
+
+ image = new_rss.image
+ assert_equal(image_url, image.about)
+ assert_equal(image_url, new_rss.channel.image.resource)
+ assert_equal(image_title, image.title)
+ assert_equal(channel_link, image.link)
+ assert_equal(image_url, image.url)
+ @dc_elems.each do |var, value|
+ assert_equal(image.__send__("dc_#{var}"), value)
+ end
+
+ textinput = new_rss.textinput
+ assert_equal(textinput_link, textinput.about)
+ assert_equal(textinput_link, new_rss.channel.textinput.resource)
+ assert_equal(textinput_title, textinput.title)
+ assert_equal(textinput_name, textinput.name)
+ assert_equal(textinput_description, textinput.description)
+ assert_equal(textinput_link, textinput.link)
+ @dc_elems.each do |var, value|
+ assert_equal(textinput.__send__("dc_#{var}"), value)
+ end
+
+ assert_equal(item_size, new_rss.items.size)
+ new_rss.items.each_with_index do |item, i|
+ assert_equal("#{item_link}#{i}", item.about)
+ assert_equal("#{item_title}#{i}", item.title)
+ assert_equal("#{item_link}#{i}", item.link)
+ assert_equal("#{item_description}#{i}", item.description)
+
+ @dc_elems.each do |var, value|
+ assert_equal(item.__send__("dc_#{var}"), value)
+ end
+
+ @content_elems.each do |var, value|
+ assert_equal(item.__send__("content_#{var}"), value)
+ end
+
+ assert_equal(@trackback_elems[:ping], item.trackback_ping)
+ assert_equal(@trackback_elems[:about].size, item.trackback_abouts.size)
+ item.trackback_abouts.each_with_index do |about, i|
+ assert_equal(@trackback_elems[:about][i], about.value)
+ end
+ end
+
+ assert_taxo_topic(@taxo_topic_elems, new_rss)
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_setup_maker_2.0.rb b/ruby_1_8_6/test/rss/test_setup_maker_2.0.rb
new file mode 100644
index 0000000000..8fb727de8d
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_setup_maker_2.0.rb
@@ -0,0 +1,308 @@
+require "rss-testcase"
+
+require "rss/maker"
+
+module RSS
+ class TestSetupMaker20 < TestCase
+
+ def test_setup_maker_channel
+ title = "fugafuga"
+ link = "http://hoge.com"
+ description = "fugafugafugafuga"
+ language = "ja"
+ copyright = "foo"
+ managingEditor = "bar"
+ webMaster = "web master"
+ rating = '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))'
+ docs = "http://foo.com/doc"
+ skipDays = [
+ "Sunday",
+ "Monday",
+ ]
+ skipHours = [
+ "0",
+ "13",
+ ]
+ pubDate = Time.now
+ lastBuildDate = Time.now
+ categories = [
+ "Nespapers",
+ "misc",
+ ]
+ generator = "RSS Maker"
+ ttl = "60"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ maker.channel.copyright = copyright
+ maker.channel.managingEditor = managingEditor
+ maker.channel.webMaster = webMaster
+ maker.channel.rating = rating
+ maker.channel.docs = docs
+ maker.channel.pubDate = pubDate
+ maker.channel.lastBuildDate = lastBuildDate
+
+ skipDays.each do |day|
+ maker.channel.skipDays.new_day do |new_day|
+ new_day.content = day
+ end
+ end
+ skipHours.each do |hour|
+ maker.channel.skipHours.new_hour do |new_hour|
+ new_hour.content = hour
+ end
+ end
+
+
+ categories.each do |category|
+ maker.channel.categories.new_category do |new_category|
+ new_category.content = category
+ end
+ end
+
+ maker.channel.generator = generator
+ maker.channel.ttl = ttl
+ end
+
+ new_rss = RSS::Maker.make("2.0") do |maker|
+ rss.channel.setup_maker(maker)
+ end
+ channel = new_rss.channel
+
+ assert_equal(title, channel.title)
+ assert_equal(link, channel.link)
+ assert_equal(description, channel.description)
+ assert_equal(language, channel.language)
+ assert_equal(copyright, channel.copyright)
+ assert_equal(managingEditor, channel.managingEditor)
+ assert_equal(webMaster, channel.webMaster)
+ assert_equal(rating, channel.rating)
+ assert_equal(docs, channel.docs)
+ assert_equal(pubDate, channel.pubDate)
+ assert_equal(lastBuildDate, channel.lastBuildDate)
+
+ skipDays.each_with_index do |day, i|
+ assert_equal(day, channel.skipDays.days[i].content)
+ end
+ skipHours.each_with_index do |hour, i|
+ assert_equal(hour.to_i, channel.skipHours.hours[i].content)
+ end
+
+
+ channel.categories.each_with_index do |category, i|
+ assert_equal(categories[i], category.content)
+ end
+
+ assert_equal(generator, channel.generator)
+ assert_equal(ttl.to_i, channel.ttl)
+
+
+ assert(channel.items.empty?)
+ assert_nil(channel.image)
+ assert_nil(channel.textInput)
+ end
+
+ def test_setup_maker_image
+ title = "fugafuga"
+ link = "http://hoge.com"
+ url = "http://hoge.com/hoge.png"
+ width = "144"
+ height = "400"
+ description = "an image"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
+ end
+
+ new_rss = RSS::Maker.make("2.0") do |maker|
+ rss.channel.setup_maker(maker)
+ rss.image.setup_maker(maker)
+ end
+
+ image = new_rss.image
+ assert_equal(title, image.title)
+ assert_equal(link, image.link)
+ assert_equal(url, image.url)
+ assert_equal(width.to_i, image.width)
+ assert_equal(height.to_i, image.height)
+ assert_equal(description, image.description)
+ end
+
+ def test_setup_maker_textinput
+ title = "fugafuga"
+ description = "text hoge fuga"
+ name = "hoge"
+ link = "http://hoge.com"
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ maker.textinput.title = title
+ maker.textinput.description = description
+ maker.textinput.name = name
+ maker.textinput.link = link
+ end
+
+ new_rss = RSS::Maker.make("2.0") do |maker|
+ rss.channel.setup_maker(maker)
+ rss.textinput.setup_maker(maker)
+ end
+
+ textInput = new_rss.channel.textInput
+ assert_equal(title, textInput.title)
+ assert_equal(description, textInput.description)
+ assert_equal(name, textInput.name)
+ assert_equal(link, textInput.link)
+ end
+
+ def test_setup_maker_items(for_backward_compatibility=false)
+ title = "TITLE"
+ link = "http://hoge.com/"
+ description = "text hoge fuga"
+ author = "oprah@oxygen.net"
+ comments = "http://www.myblog.org/cgi-local/mt/mt-comments.cgi?entry_id=290"
+ pubDate = Time.now
+
+ guid_isPermaLink = "true"
+ guid_content = "http://inessential.com/2002/09/01.php#a2"
+
+ enclosure_url = "http://www.scripting.com/mp3s/weatherReportSuite.mp3"
+ enclosure_length = "12216320"
+ enclosure_type = "audio/mpeg"
+
+ source_url = "http://static.userland.com/tomalak/links2.xml"
+ source_content = "Tomalak's Realm"
+
+ category_domain = "http://www.fool.com/cusips"
+ category_content = "MSFT"
+
+ item_size = 5
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+
+ item_size.times do |i|
+ maker.items.new_item do |item|
+ item.title = "#{title}#{i}"
+ item.link = "#{link}#{i}"
+ item.description = "#{description}#{i}"
+ item.author = "#{author}#{i}"
+ item.comments = "#{comments}#{i}"
+ item.date = pubDate
+
+ item.guid.isPermaLink = guid_isPermaLink
+ item.guid.content = guid_content
+
+ item.enclosure.url = enclosure_url
+ item.enclosure.length = enclosure_length
+ item.enclosure.type = enclosure_type
+
+ item.source.url = source_url
+ item.source.content = source_content
+
+ category = item.categories.new_category
+ category.domain = category_domain
+ category.content = category_content
+ end
+ end
+ end
+
+ new_rss = RSS::Maker.make("2.0") do |maker|
+ rss.channel.setup_maker(maker)
+
+ rss.items.each do |item|
+ if for_backward_compatibility
+ item.setup_maker(maker)
+ else
+ item.setup_maker(maker.items)
+ end
+ end
+ end
+
+ assert_equal(item_size, new_rss.items.size)
+ new_rss.items.each_with_index do |item, i|
+ assert_equal("#{title}#{i}", item.title)
+ assert_equal("#{link}#{i}", item.link)
+ assert_equal("#{description}#{i}", item.description)
+ assert_equal("#{author}#{i}", item.author)
+ assert_equal("#{comments}#{i}", item.comments)
+ assert_equal(pubDate, item.pubDate)
+
+ assert_equal(guid_isPermaLink == "true", item.guid.isPermaLink)
+ assert_equal(guid_content, item.guid.content)
+
+ assert_equal(enclosure_url, item.enclosure.url)
+ assert_equal(enclosure_length.to_i, item.enclosure.length)
+ assert_equal(enclosure_type, item.enclosure.type)
+
+ assert_equal(source_url, item.source.url)
+ assert_equal(source_content, item.source.content)
+
+ assert_equal(1, item.categories.size)
+ assert_equal(category_domain, item.category.domain)
+ assert_equal(category_content, item.category.content)
+ end
+
+ end
+
+ def test_setup_maker_items_backward_compatibility
+ test_setup_maker_items(true)
+ end
+
+ def test_setup_maker
+ encoding = "EUC-JP"
+ standalone = true
+
+ href = 'a.xsl'
+ type = 'text/xsl'
+ title = 'sample'
+ media = 'printer'
+ charset = 'UTF-8'
+ alternate = 'yes'
+
+ rss = RSS::Maker.make("2.0") do |maker|
+ maker.encoding = encoding
+ maker.standalone = standalone
+
+ maker.xml_stylesheets.new_xml_stylesheet do |xss|
+ xss.href = href
+ xss.type = type
+ xss.title = title
+ xss.media = media
+ xss.charset = charset
+ xss.alternate = alternate
+ end
+
+ setup_dummy_channel(maker)
+ end
+
+ new_rss = RSS::Maker.make("2.0") do |maker|
+ rss.setup_maker(maker)
+ end
+
+ assert_equal("2.0", new_rss.rss_version)
+ assert_equal(encoding, new_rss.encoding)
+ assert_equal(standalone, new_rss.standalone)
+
+ xss = rss.xml_stylesheets.first
+ assert_equal(1, rss.xml_stylesheets.size)
+ assert_equal(href, xss.href)
+ assert_equal(type, xss.type)
+ assert_equal(title, xss.title)
+ assert_equal(media, xss.media)
+ assert_equal(charset, xss.charset)
+ assert_equal(alternate, xss.alternate)
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_syndication.rb b/ruby_1_8_6/test/rss/test_syndication.rb
new file mode 100644
index 0000000000..697ff439e4
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_syndication.rb
@@ -0,0 +1,127 @@
+require "cgi"
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/syndication"
+
+module RSS
+ class TestSyndication < TestCase
+
+ def setup
+ @prefix = "sy"
+ @uri = "http://purl.org/rss/1.0/modules/syndication/"
+
+ @parents = %w(channel)
+
+ t = Time.iso8601("2000-01-01T12:00:05+00:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+
+ @elems = {
+ :updatePeriod => "hourly",
+ :updateFrequency => "2",
+ :updateBase => t,
+ }
+
+ @sy_nodes = @elems.collect do |name, value|
+ "<#{@prefix}:#{name}>#{CGI.escapeHTML(value.to_s)}</#{@prefix}:#{name}>"
+ end.join("\n")
+
+ @rss_source = make_RDF(<<-EOR, {@prefix => @uri})
+#{make_channel(@sy_nodes)}
+#{make_image()}
+#{make_item()}
+#{make_textinput()}
+EOR
+
+ @rss = Parser.parse(@rss_source)
+ end
+
+ def test_parser
+
+ assert_nothing_raised do
+ Parser.parse(@rss_source)
+ end
+
+ @elems.each do |tag, value|
+ assert_too_much_tag(tag.to_s, "channel") do
+ Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
+#{make_channel(("<" + @prefix + ":" + tag.to_s + ">" +
+ CGI.escapeHTML(value.to_s) +
+ "</" + @prefix + ":" + tag.to_s + ">") * 2)}
+#{make_item}
+EOR
+ end
+ end
+
+ end
+
+ def test_accessor
+
+ t = Time.iso8601("2003-01-01T12:00:23+09:00")
+ class << t
+ alias_method(:to_s, :iso8601)
+ end
+
+ new_value = {
+ :updatePeriod => "daily",
+ :updateFrequency => "11",
+ :updateBase => t,
+ }
+
+ @elems.each do |name, value|
+ value = value.to_i if name == :updateFrequency
+ @parents.each do |parent|
+ assert_equal(value, @rss.__send__(parent).__send__("sy_#{name}"))
+ @rss.__send__(parent).__send__("sy_#{name}=", new_value[name])
+ new_val = new_value[name]
+ new_val = new_val.to_i if name == :updateFrequency
+ assert_equal(new_val, @rss.__send__(parent).__send__("sy_#{name}"))
+ end
+ end
+
+ %w(hourly daily weekly monthly yearly).each do |x|
+ @parents.each do |parent|
+ assert_nothing_raised do
+ @rss.__send__(parent).sy_updatePeriod = x
+ end
+ end
+ end
+
+ %w(-2 0.3 -0.4).each do |x|
+ @parents.each do |parent|
+ assert_not_available_value("updateBase", x) do
+ @rss.__send__(parent).sy_updateBase = x
+ end
+ end
+ end
+
+ end
+
+ def test_to_s
+
+ @elems.each do |name, value|
+ excepted = "<#{@prefix}:#{name}>#{value}</#{@prefix}:#{name}>"
+ @parents.each do |parent|
+ assert_equal(excepted,
+ @rss.__send__(parent).__send__("sy_#{name}_element"))
+ end
+ end
+
+ REXML::Document.new(@rss_source).root.each_element do |parent|
+ if @parents.include?(parent.name)
+ parent.each_element do |elem|
+ if elem.namespace == @uri
+ assert_equal(elem.text, @elems[elem.name.intern].to_s)
+ end
+ end
+ end
+ end
+
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_taxonomy.rb b/ruby_1_8_6/test/rss/test_taxonomy.rb
new file mode 100644
index 0000000000..10ae55190a
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_taxonomy.rb
@@ -0,0 +1,160 @@
+require "cgi"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/2.0"
+require "rss/taxonomy"
+
+module RSS
+ class TestTaxonomy < TestCase
+
+ def setup
+ @prefix = "taxo"
+ @uri = "http://purl.org/rss/1.0/modules/taxonomy/"
+ @dc_prefix = "dc"
+ @dc_uri = "http://purl.org/dc/elements/1.1/"
+
+ @ns = {
+ @prefix => @uri,
+ @dc_prefix => @dc_uri,
+ }
+
+ @topics_parents = %w(channel item)
+
+ @topics_lis = [
+ "http://meerkat.oreillynet.com/?c=cat23",
+ "http://meerkat.oreillynet.com/?c=47",
+ "http://dmoz.org/Computers/Data_Formats/Markup_Languages/XML/",
+ ]
+
+ @topics_node = "<#{@prefix}:topics>\n"
+ @topics_node << " <rdf:Bag>\n"
+ @topics_lis.each do |value|
+ resource = CGI.escapeHTML(value)
+ @topics_node << " <rdf:li resource=\"#{resource}\"/>\n"
+ end
+ @topics_node << " </rdf:Bag>\n"
+ @topics_node << "</#{@prefix}:topics>"
+
+ @topic_topics_lis = \
+ [
+ "http://meerkat.oreillynet.com/?c=cat23",
+ "http://dmoz.org/Computers/Data_Formats/Markup_Languages/SGML/",
+ "http://dmoz.org/Computers/Programming/Internet/",
+ ]
+
+ @topic_contents = \
+ [
+ {
+ :link => "http://meerkat.oreillynet.com/?c=cat23",
+ :title => "Data: XML",
+ :description => "A Meerkat channel",
+ },
+ {
+ :link => "http://dmoz.org/Computers/Data_Formats/Markup_Languages/XML/",
+ :title => "XML",
+ :subject => "XML",
+ :description => "DMOZ category",
+ :topics => @topic_topics_lis,
+ }
+ ]
+
+ @topic_nodes = @topic_contents.collect do |info|
+ link = info[:link]
+ rv = "<#{@prefix}:topic rdf:about=\"#{link}\">\n"
+ info.each do |name, value|
+ case name
+ when :topics
+ rv << " <#{@prefix}:topics>\n"
+ rv << " <rdf:Bag>\n"
+ value.each do |li|
+ resource = CGI.escapeHTML(li)
+ rv << " <rdf:li resource=\"#{resource}\"/>\n"
+ end
+ rv << " </rdf:Bag>\n"
+ rv << " </#{@prefix}:topics>\n"
+ else
+ prefix = (name == :link ? @prefix : @dc_prefix)
+ rv << " <#{prefix}:#{name}>#{value}</#{prefix}:#{name}>\n"
+ end
+ end
+ rv << "</#{@prefix}:topic>"
+ end
+
+ @rss_source = make_RDF(<<-EOR, @ns)
+#{make_channel(@topics_node)}
+#{make_image()}
+#{make_item(@topics_node)}
+#{make_textinput()}
+#{@topic_nodes.join("\n")}
+EOR
+
+ @rss = Parser.parse(@rss_source)
+ end
+
+ def test_parser
+ assert_nothing_raised do
+ Parser.parse(@rss_source)
+ end
+
+ assert_too_much_tag("topics", "channel") do
+ Parser.parse(make_RDF(<<-EOR, @ns))
+#{make_channel(@topics_node * 2)}
+#{make_item()}
+EOR
+ end
+
+ assert_too_much_tag("topics", "item") do
+ Parser.parse(make_RDF(<<-EOR, @ns))
+#{make_channel()}
+#{make_item(@topics_node * 2)}
+EOR
+ end
+ end
+
+ def test_accessor
+ topics = @rss.channel.taxo_topics
+ assert_equal(@topics_lis.sort,
+ topics.Bag.lis.collect {|li| li.resource}.sort)
+ assert_equal(@topics_lis.sort, topics.resources.sort)
+
+ assert_equal(@rss.taxo_topics.first, @rss.taxo_topic)
+
+ @topic_contents.each_with_index do |info, i|
+ topic = @rss.taxo_topics[i]
+ info.each do |name, value|
+ case name
+ when :link
+ assert_equal(value, topic.about)
+ assert_equal(value, topic.taxo_link)
+ when :topics
+ assert_equal(value.sort, topic.taxo_topics.resources.sort)
+ else
+ assert_equal(value, topic.__send__("dc_#{name}"))
+ end
+ end
+ end
+ end
+
+ def test_to_s
+ @topics_parents.each do |parent|
+ meth = "taxo_topics_element"
+ assert_equal(@topics_node, @rss.__send__(parent).__send__(meth))
+ end
+
+ @topic_nodes.each_with_index do |node, i|
+ expected = REXML::Document.new(node).root
+ actual = REXML::Document.new(@rss.taxo_topics[i].to_s(true, "")).root
+ expected_elems = expected.reject {|x| x.is_a?(REXML::Text)}
+ actual_elems = actual.reject {|x| x.is_a?(REXML::Text)}
+ expected_elems.sort! {|x, y| x.name <=> y.name}
+ actual_elems.sort! {|x, y| x.name <=> y.name}
+ assert_equal(expected_elems.collect {|x| x.to_s},
+ actual_elems.collect {|x| x.to_s})
+ assert_equal(expected.attributes.sort, actual.attributes.sort)
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/rss/test_to_s.rb b/ruby_1_8_6/test/rss/test_to_s.rb
new file mode 100644
index 0000000000..1538534034
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_to_s.rb
@@ -0,0 +1,440 @@
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/maker"
+require "rss/1.0"
+require "rss/2.0"
+require "rss/content"
+require "rss/dublincore"
+require "rss/syndication"
+require "rss/trackback"
+
+module RSS
+ class TestToS < TestCase
+
+ def setup
+ @image_url = "http://example.com/foo.png"
+ @textinput_link = "http://example.com/search.cgi"
+ @item_links = [
+ "http://example.com/1",
+ "http://example.com/2",
+ ]
+
+ setup_xml_declaration_info
+ setup_xml_stylesheet_infos
+ setup_channel_info
+ setup_item_infos
+ setup_image_info
+ setup_textinput_info
+
+ setup_dublin_core_info
+ setup_syndication_info
+ setup_content_info
+ setup_trackback_info
+ end
+
+ def test_to_s_10
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_full(maker)
+ end
+
+ assert_xml_declaration(@version, @encoding, @standalone, rss)
+ assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
+ assert_channel10(@channel_info, rss.channel)
+ assert_items10(@item_infos, rss.items)
+ rss.items.each do |item|
+ assert_trackback(@trackback_info, item)
+ end
+ assert_image10(@image_info, rss.image)
+ assert_textinput10(@textinput_info, rss.textinput)
+
+ rss = RSS::Parser.parse(rss.to_s)
+
+ assert_xml_declaration(@version, @encoding, @standalone, rss)
+ assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
+ assert_channel10(@channel_info, rss.channel)
+ assert_items10(@item_infos, rss.items)
+ assert_image10(@image_info, rss.image)
+ assert_textinput10(@textinput_info, rss.textinput)
+ end
+
+ def test_to_s_09
+ rss = RSS::Maker.make("0.91") do |maker|
+ setup_full(maker)
+ end
+
+ assert_xml_declaration(@version, @encoding, @standalone, rss)
+ assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
+ assert_channel09(@channel_info, rss.channel)
+ assert_items09(@item_infos, rss.items)
+ assert_image09(@image_info, rss.image)
+ assert_textinput09(@textinput_info, rss.textinput)
+
+ rss = RSS::Parser.parse(rss.to_s)
+
+ assert_xml_declaration(@version, @encoding, @standalone, rss)
+ assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
+ assert_channel09(@channel_info, rss.channel)
+ assert_items09(@item_infos, rss.items)
+ assert_image09(@image_info, rss.image)
+ assert_textinput09(@textinput_info, rss.textinput)
+ end
+
+ def test_to_s_20
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_full(maker)
+ end
+
+ assert_xml_declaration(@version, @encoding, @standalone, rss)
+ assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
+ assert_channel20(@channel_info, rss.channel)
+ assert_items20(@item_infos, rss.items)
+ assert_image20(@image_info, rss.image)
+ assert_textinput20(@textinput_info, rss.textinput)
+
+ rss = RSS::Parser.parse(rss.to_s)
+
+ assert_xml_declaration(@version, @encoding, @standalone, rss)
+ assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
+ assert_channel20(@channel_info, rss.channel)
+ assert_items20(@item_infos, rss.items)
+ assert_image20(@image_info, rss.image)
+ assert_textinput20(@textinput_info, rss.textinput)
+ end
+
+ private
+ def setup_xml_declaration_info
+ @version = "1.0"
+ @encoding = "UTF-8"
+ @standalone = false
+ end
+
+ def setup_xml_stylesheet_infos
+ @xs_infos = [
+ {
+ "href" => "XXX.xsl",
+ "type" => "text/xsl",
+ "title" => "XXX",
+ "media" => "print",
+ "alternate" => "no",
+ },
+ {
+ "href" => "YYY.css",
+ "type" => "text/css",
+ "title" => "YYY",
+ "media" => "all",
+ "alternate" => "no",
+ },
+ ]
+ end
+
+ def setup_channel_info
+ @channel_info = {
+ "about" => "http://example.com/index.rdf",
+ "title" => "Sample RSS",
+ "link" => "http://example.com/",
+ "description" => "Sample\n\n\n\n\nSite",
+ "language" => "en",
+ "copyright" => "FDL",
+ "managingEditor" => "foo@example.com",
+ "webMaster" => "webmaster@example.com",
+ "rating" => '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))',
+ "docs" => "http://backend.userland.com/rss091",
+ "skipDays" => [
+ "Monday",
+ "Friday",
+ ],
+ "skipHours" => [
+ "12",
+ "23",
+ ],
+ "date" => Time.now,
+ "lastBuildDate" => Time.now - 3600,
+ "generator" => "RSS Maker",
+ "ttl" => "60",
+ "cloud" => {
+ "domain" => "rpc.sys.com",
+ "port" => "80",
+ "path" => "/RPC2",
+ "registerProcedure" => "myCloud.rssPleaseNotify",
+ "protocol" => "xml-rpc",
+ },
+ "category" => {
+ "domain" => "http://example.com/misc/",
+ "content" => "misc",
+ },
+
+ "image" => {
+ "resource" => @image_url,
+ },
+
+ "textinput" => {
+ "resource" => @textinput_link,
+ },
+
+ "items" => @item_links.collect{|link| {"resource" => link}},
+ }
+ end
+
+ def setup_item_infos
+ @item_infos = [
+ {
+ "title" => "Sample item1",
+ "link" => @item_links[0],
+ "description" => "Sample description1",
+ "date" => Time.now - 3600,
+ "author" => "foo@example.com",
+ "comments" => "http://example.com/1/comments",
+ "guid" => {
+ "isPermaLink" => "true",
+ "content" => "http://example.com/1",
+ },
+ "enclosure" => {
+ "url" => "http://example.com/1.mp3",
+ "length" => "100",
+ "type" => "audio/mpeg",
+ },
+ "source" => {
+ "url" => "http:/example.com/",
+ "content" => "Sample site",
+ },
+ "category" => {
+ "domain" => "http://example.com/misc/",
+ "content" => "misc",
+ },
+ },
+
+ {
+ "title" => "Sample item2",
+ "link" => @item_links[1],
+ "description" => "Sample description2",
+ "date" => Time.now - 7200,
+ "author" => "foo@example.com",
+ "comments" => "http://example.com/2/comments",
+ "guid" => {
+ "isPermaLink" => "false",
+ "content" => "http://example.com/2",
+ },
+ "enclosure" => {
+ "url" => "http://example.com/2.mp3",
+ "length" => "200",
+ "type" => "audio/mpeg",
+ },
+ "source" => {
+ "url" => "http:/example.com/",
+ "content" => "Sample site",
+ },
+ "category" => {
+ "domain" => "http://example.com/misc/",
+ "content" => "misc",
+ },
+ },
+ ]
+ end
+
+ def setup_image_info
+ @image_info = {
+ "title" => "Sample image",
+ "url" => @image_url,
+ "width" => "88",
+ "height" => "31",
+ "description" => "Sample",
+ }
+ end
+
+ def setup_textinput_info
+ @textinput_info = {
+ "title" => "Sample textinput",
+ "description" => "Search",
+ "name" => "key",
+ "link" => @textinput_link,
+ }
+ end
+
+ def setup_dublin_core_info
+ @dc_info = {
+ "title" => "DC title",
+ "description" => "DC desc",
+ "creator" => "DC creator",
+ "subject" => "DC subject",
+ "publisher" => "DC publisher",
+ "contributor" => "DC contributor",
+ "type" => "DC type",
+ "format" => "DC format",
+ "identifier" => "DC identifier",
+ "source" => "DC source",
+ "language" => "ja",
+ "relation" => "DC relation",
+ "coverage" => "DC coverage",
+ "rights" => "DC rights",
+ "date" => Time.now - 60,
+ }
+ end
+
+ def setup_syndication_info
+ @sy_info = {
+ "updatePeriod" => "hourly",
+ "updateFrequency" => "2",
+ "updateBase" => Time.now - 3600,
+ }
+ end
+
+ def setup_content_info
+ @content_info = {
+ "encoded" => "<p>p</p>",
+ }
+ end
+
+ def setup_trackback_info
+ @trackback_info = {
+ "ping" => "http://example.com/tb.cgi?tb_id=XXX",
+ "abouts" => [
+ "http://example.net/tb.cgi?tb_id=YYY",
+ "http://example.org/tb.cgi?tb_id=ZZZ",
+ ]
+ }
+ end
+
+
+ def setup_full(maker)
+ setup_xml_declaration(maker)
+ setup_xml_stylesheets(maker)
+ setup_channel(maker)
+ setup_image(maker)
+ setup_items(maker)
+ setup_textinput(maker)
+ end
+
+ def setup_xml_declaration(maker)
+ %w(version encoding standalone).each do |name|
+ maker.__send__("#{name}=", instance_eval("@#{name}"))
+ end
+ end
+
+ def setup_xml_stylesheets(maker)
+ @xs_infos.each do |info|
+ xs = maker.xml_stylesheets.new_xml_stylesheet
+ info.each do |name, value|
+ xs.__send__("#{name}=", value)
+ end
+ end
+ end
+
+ def setup_channel(maker)
+ channel = maker.channel
+ info = @channel_info
+
+ %w(about title link description language copyright
+ managingEditor webMaster rating docs date
+ lastBuildDate generator ttl).each do |name|
+ channel.__send__("#{name}=", info[name])
+ end
+
+ skipDays = channel.skipDays
+ info["skipDays"].each do |day|
+ new_day = skipDays.new_day
+ new_day.content = day
+ end
+
+ skipHours = channel.skipHours
+ info["skipHours"].each do |hour|
+ new_hour = skipHours.new_hour
+ new_hour.content = hour
+ end
+
+ cloud = channel.cloud
+ %w(domain port path registerProcedure protocol).each do |name|
+ cloud.__send__("#{name}=", info["cloud"][name])
+ end
+
+ category = channel.categories.new_category
+ %w(domain content).each do |name|
+ category.__send__("#{name}=", info["category"][name])
+ end
+ end
+
+ def setup_image(maker)
+ image = maker.image
+ info = @image_info
+
+ %w(title url width height description).each do |name|
+ image.__send__("#{name}=", info[name])
+ end
+ end
+
+ def setup_items(maker)
+ items = maker.items
+
+ @item_infos.each do |info|
+ item = items.new_item
+ %w(title link description date author comments).each do |name|
+ item.__send__("#{name}=", info[name])
+ end
+
+ guid = item.guid
+ %w(isPermaLink content).each do |name|
+ guid.__send__("#{name}=", info["guid"][name])
+ end
+
+ enclosure = item.enclosure
+ %w(url length type).each do |name|
+ enclosure.__send__("#{name}=", info["enclosure"][name])
+ end
+
+ source = item.source
+ %w(url content).each do |name|
+ source.__send__("#{name}=", info["source"][name])
+ end
+
+ category = item.categories.new_category
+ %w(domain content).each do |name|
+ category.__send__("#{name}=", info["category"][name])
+ end
+
+ setup_trackback(item)
+ end
+ end
+
+ def setup_textinput(maker)
+ textinput = maker.textinput
+ info = @textinput_info
+
+ %w(title description name link).each do |name|
+ textinput.__send__("#{name}=", info[name])
+ end
+ end
+
+ def setup_content(target)
+ prefix = "content"
+ %w(encoded).each do |name|
+ target.__send__("#{prefix}_#{name}=", @content_info[name])
+ end
+ end
+
+ def setup_dublin_core(target)
+ prefix = "dc"
+ %w(title description creator subject publisher
+ contributor type format identifier source language
+ relation coverage rights).each do |name|
+ target.__send__("#{prefix}_#{name}=", @dc_info[name])
+ end
+ end
+
+ def setup_syndicate(target)
+ prefix = "sy"
+ %w(updatePeriod updateFrequency updateBase).each do |name|
+ target.__send__("#{prefix}_#{name}=", @sy_info[name])
+ end
+ end
+
+ def setup_trackback(target)
+ target.trackback_ping = @trackback_info["ping"]
+ @trackback_info["abouts"].each do |about|
+ new_about = target.trackback_abouts.new_about
+ new_about.value = about
+ end
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_trackback.rb b/ruby_1_8_6/test/rss/test_trackback.rb
new file mode 100644
index 0000000000..26812d9010
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_trackback.rb
@@ -0,0 +1,135 @@
+require "cgi"
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/2.0"
+require "rss/trackback"
+
+module RSS
+ class TestTrackBack < TestCase
+
+ def setup
+ @prefix = "trackback"
+ @uri = "http://madskills.com/public/xml/rss/module/trackback/"
+
+ @parents = %w(item)
+
+ @elems = {
+ :ping => "http://bar.com/tb.cgi?tb_id=rssplustrackback",
+ :about => "http://foo.com/trackback/tb.cgi?tb_id=20020923",
+ }
+
+ @content_nodes = @elems.collect do |name, value|
+ "<#{@prefix}:#{name} rdf:resource=\"#{CGI.escapeHTML(value.to_s)}\"/>"
+ end.join("\n")
+
+ @content_nodes2 = @elems.collect do |name, value|
+ "<#{@prefix}:#{name}>#{CGI.escapeHTML(value.to_s)}</#{@prefix}:#{name}>"
+ end.join("\n")
+
+ @rss_source = make_RDF(<<-EOR, {@prefix => @uri})
+#{make_channel()}
+#{make_image()}
+#{make_item(@content_nodes)}
+#{make_textinput()}
+EOR
+
+ @rss = Parser.parse(@rss_source)
+
+ @rss20_source = make_rss20(nil, {@prefix => @uri}) do
+ make_channel20(nil) do
+ make_item20(@content_nodes2)
+ end
+ end
+
+ @rss20 = Parser.parse(@rss20_source, false)
+ end
+
+ def test_parser
+
+ assert_nothing_raised do
+ Parser.parse(@rss_source)
+ end
+
+ @elems.find_all{|k, v| k == :ping}.each do |tag, value|
+ assert_too_much_tag(tag.to_s, "item") do
+ Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
+#{make_channel()}
+#{make_item(("<" + @prefix + ":" + tag.to_s + " rdf:resource=\"" +
+ CGI.escapeHTML(value.to_s) +
+ "\"/>") * 2)}
+EOR
+ end
+ end
+
+ @elems.find_all{|k, v| k == :about}.each do |tag, value|
+ assert_missing_tag("trackback:ping", "item") do
+ Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
+#{make_channel()}
+#{make_item(("<" + @prefix + ":" + tag.to_s + " rdf:resource=\"" +
+ CGI.escapeHTML(value.to_s) +
+ "\"/>") * 2)}
+EOR
+ end
+
+ end
+
+ end
+
+ def test_accessor
+
+ new_value = {
+ :ping => "http://baz.com/trackback/tb.cgi?tb_id=20030808",
+ :about => "http://hoge.com/trackback/tb.cgi?tb_id=90030808",
+ }
+
+ @elems.each do |name, value|
+ @parents.each do |parent|
+ accessor = "#{RSS::TRACKBACK_PREFIX}_#{name}"
+ target = @rss.__send__(parent)
+ target20 = @rss20.channel.__send__(parent, -1)
+ assert_equal(value, target.__send__(accessor))
+ assert_equal(value, target20.__send__(accessor))
+ if name == :about
+ # abount is zero or more
+ target.__send__("#{accessor}=", 0, new_value[name].to_s)
+ target20.__send__("#{accessor}=", 0, new_value[name].to_s)
+ else
+ target.__send__("#{accessor}=", new_value[name].to_s)
+ target20.__send__("#{accessor}=", new_value[name].to_s)
+ end
+ assert_equal(new_value[name], target.__send__(accessor))
+ assert_equal(new_value[name], target20.__send__(accessor))
+ end
+ end
+
+ end
+
+ def test_to_s
+
+ @elems.each do |name, value|
+ excepted = %Q!<#{@prefix}:#{name} rdf:resource="#{CGI.escapeHTML(value)}"/>!
+ @parents.each do |parent|
+ meth = "#{RSS::TRACKBACK_PREFIX}_#{name}_element"
+ meth << "s" if name == :about
+ assert_equal(excepted, @rss.__send__(parent).__send__(meth))
+ end
+ end
+
+ REXML::Document.new(@rss_source).root.each_element do |parent|
+ if @parents.include?(parent.name)
+ parent.each_element do |elem|
+ if elem.namespace == @uri
+ assert_equal(elem.attributes["resource"], @elems[elem.name.intern])
+ end
+ end
+ end
+ end
+
+ end
+
+ end
+end
+
diff --git a/ruby_1_8_6/test/rss/test_version.rb b/ruby_1_8_6/test/rss/test_version.rb
new file mode 100644
index 0000000000..237f364b20
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_version.rb
@@ -0,0 +1,9 @@
+require "rss-testcase"
+
+module RSS
+ class TestVersion < TestCase
+ def test_version
+ assert_equal("0.1.6", ::RSS::VERSION)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/rss/test_xml-stylesheet.rb b/ruby_1_8_6/test/rss/test_xml-stylesheet.rb
new file mode 100644
index 0000000000..c88a858f56
--- /dev/null
+++ b/ruby_1_8_6/test/rss/test_xml-stylesheet.rb
@@ -0,0 +1,108 @@
+require "rexml/document"
+
+require "rss-testcase"
+
+require "rss/1.0"
+require "rss/xml-stylesheet"
+
+module RSS
+ class TestXMLStyleSheet < TestCase
+
+ def test_accessor
+ [
+ {:href => "a.xsl", :type => "text/xsl"},
+ {:media => "print", :title => "FOO"},
+ {:charset => "UTF-8", :alternate => "yes"},
+ ].each do |attrs|
+ assert_xml_stylesheet_attrs(attrs, XMLStyleSheet.new(*attrs))
+ end
+ end
+
+ def test_to_s
+ [
+ {:href => "a.xsl", :type => "text/xsl"},
+ {:type => "text/xsl"},
+ {:href => "a.xsl", :guess_type => "text/xsl"},
+ {:href => "a.css", :type => "text/css"},
+ {:href => "a.css", :type => "text/xsl",
+ :guess_type => "text/css"},
+ {:href => "a.xsl", :type => "text/xsl",
+ :title => "sample", :media => "printer",
+ :charset => "UTF-8", :alternate => "yes"},
+ {:href => "a.css", :guess_type => "text/css",
+ :alternate => "no"},
+ {:type => "text/xsl", :title => "sample",
+ :media => "printer", :charset => "UTF-8",
+ :alternate => "yes"},
+ ].each do |attrs|
+ target, contents = parse_pi(XMLStyleSheet.new(*attrs).to_s)
+ assert_xml_stylesheet(target, attrs, XMLStyleSheet.new(*contents))
+ end
+ end
+
+ def test_bad_alternate
+ %w(a ___ ??? BAD_ALTERNATE).each do |value|
+ xss = XMLStyleSheet.new
+ assert_raise(NotAvailableValueError) do
+ xss.alternate = value
+ end
+ xss.do_validate = false
+ assert_nothing_raised do
+ xss.alternate = value
+ end
+ assert_nil(xss.alternate)
+ end
+ end
+
+ def test_parse
+ [
+ [{:href => "a.xsl", :type => "text/xsl"},],
+ [{:media => "print", :title => "FOO"},],
+ [{:charset => "UTF-8", :alternate => "yes"},],
+ [{:href => "a.xsl", :type => "text/xsl"},
+ {:type => "text/xsl"},
+ {:href => "a.xsl", :guess_type => "text/xsl"},
+ {:href => "a.css", :type => "text/css"},
+ {:href => "a.css", :type => "text/xsl",
+ :guess_type => "text/css"},
+ {:href => "a.xsl", :type => "text/xsl",
+ :title => "sample", :media => "printer",
+ :charset => "UTF-8", :alternate => "yes"},
+ {:href => "a.css", :guess_type => "text/css",
+ :alternate => "no"},
+ {:type => "text/xsl", :title => "sample",
+ :media => "printer", :charset => "UTF-8",
+ :alternate => "yes"},],
+ ].each do |xsss|
+ doc = REXML::Document.new(make_sample_RDF)
+ root = doc.root
+ xsss.each do |xss|
+ content = xss.collect do |key, name|
+ %Q[#{key}="#{name}"]
+ end.join(" ")
+ pi = REXML::Instruction.new("xml-stylesheet", content)
+ root.previous_sibling = pi
+ end
+ rss = Parser.parse(doc.to_s)
+ have_href_xsss = xsss.find_all {|xss| xss.has_key?(:href)}
+ assert_equal(have_href_xsss.size, rss.xml_stylesheets.size)
+ rss.xml_stylesheets.each_with_index do |stylesheet, i|
+ target, = parse_pi(stylesheet.to_s)
+ assert_xml_stylesheet(target, have_href_xsss[i], stylesheet)
+ end
+ end
+ end
+
+ def parse_pi(pi)
+ /\A\s*<\?(\S+)([^(?:\?>)]+)\?>\s*\z/ =~ pi
+ target = $1
+ dummy = REXML::Document.new("<dummy #{$2}/>").root
+ contents = {}
+ dummy.attributes.each do |name, value|
+ contents[name] = value
+ end
+ [target, contents]
+ end
+
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/beginmainend.rb b/ruby_1_8_6/test/ruby/beginmainend.rb
new file mode 100644
index 0000000000..646140dd22
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/beginmainend.rb
@@ -0,0 +1,80 @@
+errout = ARGV.shift
+
+BEGIN {
+ puts "b1"
+ local_begin1 = "local_begin1"
+ $global_begin1 = "global_begin1"
+ ConstBegin1 = "ConstBegin1"
+}
+
+BEGIN {
+ puts "b2"
+
+ BEGIN {
+ puts "b2-1"
+ }
+}
+
+# for scope check
+raise if defined?(local_begin1)
+raise unless defined?($global_begin1)
+raise unless defined?(::ConstBegin1)
+local_for_end2 = "e2"
+$global_for_end1 = "e1"
+
+puts "main"
+
+END {
+ puts local_for_end2 # e2
+}
+
+eval <<EOE
+ BEGIN {
+ puts "b3"
+
+ BEGIN {
+ puts "b3-1"
+ }
+ }
+
+ BEGIN {
+ puts "b4"
+ }
+
+ END {
+ puts "e3"
+ }
+
+ END {
+ puts "e4"
+
+ END {
+ puts "e4-1"
+
+ END {
+ puts "e4-1-1"
+ }
+ }
+
+ END {
+ puts "e4-2"
+ }
+ }
+EOE
+
+END {
+ exit
+ puts "should not be dumped"
+
+ END {
+ puts "not reached"
+ }
+}
+
+END {
+ puts $global_for_end1 # e1
+
+ END {
+ puts "e1-1"
+ }
+}
diff --git a/ruby_1_8_6/test/ruby/endblockwarn.rb b/ruby_1_8_6/test/ruby/endblockwarn.rb
new file mode 100644
index 0000000000..7b7f97f597
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/endblockwarn.rb
@@ -0,0 +1,12 @@
+def end1
+ END {}
+end
+
+end1
+
+eval <<EOE
+ def end2
+ END {}
+ end
+EOE
+
diff --git a/ruby_1_8_6/test/ruby/envutil.rb b/ruby_1_8_6/test/ruby/envutil.rb
new file mode 100644
index 0000000000..c481326288
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/envutil.rb
@@ -0,0 +1,28 @@
+module EnvUtil
+ def rubybin
+ if ruby = ENV["RUBY"]
+ return ruby
+ end
+ ruby = "ruby"
+ rubyexe = ruby+".exe"
+ 3.times do
+ if File.exist? ruby and File.executable? ruby and !File.directory? ruby
+ return File.expand_path(ruby)
+ end
+ if File.exist? rubyexe and File.executable? rubyexe
+ return File.expand_path(ruby)
+ end
+ ruby = File.join("..", ruby)
+ end
+ begin
+ require "rbconfig"
+ File.join(
+ Config::CONFIG["bindir"],
+ Config::CONFIG["ruby_install_name"] + Config::CONFIG["EXEEXT"]
+ )
+ rescue LoadError
+ "ruby"
+ end
+ end
+ module_function :rubybin
+end
diff --git a/ruby_1_8_6/test/ruby/marshaltestlib.rb b/ruby_1_8_6/test/ruby/marshaltestlib.rb
new file mode 100644
index 0000000000..891f43b1f7
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/marshaltestlib.rb
@@ -0,0 +1,494 @@
+module MarshalTestLib
+ # include this module to a Test::Unit::TestCase and definde encode(o) and
+ # decode(s) methods. e.g.
+ #
+ # def encode(o)
+ # SOAPMarshal.dump(o)
+ # end
+ #
+ # def decode(s)
+ # SOAPMarshal.load(s)
+ # end
+
+ NegativeZero = (-1.0 / (1.0 / 0.0))
+
+ module Mod1; end
+ module Mod2; end
+
+ def marshaltest(o1)
+ str = encode(o1)
+ print str, "\n" if $DEBUG
+ o2 = decode(str)
+ o2
+ end
+
+ def marshal_equal(o1, msg = nil)
+ msg = msg ? msg + "(#{ caller[0] })" : caller[0]
+ o2 = marshaltest(o1)
+ assert_equal(o1.class, o2.class, msg)
+ iv1 = o1.instance_variables.sort
+ iv2 = o2.instance_variables.sort
+ assert_equal(iv1, iv2)
+ val1 = iv1.map {|var| o1.instance_eval {eval var}}
+ val2 = iv1.map {|var| o2.instance_eval {eval var}}
+ assert_equal(val1, val2, msg)
+ if block_given?
+ assert_equal(yield(o1), yield(o2), msg)
+ else
+ assert_equal(o1, o2, msg)
+ end
+ end
+
+ class MyObject; def initialize(v) @v = v end; attr_reader :v; end
+ def test_object
+ o1 = Object.new
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_object_subclass
+ marshal_equal(MyObject.new(2)) {|o| o.v}
+ end
+
+ def test_object_extend
+ o1 = Object.new
+ o1.extend(Mod1)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ o1.extend(Mod2)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ end
+
+ def test_object_subclass_extend
+ o1 = MyObject.new(2)
+ o1.extend(Mod1)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ o1.extend(Mod2)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ end
+
+ class MyArray < Array
+ def initialize(v, *args)
+ super(args)
+ @v = v
+ end
+ end
+ def test_array
+ marshal_equal(5)
+ marshal_equal([1,2,3])
+ end
+
+ def test_array_subclass
+ marshal_equal(MyArray.new(0, 1, 2, 3))
+ end
+
+ def test_array_ivar
+ o1 = Array.new
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ class MyException < Exception; def initialize(v, *args) super(*args); @v = v; end; attr_reader :v; end
+ def test_exception
+ marshal_equal(Exception.new('foo')) {|o| o.message}
+ marshal_equal(assert_raise(NoMethodError) {no_such_method()}) {|o| o.message}
+ end
+
+ def test_exception_subclass
+ marshal_equal(MyException.new(20, "bar")) {|o| [o.message, o.v]}
+ end
+
+ def test_false
+ marshal_equal(false)
+ end
+
+ class MyHash < Hash; def initialize(v, *args) super(*args); @v = v; end end
+ def test_hash
+ marshal_equal({1=>2, 3=>4})
+ end
+
+ def test_hash_default
+ h = Hash.new(:default)
+ h[5] = 6
+ marshal_equal(h)
+ end
+
+ def test_hash_subclass
+ h = MyHash.new(7, 8)
+ h[4] = 5
+ marshal_equal(h)
+ end
+
+ def test_hash_default_proc
+ h = Hash.new {}
+ assert_raises(TypeError) { marshaltest(h) }
+ end
+
+ def test_hash_ivar
+ o1 = Hash.new
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_hash_extend
+ o1 = Hash.new
+ o1.extend(Mod1)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ o1.extend(Mod2)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ end
+
+ def test_hash_subclass_extend
+ o1 = MyHash.new(2)
+ o1.extend(Mod1)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ o1.extend(Mod2)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ end
+
+ def test_bignum
+ marshal_equal(-0x4000_0000_0000_0001)
+ marshal_equal(-0x4000_0001)
+ marshal_equal(0x4000_0000)
+ marshal_equal(0x4000_0000_0000_0000)
+ end
+
+ def test_fixnum
+ marshal_equal(-0x4000_0000)
+ marshal_equal(-0x3fff_ffff)
+ marshal_equal(-1)
+ marshal_equal(0)
+ marshal_equal(1)
+ marshal_equal(0x3fff_ffff)
+ end
+
+ def test_fixnum_ivar
+ o1 = 1
+ o1.instance_eval { @iv = 2 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ ensure
+ 1.instance_eval { remove_instance_variable("@iv") }
+ end
+
+ def test_fixnum_ivar_self
+ o1 = 1
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ ensure
+ 1.instance_eval { remove_instance_variable("@iv") }
+ end
+
+ def test_float
+ marshal_equal(-1.0)
+ marshal_equal(0.0)
+ marshal_equal(1.0)
+ end
+
+ def test_float_inf_nan
+ marshal_equal(1.0/0.0)
+ marshal_equal(-1.0/0.0)
+ marshal_equal(0.0/0.0) {|o| o.nan?}
+ marshal_equal(NegativeZero) {|o| 1.0/o}
+ end
+
+ def test_float_ivar
+ o1 = 1.23
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_float_ivar_self
+ o1 = 5.5
+ o1.instance_eval { @iv = o1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_float_extend
+ o1 = 0.0/0.0
+ o1.extend(Mod1)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ o1.extend(Mod2)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ end
+
+ class MyRange < Range; def initialize(v, *args) super(*args); @v = v; end end
+ def test_range
+ marshal_equal(1..2)
+ marshal_equal(1...3)
+ end
+
+ def test_range_subclass
+ marshal_equal(MyRange.new(4,5,8, false))
+ end
+
+ class MyRegexp < Regexp; def initialize(v, *args) super(*args); @v = v; end end
+ def test_regexp
+ marshal_equal(/a/)
+ marshal_equal(/A/i)
+ marshal_equal(/A/mx)
+ end
+
+ def test_regexp_subclass
+ marshal_equal(MyRegexp.new(10, "a"))
+ end
+
+ class MyString < String; def initialize(v, *args) super(*args); @v = v; end end
+ def test_string
+ marshal_equal("abc")
+ end
+
+ def test_string_ivar
+ o1 = ""
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_string_subclass
+ marshal_equal(MyString.new(10, "a"))
+ end
+
+ def test_string_subclass_cycle
+ str = MyString.new(10, "b")
+ str.instance_eval { @v = str }
+ marshal_equal(str) { |o|
+ assert_equal(o.__id__, o.instance_eval { @v }.__id__)
+ o.instance_eval { @v }
+ }
+ end
+
+ def test_string_subclass_extend
+ o = "abc"
+ o.extend(Mod1)
+ str = MyString.new(o, "c")
+ marshal_equal(str) { |o|
+ assert(o.instance_eval { @v }).kind_of?(Mod1)
+ }
+ end
+
+ MyStruct = Struct.new("MyStruct", :a, :b)
+ if RUBY_VERSION < "1.8.0"
+ # Struct#== is not defined in ruby/1.6
+ class MyStruct
+ def ==(rhs)
+ return true if __id__ == rhs.__id__
+ return false unless rhs.is_a?(::Struct)
+ return false if self.class != rhs.class
+ members.each do |member|
+ return false if self.__send__(member) != rhs.__send__(member)
+ end
+ return true
+ end
+ end
+ end
+ class MySubStruct < MyStruct; def initialize(v, *args) super(*args); @v = v; end end
+ def test_struct
+ marshal_equal(MyStruct.new(1,2))
+ end
+
+ def test_struct_subclass
+ if RUBY_VERSION < "1.8.0"
+ # Substruct instance cannot be dumped in ruby/1.6
+ # ::Marshal.dump(MySubStruct.new(10, 1, 2)) #=> uninitialized struct
+ return false
+ end
+ marshal_equal(MySubStruct.new(10,1,2))
+ end
+
+ def test_struct_ivar
+ o1 = MyStruct.new
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_struct_subclass_extend
+ o1 = MyStruct.new
+ o1.extend(Mod1)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ o1.extend(Mod2)
+ marshal_equal(o1) { |o|
+ (class << self; self; end).ancestors
+ }
+ end
+
+ def test_symbol
+ marshal_equal(:a)
+ marshal_equal(:a?)
+ marshal_equal(:a!)
+ marshal_equal(:a=)
+ marshal_equal(:|)
+ marshal_equal(:^)
+ marshal_equal(:&)
+ marshal_equal(:<=>)
+ marshal_equal(:==)
+ marshal_equal(:===)
+ marshal_equal(:=~)
+ marshal_equal(:>)
+ marshal_equal(:>=)
+ marshal_equal(:<)
+ marshal_equal(:<=)
+ marshal_equal(:<<)
+ marshal_equal(:>>)
+ marshal_equal(:+)
+ marshal_equal(:-)
+ marshal_equal(:*)
+ marshal_equal(:/)
+ marshal_equal(:%)
+ marshal_equal(:**)
+ marshal_equal(:~)
+ marshal_equal(:+@)
+ marshal_equal(:-@)
+ marshal_equal(:[])
+ marshal_equal(:[]=)
+ marshal_equal(:`) #`
+ marshal_equal("a b".intern)
+ end
+
+ class MyTime < Time; def initialize(v, *args) super(*args); @v = v; end end
+ def test_time
+ # once there was a bug caused by usec overflow. try a little harder.
+ 10.times do
+ t = Time.now
+ marshal_equal(t, t.usec.to_s)
+ end
+ end
+
+ def test_time_subclass
+ marshal_equal(MyTime.new(10))
+ end
+
+ def test_time_ivar
+ o1 = Time.now
+ o1.instance_eval { @iv = 1 }
+ marshal_equal(o1) {|o| o.instance_eval { @iv }}
+ end
+
+ def test_true
+ marshal_equal(true)
+ end
+
+ def test_nil
+ marshal_equal(nil)
+ end
+
+ def test_share
+ o = [:share]
+ o1 = [o, o]
+ o2 = marshaltest(o1)
+ assert_same(o2.first, o2.last)
+ end
+
+ class CyclicRange < Range
+ def <=>(other); true; end
+ end
+ def test_range_cyclic
+ return unless CyclicRange.respond_to?(:allocate) # test for 1.8
+ o1 = CyclicRange.allocate
+ o1.instance_eval { initialize(o1, o1) }
+ o2 = marshaltest(o1)
+ assert_same(o2, o2.begin)
+ assert_same(o2, o2.end)
+ end
+
+ def test_singleton
+ o = Object.new
+ def o.m() end
+ assert_raises(TypeError) { marshaltest(o) }
+ o = Object.new
+ c = class << o
+ @v = 1
+ class C; self; end
+ end
+ assert_raises(TypeError) { marshaltest(o) }
+ assert_raises(TypeError) { marshaltest(c) }
+ assert_raises(TypeError) { marshaltest(ARGF) }
+ assert_raises(TypeError) { marshaltest(ENV) }
+ end
+
+ def test_extend
+ o = Object.new
+ o.extend Mod1
+ marshal_equal(o) { |obj| obj.kind_of? Mod1 }
+ o = Object.new
+ o.extend Mod1
+ o.extend Mod2
+ marshal_equal(o) {|obj| class << obj; ancestors end}
+ o = Object.new
+ o.extend Module.new
+ assert_raises(TypeError) { marshaltest(o) }
+ end
+
+ def test_extend_string
+ o = ""
+ o.extend Mod1
+ marshal_equal(o) { |obj| obj.kind_of? Mod1 }
+ o = ""
+ o.extend Mod1
+ o.extend Mod2
+ marshal_equal(o) {|obj| class << obj; ancestors end}
+ o = ""
+ o.extend Module.new
+ assert_raises(TypeError) { marshaltest(o) }
+ end
+
+ def test_anonymous
+ c = Class.new
+ assert_raises(TypeError) { marshaltest(c) }
+ o = c.new
+ assert_raises(TypeError) { marshaltest(o) }
+ m = Module.new
+ assert_raises(TypeError) { marshaltest(m) }
+ end
+
+ def test_string_empty
+ marshal_equal("")
+ end
+
+ def test_string_crlf
+ marshal_equal("\r\n")
+ end
+
+ def test_string_escape
+ marshal_equal("\0<;;>\1;;")
+ end
+
+ MyStruct2 = Struct.new(:a, :b)
+ if RUBY_VERSION < "1.8.0"
+ # Struct#== is not defined in ruby/1.6
+ class MyStruct2
+ def ==(rhs)
+ return true if __id__ == rhs.__id__
+ return false unless rhs.is_a?(::Struct)
+ return false if self.class != rhs.class
+ members.each do |member|
+ return false if self.__send__(member) != rhs.__send__(member)
+ end
+ return true
+ end
+ end
+ end
+ def test_struct_toplevel
+ o = MyStruct2.new(1,2)
+ marshal_equal(o)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/suicide.rb b/ruby_1_8_6/test/ruby/suicide.rb
new file mode 100644
index 0000000000..2687ed04cd
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/suicide.rb
@@ -0,0 +1,2 @@
+STDERR.reopen(STDOUT)
+at_exit{Process.kill(:INT, $$)}
diff --git a/ruby_1_8_6/test/ruby/test_alias.rb b/ruby_1_8_6/test/ruby/test_alias.rb
new file mode 100644
index 0000000000..83f897fb00
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_alias.rb
@@ -0,0 +1,40 @@
+require 'test/unit'
+
+class TestAlias < Test::Unit::TestCase
+ class Alias0
+ def foo; "foo" end
+ end
+ class Alias1<Alias0
+ alias bar foo
+ def foo; "foo+" + super end
+ end
+ class Alias2<Alias1
+ alias baz foo
+ undef foo
+ end
+ class Alias3<Alias2
+ def foo
+ defined? super
+ end
+ def bar
+ defined? super
+ end
+ def quux
+ defined? super
+ end
+ end
+
+ def test_alias
+ x = Alias2.new
+ assert_equal("foo", x.bar)
+ assert_equal("foo+foo", x.baz)
+
+ # test_check for cache
+ assert_equal("foo+foo", x.baz)
+
+ x = Alias3.new
+ assert(!x.foo)
+ assert(x.bar)
+ assert(!x.quux)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_array.rb b/ruby_1_8_6/test/ruby/test_array.rb
new file mode 100644
index 0000000000..c56f06c3b2
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_array.rb
@@ -0,0 +1,145 @@
+require 'test/unit'
+
+class TestArray < Test::Unit::TestCase
+ def test_array
+ assert_equal([1, 2, 3, 4], [1, 2] + [3, 4])
+ assert_equal([1, 2, 1, 2], [1, 2] * 2)
+ assert_equal("1:2", [1, 2] * ":")
+
+ assert_equal([1, 2].hash, [1, 2].hash)
+
+ assert_equal([2,3], [1,2,3] & [2,3,4])
+ assert_equal([1,2,3,4], [1,2,3] | [2,3,4])
+ assert_equal([1,2,3] - [2,3], [1])
+
+ x = [0, 1, 2, 3, 4, 5]
+ assert_equal(2, x[2])
+ assert_equal([1, 2, 3], x[1..3])
+ assert_equal([1, 2, 3], x[1,3])
+
+ x[0, 2] = 10
+ assert(x[0] == 10 && x[1] == 2)
+
+ x[0, 0] = -1
+ assert(x[0] == -1 && x[1] == 10)
+
+ x[-1, 1] = 20
+ assert(x[-1] == 20 && x.pop == 20)
+ end
+
+ def test_array_andor
+ assert_equal([2], ([1,2,3]&[2,4,6]))
+ assert_equal([1,2,3,4,6], ([1,2,3]|[2,4,6]))
+ end
+
+ def test_compact
+ x = [nil, 1, nil, nil, 5, nil, nil]
+ x.compact!
+ assert_equal([1, 5], x)
+ end
+
+ def test_uniq
+ x = [1, 1, 4, 2, 5, 4, 5, 1, 2]
+ x.uniq!
+ assert_equal([1, 4, 2, 5], x)
+
+ # empty?
+ assert(!x.empty?)
+ x = []
+ assert(x.empty?)
+ end
+
+ def test_sort
+ x = ["it", "came", "to", "pass", "that", "..."]
+ x = x.sort.join(" ")
+ assert_equal("... came it pass that to", x)
+ x = [2,5,3,1,7]
+ x.sort!{|a,b| a<=>b} # sort with condition
+ assert_equal([1,2,3,5,7], x)
+ x.sort!{|a,b| b-a} # reverse sort
+ assert_equal([7,5,3,2,1], x)
+ end
+
+ def test_split
+ x = "The Boassert of Mormon"
+ assert_equal(x.reverse, x.split(//).reverse!.join)
+ assert_equal(x.reverse, x.reverse!)
+ assert_equal("g:n:i:r:t:s: :e:t:y:b: :1", "1 byte string".split(//).reverse.join(":"))
+ x = "a b c d"
+ assert_equal(['a', 'b', 'c', 'd'], x.split)
+ assert_equal(['a', 'b', 'c', 'd'], x.split(' '))
+ end
+
+ def test_misc
+ assert(defined? "a".chomp)
+ assert_equal(["a", "b", "c"], "abc".scan(/./))
+ assert_equal([["1a"], ["2b"], ["3c"]], "1a2b3c".scan(/(\d.)/))
+ # non-greedy match
+ assert_equal([["a", "12"], ["b", "22"]], "a=12;b=22".scan(/(.*?)=(\d*);?/))
+
+ x = [1]
+ assert_equal('1:1:1:1:1', (x * 5).join(":"))
+ assert_equal('1', (x * 1).join(":"))
+ assert_equal('', (x * 0).join(":"))
+
+ *x = *(1..7).to_a
+ assert_equal(7, x.size)
+ assert_equal([1, 2, 3, 4, 5, 6, 7], x)
+
+ x = [1,2,3]
+ x[1,0] = x
+ assert_equal([1,1,2,3,2,3], x)
+
+ x = [1,2,3]
+ x[-1,0] = x
+ assert_equal([1,2,1,2,3,3], x)
+
+ x = [1,2,3]
+ x.concat(x)
+ assert_equal([1,2,3,1,2,3], x)
+
+ x = [1,2,3]
+ x.clear
+ assert_equal([], x)
+
+ x = [1,2,3]
+ y = x.dup
+ x << 4
+ y << 5
+ assert_equal([1,2,3,4], x)
+ assert_equal([1,2,3,5], y)
+ end
+
+ def test_find_all
+ assert_respond_to([], :find_all)
+ assert_respond_to([], :select) # Alias
+ assert_equal([], [].find_all{ |obj| obj == "foo"})
+
+ x = ["foo", "bar", "baz", "baz", 1, 2, 3, 3, 4]
+ assert_equal(["baz","baz"], x.find_all{ |obj| obj == "baz" })
+ assert_equal([3,3], x.find_all{ |obj| obj == 3 })
+ end
+
+ def test_fill
+ assert_equal([-1, -1, -1, -1, -1, -1], [0, 1, 2, 3, 4, 5].fill(-1))
+ assert_equal([0, 1, 2, -1, -1, -1], [0, 1, 2, 3, 4, 5].fill(-1, 3))
+ assert_equal([0, 1, 2, -1, -1, 5], [0, 1, 2, 3, 4, 5].fill(-1, 3, 2))
+ assert_equal([0, 1, 2, -1, -1, -1, -1, -1], [0, 1, 2, 3, 4, 5].fill(-1, 3, 5))
+ assert_equal([0, 1, -1, -1, 4, 5], [0, 1, 2, 3, 4, 5].fill(-1, 2, 2))
+ assert_equal([0, 1, -1, -1, -1, -1, -1], [0, 1, 2, 3, 4, 5].fill(-1, 2, 5))
+ assert_equal([0, 1, 2, 3, -1, 5], [0, 1, 2, 3, 4, 5].fill(-1, -2, 1))
+ assert_equal([0, 1, 2, 3, -1, -1, -1], [0, 1, 2, 3, 4, 5].fill(-1, -2, 3))
+ assert_equal([0, 1, 2, -1, -1, 5], [0, 1, 2, 3, 4, 5].fill(-1, 3..4))
+ assert_equal([0, 1, 2, -1, 4, 5], [0, 1, 2, 3, 4, 5].fill(-1, 3...4))
+ assert_equal([0, 1, -1, -1, -1, 5], [0, 1, 2, 3, 4, 5].fill(-1, 2..-2))
+ assert_equal([0, 1, -1, -1, 4, 5], [0, 1, 2, 3, 4, 5].fill(-1, 2...-2))
+ assert_equal([10, 11, 12, 13, 14, 15], [0, 1, 2, 3, 4, 5].fill{|i| i+10})
+ assert_equal([0, 1, 2, 13, 14, 15], [0, 1, 2, 3, 4, 5].fill(3){|i| i+10})
+ assert_equal([0, 1, 2, 13, 14, 5], [0, 1, 2, 3, 4, 5].fill(3, 2){|i| i+10})
+ assert_equal([0, 1, 2, 13, 14, 15, 16, 17], [0, 1, 2, 3, 4, 5].fill(3, 5){|i| i+10})
+ assert_equal([0, 1, 2, 13, 14, 5], [0, 1, 2, 3, 4, 5].fill(3..4){|i| i+10})
+ assert_equal([0, 1, 2, 13, 4, 5], [0, 1, 2, 3, 4, 5].fill(3...4){|i| i+10})
+ assert_equal([0, 1, 12, 13, 14, 5], [0, 1, 2, 3, 4, 5].fill(2..-2){|i| i+10})
+ assert_equal([0, 1, 12, 13, 4, 5], [0, 1, 2, 3, 4, 5].fill(2...-2){|i| i+10})
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_assignment.rb b/ruby_1_8_6/test/ruby/test_assignment.rb
new file mode 100644
index 0000000000..63f37a9d73
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_assignment.rb
@@ -0,0 +1,467 @@
+require 'test/unit'
+
+class TestAssignment < Test::Unit::TestCase
+ def test_assign
+ a=[]; a[0] ||= "bar";
+ assert_equal("bar", a[0])
+ h={}; h["foo"] ||= "bar";
+ assert_equal("bar", h["foo"])
+
+ aa = 5
+ aa ||= 25
+ assert_equal(5, aa)
+ bb ||= 25
+ assert_equal(25, bb)
+ cc &&=33
+ assert_nil(cc)
+ cc = 5
+ cc &&=44
+ assert_equal(44, cc)
+
+ a = nil; assert_nil(a)
+ a = 1; assert_equal(1, a)
+ a = []; assert_equal([], a)
+ a = [1]; assert_equal([1], a)
+ a = [nil]; assert_equal([nil], a)
+ a = [[]]; assert_equal([[]], a)
+ a = [1,2]; assert_equal([1,2], a)
+ a = [*[]]; assert_equal([], a)
+ a = [*[1]]; assert_equal([1], a)
+ a = [*[1,2]]; assert_equal([1,2], a)
+
+ a = *nil; assert_nil(a)
+ a = *1; assert_equal(1, a)
+ a = *[]; assert_nil(a)
+ a = *[1]; assert_equal(1, a)
+ a = *[nil]; assert_nil(a)
+ a = *[[]]; assert_equal([], a)
+ a = *[1,2]; assert_equal([1,2], a)
+ a = *[*[]]; assert_nil(a)
+ a = *[*[1]]; assert_equal(1, a)
+ a = *[*[1,2]]; assert_equal([1,2], a)
+
+ *a = nil; assert_equal([nil], a)
+ *a = 1; assert_equal([1], a)
+ *a = []; assert_equal([[]], a)
+ *a = [1]; assert_equal([[1]], a)
+ *a = [nil]; assert_equal([[nil]], a)
+ *a = [[]]; assert_equal([[[]]], a)
+ *a = [1,2]; assert_equal([[1,2]], a)
+ *a = [*[]]; assert_equal([[]], a)
+ *a = [*[1]]; assert_equal([[1]], a)
+ *a = [*[1,2]]; assert_equal([[1,2]], a)
+
+ *a = *nil; assert_equal([nil], a)
+ *a = *1; assert_equal([1], a)
+ *a = *[]; assert_equal([], a)
+ *a = *[1]; assert_equal([1], a)
+ *a = *[nil]; assert_equal([nil], a)
+ *a = *[[]]; assert_equal([[]], a)
+ *a = *[1,2]; assert_equal([1,2], a)
+ *a = *[*[]]; assert_equal([], a)
+ *a = *[*[1]]; assert_equal([1], a)
+ *a = *[*[1,2]]; assert_equal([1,2], a)
+
+ a,b,*c = nil; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = 1; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = []; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = [1]; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = [nil]; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = [[]]; assert_equal([[],nil,[]], [a,b,c])
+ a,b,*c = [1,2]; assert_equal([1,2,[]], [a,b,c])
+ a,b,*c = [*[]]; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = [*[1]]; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = [*[1,2]]; assert_equal([1,2,[]], [a,b,c])
+
+ a,b,*c = *nil; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = *1; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = *[]; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = *[1]; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = *[nil]; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = *[[]]; assert_equal([[],nil,[]], [a,b,c])
+ a,b,*c = *[1,2]; assert_equal([1,2,[]], [a,b,c])
+ a,b,*c = *[*[]]; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = *[*[1]]; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = *[*[1,2]]; assert_equal([1,2,[]], [a,b,c])
+ end
+
+ def test_yield
+ def f; yield nil; end; f {|a| assert_nil(a)}
+ def f; yield 1; end; f {|a| assert_equal(1, a)}
+ def f; yield []; end; f {|a| assert_equal([], a)}
+ def f; yield [1]; end; f {|a| assert_equal([1], a)}
+ def f; yield [nil]; end; f {|a| assert_equal([nil], a)}
+ def f; yield [[]]; end; f {|a| assert_equal([[]], a)}
+ def f; yield [*[]]; end; f {|a| assert_equal([], a)}
+ def f; yield [*[1]]; end; f {|a| assert_equal([1], a)}
+ def f; yield [*[1,2]]; end; f {|a| assert_equal([1,2], a)}
+
+ def f; yield *nil; end; f {|a| assert_nil(a)}
+ def f; yield *1; end; f {|a| assert_equal(1, a)}
+ def f; yield *[1]; end; f {|a| assert_equal(1, a)}
+ def f; yield *[nil]; end; f {|a| assert_nil(a)}
+ def f; yield *[[]]; end; f {|a| assert_equal([], a)}
+ def f; yield *[*[1]]; end; f {|a| assert_equal(1, a)}
+
+ def f; yield; end; f {|*a| assert_equal([], a)}
+ def f; yield nil; end; f {|*a| assert_equal([nil], a)}
+ def f; yield 1; end; f {|*a| assert_equal([1], a)}
+ def f; yield []; end; f {|*a| assert_equal([[]], a)}
+ def f; yield [1]; end; f {|*a| assert_equal([[1]], a)}
+ def f; yield [nil]; end; f {|*a| assert_equal([[nil]], a)}
+ def f; yield [[]]; end; f {|*a| assert_equal([[[]]], a)}
+ def f; yield [1,2]; end; f {|*a| assert_equal([[1,2]], a)}
+ def f; yield [*[]]; end; f {|*a| assert_equal([[]], a)}
+ def f; yield [*[1]]; end; f {|*a| assert_equal([[1]], a)}
+ def f; yield [*[1,2]]; end; f {|*a| assert_equal([[1,2]], a)}
+
+ def f; yield *nil; end; f {|*a| assert_equal([nil], a)}
+ def f; yield *1; end; f {|*a| assert_equal([1], a)}
+ def f; yield *[]; end; f {|*a| assert_equal([], a)}
+ def f; yield *[1]; end; f {|*a| assert_equal([1], a)}
+ def f; yield *[nil]; end; f {|*a| assert_equal([nil], a)}
+ def f; yield *[[]]; end; f {|*a| assert_equal([[]], a)}
+ def f; yield *[*[]]; end; f {|*a| assert_equal([], a)}
+ def f; yield *[*[1]]; end; f {|*a| assert_equal([1], a)}
+ def f; yield *[*[1,2]]; end; f {|*a| assert_equal([1,2], a)}
+
+ def f; yield; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield nil; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield 1; end; f {|a,b,*c| assert_equal([1,nil,[]], [a,b,c])}
+ def f; yield []; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield [1]; end; f {|a,b,*c| assert_equal([1,nil,[]], [a,b,c])}
+ def f; yield [nil]; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield [[]]; end; f {|a,b,*c| assert_equal([[],nil,[]], [a,b,c])}
+ def f; yield [*[]]; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield [*[1]]; end; f {|a,b,*c| assert_equal([1,nil,[]], [a,b,c])}
+ def f; yield [*[1,2]]; end; f {|a,b,*c| assert_equal([1,2,[]], [a,b,c])}
+
+ def f; yield *nil; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield *1; end; f {|a,b,*c| assert_equal([1,nil,[]], [a,b,c])}
+ def f; yield *[]; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield *[1]; end; f {|a,b,*c| assert_equal([1,nil,[]], [a,b,c])}
+ def f; yield *[nil]; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield *[[]]; end; f {|a,b,*c| assert_equal([[],nil,[]], [a,b,c])}
+ def f; yield *[*[]]; end; f {|a,b,*c| assert_equal([nil,nil,[]], [a,b,c])}
+ def f; yield *[*[1]]; end; f {|a,b,*c| assert_equal([1,nil,[]], [a,b,c])}
+ def f; yield *[*[1,2]]; end; f {|a,b,*c| assert_equal([1,2,[]], [a,b,c])}
+ end
+
+ def test_return
+ def r; return; end; a = r(); assert_nil(a)
+ def r; return nil; end; a = r(); assert_nil(a)
+ def r; return 1; end; a = r(); assert_equal(1, a)
+ def r; return []; end; a = r(); assert_equal([], a)
+ def r; return [1]; end; a = r(); assert_equal([1], a)
+ def r; return [nil]; end; a = r(); assert_equal([nil], a)
+ def r; return [[]]; end; a = r(); assert_equal([[]], a)
+ def r; return [*[]]; end; a = r(); assert_equal([], a)
+ def r; return [*[1]]; end; a = r(); assert_equal([1], a)
+ def r; return [*[1,2]]; end; a = r(); assert_equal([1,2], a)
+
+ def r; return *nil; end; a = r(); assert_nil(a)
+ def r; return *1; end; a = r(); assert_equal(1, a)
+ def r; return *[]; end; a = r(); assert_nil(a)
+ def r; return *[1]; end; a = r(); assert_equal(1, a)
+ def r; return *[nil]; end; a = r(); assert_nil(a)
+ def r; return *[[]]; end; a = r(); assert_equal([], a)
+ def r; return *[*[]]; end; a = r(); assert_nil(a)
+ def r; return *[*[1]]; end; a = r(); assert_equal(1, a)
+ def r; return *[*[1,2]]; end; a = r(); assert_equal([1,2], a)
+
+ def r; return *nil; end; a = *r(); assert_nil(a)
+ def r; return *1; end; a = *r(); assert_equal(1, a)
+ def r; return *[]; end; a = *r(); assert_nil(a)
+ def r; return *[1]; end; a = *r(); assert_equal(1, a)
+ def r; return *[nil]; end; a = *r(); assert_nil(a)
+ def r; return *[[]]; end; a = *r(); assert_nil(a)
+ def r; return *[*[]]; end; a = *r(); assert_nil(a)
+ def r; return *[*[1]]; end; a = *r(); assert_equal(1, a)
+ def r; return *[*[1,2]]; end; a = *r(); assert_equal([1,2], a)
+
+ def r; return; end; *a = r(); assert_equal([nil], a)
+ def r; return nil; end; *a = r(); assert_equal([nil], a)
+ def r; return 1; end; *a = r(); assert_equal([1], a)
+ def r; return []; end; *a = r(); assert_equal([[]], a)
+ def r; return [1]; end; *a = r(); assert_equal([[1]], a)
+ def r; return [nil]; end; *a = r(); assert_equal([[nil]], a)
+ def r; return [[]]; end; *a = r(); assert_equal([[[]]], a)
+ def r; return [1,2]; end; *a = r(); assert_equal([[1,2]], a)
+ def r; return [*[]]; end; *a = r(); assert_equal([[]], a)
+ def r; return [*[1]]; end; *a = r(); assert_equal([[1]], a)
+ def r; return [*[1,2]]; end; *a = r(); assert_equal([[1,2]], a)
+
+ def r; return *nil; end; *a = r(); assert_equal([nil], a)
+ def r; return *1; end; *a = r(); assert_equal([1], a)
+ def r; return *[]; end; *a = r(); assert_equal([nil], a)
+ def r; return *[1]; end; *a = r(); assert_equal([1], a)
+ def r; return *[nil]; end; *a = r(); assert_equal([nil], a)
+ def r; return *[[]]; end; *a = r(); assert_equal([[]], a)
+ def r; return *[1,2]; end; *a = r(); assert_equal([[1,2]], a)
+ def r; return *[*[]]; end; *a = r(); assert_equal([nil], a)
+ def r; return *[*[1]]; end; *a = r(); assert_equal([1], a)
+ def r; return *[*[1,2]]; end; *a = r(); assert_equal([[1,2]], a)
+
+ def r; return *nil; end; *a = *r(); assert_equal([nil], a)
+ def r; return *1; end; *a = *r(); assert_equal([1], a)
+ def r; return *[]; end; *a = *r(); assert_equal([nil], a)
+ def r; return *[1]; end; *a = *r(); assert_equal([1], a)
+ def r; return *[nil]; end; *a = *r(); assert_equal([nil], a)
+ def r; return *[[]]; end; *a = *r(); assert_equal([], a)
+ def r; return *[1,2]; end; *a = *r(); assert_equal([1,2], a)
+ def r; return *[*[]]; end; *a = *r(); assert_equal([nil], a)
+ def r; return *[*[1]]; end; *a = *r(); assert_equal([1], a)
+ def r; return *[*[1,2]]; end; *a = *r(); assert_equal([1,2], a)
+
+ def r; return; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return nil; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return 1; end; a,b,*c = r(); assert_equal([1,nil,[]], [a,b,c])
+ def r; return []; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return [1]; end; a,b,*c = r(); assert_equal([1,nil,[]], [a,b,c])
+ def r; return [nil]; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return [[]]; end; a,b,*c = r(); assert_equal([[],nil,[]], [a,b,c])
+ def r; return [1,2]; end; a,b,*c = r(); assert_equal([1,2,[]], [a,b,c])
+ def r; return [*[]]; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return [*[1]]; end; a,b,*c = r(); assert_equal([1,nil,[]], [a,b,c])
+ def r; return [*[1,2]]; end; a,b,*c = r(); assert_equal([1,2,[]], [a,b,c])
+
+ def r; return *nil; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return *1; end; a,b,*c = r(); assert_equal([1,nil,[]], [a,b,c])
+ def r; return *[]; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return *[1]; end; a,b,*c = r(); assert_equal([1,nil,[]], [a,b,c])
+ def r; return *[nil]; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return *[[]]; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return *[1,2]; end; a,b,*c = r(); assert_equal([1,2,[]], [a,b,c])
+ def r; return *[*[]]; end; a,b,*c = r(); assert_equal([nil,nil,[]], [a,b,c])
+ def r; return *[*[1]]; end; a,b,*c = r(); assert_equal([1,nil,[]], [a,b,c])
+ def r; return *[*[1,2]]; end; a,b,*c = r(); assert_equal([1,2,[]], [a,b,c])
+ end
+
+ def test_lambda
+ f = lambda {|r,| assert_equal([], r)}
+ f.call([], *[])
+
+ f = lambda {|r,*l| assert_equal([], r); assert_equal([1], l)}
+ f.call([], *[1])
+
+ f = lambda{|x| x}
+ assert_equal(42, f.call(42))
+ assert_equal([42], f.call([42]))
+ assert_equal([[42]], f.call([[42]]))
+ assert_equal([42,55], f.call([42,55]))
+
+ f = lambda{|x,| x}
+ assert_equal(42, f.call(42))
+ assert_equal([42], f.call([42]))
+ assert_equal([[42]], f.call([[42]]))
+ assert_equal([42,55], f.call([42,55]))
+
+ f = lambda{|*x| x}
+ assert_equal([42], f.call(42))
+ assert_equal([[42]], f.call([42]))
+ assert_equal([[[42]]], f.call([[42]]))
+ assert_equal([[42,55]], f.call([42,55]))
+ assert_equal([42,55], f.call(42,55))
+ end
+
+ def test_multi
+ a,=*[1]
+ assert_equal(1, a)
+ a,=*[[1]]
+ assert_equal([1], a)
+ a,=*[[[1]]]
+ assert_equal([[1]], a)
+
+ x, (y, z) = 1, 2, 3
+ assert_equal([1,2,nil], [x,y,z])
+ x, (y, z) = 1, [2,3]
+ assert_equal([1,2,3], [x,y,z])
+ x, (y, z) = 1, [2]
+ assert_equal([1,2,nil], [x,y,z])
+ end
+
+ def test_break
+ a = loop do break; end; assert_nil(a)
+ a = loop do break nil; end; assert_nil(a)
+ a = loop do break 1; end; assert_equal(1, a)
+ a = loop do break []; end; assert_equal([], a)
+ a = loop do break [1]; end; assert_equal([1], a)
+ a = loop do break [nil]; end; assert_equal([nil], a)
+ a = loop do break [[]]; end; assert_equal([[]], a)
+ a = loop do break [*[]]; end; assert_equal([], a)
+ a = loop do break [*[1]]; end; assert_equal([1], a)
+ a = loop do break [*[1,2]]; end; assert_equal([1,2], a)
+
+ a = loop do break *nil; end; assert_nil(a)
+ a = loop do break *1; end; assert_equal(1, a)
+ a = loop do break *[]; end; assert_nil(a)
+ a = loop do break *[1]; end; assert_equal(1, a)
+ a = loop do break *[nil]; end; assert_nil(a)
+ a = loop do break *[[]]; end; assert_equal([], a)
+ a = loop do break *[*[]]; end; assert_nil(a)
+ a = loop do break *[*[1]]; end; assert_equal(1, a)
+ a = loop do break *[*[1,2]]; end; assert_equal([1,2], a)
+
+ *a = loop do break; end; assert_equal([nil], a)
+ *a = loop do break nil; end; assert_equal([nil], a)
+ *a = loop do break 1; end; assert_equal([1], a)
+ *a = loop do break []; end; assert_equal([[]], a)
+ *a = loop do break [1]; end; assert_equal([[1]], a)
+ *a = loop do break [nil]; end; assert_equal([[nil]], a)
+ *a = loop do break [[]]; end; assert_equal([[[]]], a)
+ *a = loop do break [1,2]; end; assert_equal([[1,2]], a)
+ *a = loop do break [*[]]; end; assert_equal([[]], a)
+ *a = loop do break [*[1]]; end; assert_equal([[1]], a)
+ *a = loop do break [*[1,2]]; end; assert_equal([[1,2]], a)
+
+ *a = loop do break *nil; end; assert_equal([nil], a)
+ *a = loop do break *1; end; assert_equal([1], a)
+ *a = loop do break *[]; end; assert_equal([nil], a)
+ *a = loop do break *[1]; end; assert_equal([1], a)
+ *a = loop do break *[nil]; end; assert_equal([nil], a)
+ *a = loop do break *[[]]; end; assert_equal([[]], a)
+ *a = loop do break *[1,2]; end; assert_equal([[1,2]], a)
+ *a = loop do break *[*[]]; end; assert_equal([nil], a)
+ *a = loop do break *[*[1]]; end; assert_equal([1], a)
+ *a = loop do break *[*[1,2]]; end; assert_equal([[1,2]], a)
+
+ *a = *loop do break *nil; end; assert_equal([nil], a)
+ *a = *loop do break *1; end; assert_equal([1], a)
+ *a = *loop do break *[]; end; assert_equal([nil], a)
+ *a = *loop do break *[1]; end; assert_equal([1], a)
+ *a = *loop do break *[nil]; end; assert_equal([nil], a)
+ *a = *loop do break *[[]]; end; assert_equal([], a)
+ *a = *loop do break *[1,2]; end; assert_equal([1,2], a)
+ *a = *loop do break *[*[]]; end; assert_equal([nil], a)
+ *a = *loop do break *[*[1]]; end; assert_equal([1], a)
+ *a = *loop do break *[*[1,2]]; end; assert_equal([1,2], a)
+
+ a,b,*c = loop do break; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break nil; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break 1; end; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = loop do break []; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break [1]; end; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = loop do break [nil]; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break [[]]; end; assert_equal([[],nil,[]], [a,b,c])
+ a,b,*c = loop do break [1,2]; end; assert_equal([1,2,[]], [a,b,c])
+ a,b,*c = loop do break [*[]]; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break [*[1]]; end; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = loop do break [*[1,2]]; end; assert_equal([1,2,[]], [a,b,c])
+
+ a,b,*c = loop do break *nil; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break *1; end; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[]; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[1]; end; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[nil]; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[[]]; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[1,2]; end; assert_equal([1,2,[]], [a,b,c])
+ a,b,*c = loop do break *[*[]]; end; assert_equal([nil,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[*[1]]; end; assert_equal([1,nil,[]], [a,b,c])
+ a,b,*c = loop do break *[*[1,2]]; end; assert_equal([1,2,[]], [a,b,c])
+ end
+
+ def test_next
+ def r(val); a = yield(); assert_equal(val, a); end
+ r(nil){next}
+ r(nil){next nil}
+ r(1){next 1}
+ r([]){next []}
+ r([1]){next [1]}
+ r([nil]){next [nil]}
+ r([[]]){next [[]]}
+ r([]){next [*[]]}
+ r([1]){next [*[1]]}
+ r([1,2]){next [*[1,2]]}
+
+ r(nil){next *nil}
+ r(1){next *1}
+ r(nil){next *[]}
+ r(1){next *[1]}
+ r(nil){next *[nil]}
+ r([]){next *[[]]}
+ r(nil){next *[*[]]}
+ r(1){next *[*[1]]}
+ r([1,2]){next *[*[1,2]]}
+
+ def r(val); *a = yield(); assert_equal(val, a); end
+ r([nil]){next}
+ r([nil]){next nil}
+ r([1]){next 1}
+ r([[]]){next []}
+ r([[1]]){next [1]}
+ r([[nil]]){next [nil]}
+ r([[[]]]){next [[]]}
+ r([[1,2]]){next [1,2]}
+ r([[]]){next [*[]]}
+ r([[1]]){next [*[1]]}
+ r([[1,2]]){next [*[1,2]]}
+
+ def r(val); *a = *yield(); assert_equal(val, a); end
+ r([nil]){next *nil}
+ r([1]){next *1}
+ r([nil]){next *[]}
+ r([1]){next *[1]}
+ r([nil]){next *[nil]}
+ r([]){next *[[]]}
+ r([1,2]){next *[1,2]}
+ r([nil]){next *[*[]]}
+ r([1]){next *[*[1]]}
+ r([1,2]){next *[*[1,2]]}
+
+ def r(val); a,b,*c = yield(); assert_equal(val, [a,b,c]); end
+ r([nil,nil,[]]){next}
+ r([nil,nil,[]]){next nil}
+ r([1,nil,[]]){next 1}
+ r([nil,nil,[]]){next []}
+ r([1,nil,[]]){next [1]}
+ r([nil,nil,[]]){next [nil]}
+ r([[],nil,[]]){next [[]]}
+ r([1,2,[]]){next [1,2]}
+ r([nil,nil,[]]){next [*[]]}
+ r([1,nil,[]]){next [*[1]]}
+ r([1,2,[]]){next [*[1,2]]}
+
+ def r(val); a,b,*c = *yield(); assert_equal(val, [a,b,c]); end
+ r([nil,nil,[]]){next *nil}
+ r([1,nil,[]]){next *1}
+ r([nil,nil,[]]){next *[]}
+ r([1,nil,[]]){next *[1]}
+ r([nil,nil,[]]){next *[nil]}
+ r([nil,nil,[]]){next *[[]]}
+ r([1,2,[]]){next *[1,2]}
+ r([nil,nil,[]]){next *[*[]]}
+ r([1,nil,[]]){next *[*[1]]}
+ r([1,2,[]]){next *[*[1,2]]}
+ end
+
+ def test_assign2
+ a = nil
+ assert(defined?(a))
+ assert_nil(a)
+
+ # multiple asignment
+ a, b = 1, 2
+ assert(a == 1 && b == 2)
+
+ a, b = b, a
+ assert(a == 2 && b == 1)
+
+ a, = 1,2
+ assert_equal(1, a)
+
+ a, *b = 1, 2, 3
+ assert(a == 1 && b == [2, 3])
+
+ a, (b, c), d = 1, [2, 3], 4
+ assert(a == 1 && b == 2 && c == 3 && d == 4)
+
+ *a = 1, 2, 3
+ assert_equal([1, 2, 3], a)
+
+ *a = 4
+ assert_equal([4], a)
+
+ *a = nil
+ assert_equal([nil], a)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_beginendblock.rb b/ruby_1_8_6/test/ruby/test_beginendblock.rb
new file mode 100644
index 0000000000..a60e41b848
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_beginendblock.rb
@@ -0,0 +1,86 @@
+require 'test/unit'
+require 'tempfile'
+$:.replace([File.dirname(File.expand_path(__FILE__))] | $:)
+require 'envutil'
+
+class TestBeginEndBlock < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def q(content)
+ "\"#{content}\""
+ end
+
+ def test_beginendblock
+ ruby = EnvUtil.rubybin
+ target = File.join(DIR, 'beginmainend.rb')
+ io = IO.popen("#{q(ruby)} #{q(target)}")
+ assert_equal(%w(b1 b2-1 b2 main b3-1 b3 b4 e1 e4 e3 e2 e4-2 e4-1 e1-1 e4-1-1), io.read.split)
+ io.close
+ end
+
+ def test_begininmethod
+ assert_raises(SyntaxError) do
+ eval("def foo; BEGIN {}; end")
+ end
+
+ assert_raises(SyntaxError) do
+ eval('eval("def foo; BEGIN {}; end")')
+ end
+ end
+
+ def test_endblockwarn
+ ruby = EnvUtil.rubybin
+ # Use Tempfile to create temporary file path.
+ launcher = Tempfile.new(self.class.name)
+ errout = Tempfile.new(self.class.name)
+
+ launcher << <<EOF
+errout = ARGV.shift
+STDERR.reopen(File.open(errout, "w"))
+STDERR.sync = true
+Dir.chdir(#{q(DIR)})
+cmd = "\\"#{ruby}\\" \\"endblockwarn.rb\\""
+system(cmd)
+EOF
+ launcher.close
+ launcherpath = launcher.path
+ errout.close
+ erroutpath = errout.path
+ system("#{q(ruby)} #{q(launcherpath)} #{q(erroutpath)}")
+ expected = <<EOW
+endblockwarn.rb:2: warning: END in method; use at_exit
+(eval):2: warning: END in method; use at_exit
+EOW
+ assert_equal(expected, File.read(erroutpath))
+ # expecting Tempfile to unlink launcher and errout file.
+ end
+
+ def test_raise_in_at_exit
+ # [ruby-core:09675]
+ ruby = EnvUtil.rubybin
+ out = IO.popen("#{q(ruby)} -e 'STDERR.reopen(STDOUT);" \
+ "at_exit{raise %[SomethingBad]};" \
+ "raise %[SomethingElse]'") {|f|
+ f.read
+ }
+ assert_match /SomethingBad/, out
+ assert_match /SomethingElse/, out
+ end
+
+ def test_should_propagate_exit_code
+ ruby = EnvUtil.rubybin
+ assert_equal false, system(ruby, '-e', 'at_exit{exit 2}')
+ assert_equal 2, $?.exitstatus
+ assert_nil $?.termsig
+ end
+
+ def test_should_propagate_signaled
+ ruby = EnvUtil.rubybin
+ out = IO.popen("#{ruby} #{File.dirname(__FILE__)}/suicide.rb"){|f|
+ f.read
+ }
+ assert_match /Interrupt$/, out
+ assert_nil $?.exitstatus
+ assert_equal Signal.list["INT"], $?.termsig
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_bignum.rb b/ruby_1_8_6/test/ruby/test_bignum.rb
new file mode 100644
index 0000000000..c238337db5
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_bignum.rb
@@ -0,0 +1,87 @@
+require 'test/unit'
+
+class TestBignum < Test::Unit::TestCase
+ def fact(n)
+ return 1 if n == 0
+ f = 1
+ while n>0
+ f *= n
+ n -= 1
+ end
+ return f
+ end
+
+ def test_bignum
+ $x = fact(40)
+ assert_equal($x, $x)
+ assert_equal($x, fact(40))
+ assert($x < $x+2)
+ assert($x > $x-2)
+ assert_equal(815915283247897734345611269596115894272000000000, $x)
+ assert_not_equal(815915283247897734345611269596115894272000000001, $x)
+ assert_equal(815915283247897734345611269596115894272000000001, $x+1)
+ assert_equal(335367096786357081410764800000, $x/fact(20))
+ $x = -$x
+ assert_equal(-815915283247897734345611269596115894272000000000, $x)
+ assert_equal(2-(2**32), -(2**32-2))
+ assert_equal(2**32 - 5, (2**32-3)-2)
+
+ for i in 1000..1014
+ assert_equal(2 ** i, 1 << i)
+ end
+
+ n1 = 1 << 1000
+ for i in 1000..1014
+ assert_equal(n1, 1 << i)
+ n1 *= 2
+ end
+
+ n2=n1
+ for i in 1..10
+ n1 = n1 / 2
+ n2 = n2 >> 1
+ assert_equal(n1, n2)
+ end
+
+ for i in 4000..4096
+ n1 = 1 << i;
+ assert_equal(n1-1, (n1**2-1) / (n1+1))
+ end
+ end
+
+ def test_calc
+ b = 10**80
+ a = b * 9 + 7
+ assert_equal(7, a.modulo(b))
+ assert_equal(-b + 7, a.modulo(-b))
+ assert_equal(b + -7, (-a).modulo(b))
+ assert_equal(-7, (-a).modulo(-b))
+ assert_equal(7, a.remainder(b))
+ assert_equal(7, a.remainder(-b))
+ assert_equal(-7, (-a).remainder(b))
+ assert_equal(-7, (-a).remainder(-b))
+
+ assert_equal(10000000000000000000100000000000000000000, 10**40+10**20)
+ assert_equal(100000000000000000000, 10**40/10**20)
+
+ a = 677330545177305025495135714080
+ b = 14269972710765292560
+ assert_equal(0, a % b)
+ assert_equal(0, -a % b)
+ end
+
+ def shift_test(a)
+ b = a / (2 ** 32)
+ c = a >> 32
+ assert_equal(b, c)
+
+ b = a * (2 ** 32)
+ c = a << 32
+ assert_equal(b, c)
+ end
+
+ def test_shift
+ shift_test(-4518325415524767873)
+ shift_test(-0xfffffffffffffffff)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_call.rb b/ruby_1_8_6/test/ruby/test_call.rb
new file mode 100644
index 0000000000..da7ee93c73
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_call.rb
@@ -0,0 +1,19 @@
+require 'test/unit'
+
+class TestCall < Test::Unit::TestCase
+ def aaa(a, b=100, *rest)
+ res = [a, b]
+ res += rest if rest
+ return res
+ end
+
+ def test_call
+ assert_raises(ArgumentError) {aaa()}
+ assert_raises(ArgumentError) {aaa}
+
+ assert_equal([1, 100], aaa(1))
+ assert_equal([1, 2], aaa(1, 2))
+ assert_equal([1, 2, 3, 4], aaa(1, 2, 3, 4))
+ assert_equal([1, 2, 3, 4], aaa(1, *[2, 3, 4]))
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_case.rb b/ruby_1_8_6/test/ruby/test_case.rb
new file mode 100644
index 0000000000..41a22038a0
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_case.rb
@@ -0,0 +1,49 @@
+require 'test/unit'
+
+class TestCase < Test::Unit::TestCase
+ def test_case
+ case 5
+ when 1, 2, 3, 4, 6, 7, 8
+ assert(false)
+ when 5
+ assert(true)
+ end
+
+ case 5
+ when 5
+ assert(true)
+ when 1..10
+ assert(false)
+ end
+
+ case 5
+ when 1..10
+ assert(true)
+ else
+ assert(false)
+ end
+
+ case 5
+ when 5
+ assert(true)
+ else
+ assert(false)
+ end
+
+ case "foobar"
+ when /^f.*r$/
+ assert(true)
+ else
+ assert(false)
+ end
+
+ case
+ when true
+ assert(true)
+ when false, nil
+ assert(false)
+ else
+ assert(false)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_clone.rb b/ruby_1_8_6/test/ruby/test_clone.rb
new file mode 100644
index 0000000000..43c0cffa1d
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_clone.rb
@@ -0,0 +1,28 @@
+require 'test/unit'
+
+class TestClone < Test::Unit::TestCase
+ module M001; end
+ module M002; end
+ module M003; include M002; end
+ module M002; include M001; end
+ module M003; include M002; end
+
+ def test_clone
+ foo = Object.new
+ def foo.test
+ "test"
+ end
+ bar = foo.clone
+ def bar.test2
+ "test2"
+ end
+
+ assert_equal("test2", bar.test2)
+ assert_equal("test", bar.test)
+ assert_equal("test", foo.test)
+
+ assert_raises(NoMethodError) {foo.test2}
+
+ assert_equal([M003, M002, M001], M003.ancestors)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_condition.rb b/ruby_1_8_6/test/ruby/test_condition.rb
new file mode 100644
index 0000000000..ba2e0688f3
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_condition.rb
@@ -0,0 +1,16 @@
+require 'test/unit'
+
+class TestCondition < Test::Unit::TestCase
+
+ # [should] first test to see if we can run the tests.
+
+ def test_condition
+ $x = '0';
+
+ $x == $x && assert(true)
+ $x != $x && assert(false)
+ $x == $x || assert(false)
+ $x != $x || assert(true)
+
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_const.rb b/ruby_1_8_6/test/ruby/test_const.rb
new file mode 100644
index 0000000000..8d01379dbd
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_const.rb
@@ -0,0 +1,33 @@
+require 'test/unit'
+
+class TestConst < Test::Unit::TestCase
+ TEST1 = 1
+ TEST2 = 2
+
+ module Const
+ TEST3 = 3
+ TEST4 = 4
+ end
+
+ module Const2
+ TEST3 = 6
+ TEST4 = 8
+ end
+
+ def test_const
+ self.class.class_eval {
+ include Const
+ }
+ assert_equal([1,2,3,4], [TEST1,TEST2,TEST3,TEST4])
+
+ self.class.class_eval {
+ include Const2
+ }
+ STDERR.print "intentionally redefines TEST3, TEST4\n" if $VERBOSE
+ assert_equal([1,2,6,8], [TEST1,TEST2,TEST3,TEST4])
+
+ assert_equal(-1, (String <=> Object))
+ assert_equal(1, (Object <=> String))
+ assert_equal(nil, (Array <=> String))
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_defined.rb b/ruby_1_8_6/test/ruby/test_defined.rb
new file mode 100644
index 0000000000..8a7fcf45a9
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_defined.rb
@@ -0,0 +1,43 @@
+require 'test/unit'
+
+class TestDefined < Test::Unit::TestCase
+ class Foo
+ def foo
+ p :foo
+ end
+ protected :foo
+ def bar(f)
+ yield(defined?(self.foo))
+ yield(defined?(f.foo))
+ end
+ end
+
+ def defined_test
+ return !defined?(yield)
+ end
+
+ def test_defined
+ $x = nil
+
+ assert(defined?($x)) # global variable
+ assert_equal('global-variable', defined?($x))# returns description
+
+ assert_nil(defined?(foo)) # undefined
+ foo=5
+ assert(defined?(foo)) # local variable
+
+ assert(defined?(Array)) # constant
+ assert(defined?(::Array)) # toplevel constant
+ assert(defined?(File::Constants)) # nested constant
+ assert(defined?(Object.new)) # method
+ assert(!defined?(Object.print)) # private method
+ assert(defined?(1 == 2)) # operator expression
+
+ f = Foo.new
+ assert_nil(defined?(f.foo))
+ f.bar(f) { |v| assert(v) }
+
+ assert(defined_test) # not iterator
+ assert(!defined_test{}) # called as iterator
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_dir.rb b/ruby_1_8_6/test/ruby/test_dir.rb
new file mode 100644
index 0000000000..09685bee8f
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_dir.rb
@@ -0,0 +1,42 @@
+require 'test/unit'
+
+require 'tmpdir'
+require 'fileutils'
+
+class TestDir < Test::Unit::TestCase
+
+ ROOT = File.join(Dir.tmpdir, "__test_dir__#{$$}")
+
+ def setup
+ Dir.mkdir(ROOT)
+ for i in ?a..?z
+ if i % 2 == 0
+ FileUtils.touch(File.join(ROOT, i.chr))
+ else
+ FileUtils.mkdir(File.join(ROOT, i.chr))
+ end
+ end
+ end
+
+ def teardown
+ FileUtils.rm_rf ROOT if File.directory?(ROOT)
+ end
+
+ def test_seek
+ dir = Dir.open(ROOT)
+ begin
+ cache = []
+ loop do
+ pos = dir.tell
+ break unless name = dir.read
+ cache << [pos, name]
+ end
+ for x in cache.sort_by {|x| x[0] % 3 } # shuffle
+ dir.seek(x[0])
+ assert_equal(x[1], dir.read)
+ end
+ ensure
+ dir.close
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_env.rb b/ruby_1_8_6/test/ruby/test_env.rb
new file mode 100644
index 0000000000..3a65f91fa4
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_env.rb
@@ -0,0 +1,82 @@
+require 'test/unit'
+
+class TestEnv < Test::Unit::TestCase
+ IGNORE_CASE = /djgpp|bccwin|mswin|mingw/ =~ RUBY_PLATFORM
+
+ def setup
+ @backup = ENV.delete('test')
+ @BACKUP = ENV.delete('TEST')
+ end
+
+ def teardown
+ ENV['test'] = @backup if @backup
+ ENV['TEST'] = @BACKUP if @BACKUP
+ end
+
+ def test_bracket
+ assert_nil(ENV['test'])
+ assert_nil(ENV['TEST'])
+ ENV['test'] = 'foo'
+ assert_equal('foo', ENV['test'])
+ if IGNORE_CASE
+ assert_equal('foo', ENV['TEST'])
+ else
+ assert_nil(ENV['TEST'])
+ end
+ ENV['TEST'] = 'bar'
+ assert_equal('bar', ENV['TEST'])
+ if IGNORE_CASE
+ assert_equal('bar', ENV['test'])
+ else
+ assert_equal('foo', ENV['test'])
+ end
+
+ assert_raises(TypeError) {
+ tmp = ENV[1]
+ }
+ assert_raises(TypeError) {
+ ENV[1] = 'foo'
+ }
+ assert_raises(TypeError) {
+ ENV['test'] = 0
+ }
+ end
+
+ def test_has_value
+ val = 'a'
+ val.succ! while ENV.has_value?(val) && ENV.has_value?(val.upcase)
+ ENV['test'] = val[0...-1]
+
+ assert_equal(false, ENV.has_value?(val))
+ assert_equal(false, ENV.has_value?(val.upcase))
+ ENV['test'] = val
+ assert_equal(true, ENV.has_value?(val))
+ assert_equal(false, ENV.has_value?(val.upcase))
+ ENV['test'] = val.upcase
+ assert_equal(false, ENV.has_value?(val))
+ assert_equal(true, ENV.has_value?(val.upcase))
+ end
+
+ def test_index
+ val = 'a'
+ val.succ! while ENV.has_value?(val) && ENV.has_value?(val.upcase)
+ ENV['test'] = val[0...-1]
+
+ assert_nil(ENV.index(val))
+ assert_nil(ENV.index(val.upcase))
+ ENV['test'] = val
+ if IGNORE_CASE
+ assert_equal('TEST', ENV.index(val).upcase)
+ else
+ assert_equal('test', ENV.index(val))
+ end
+ assert_nil(ENV.index(val.upcase))
+ ENV['test'] = val.upcase
+ assert_nil(ENV.index(val))
+ if IGNORE_CASE
+ assert_equal('TEST', ENV.index(val.upcase).upcase)
+ else
+ assert_equal('test', ENV.index(val.upcase))
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_eval.rb b/ruby_1_8_6/test/ruby/test_eval.rb
new file mode 100644
index 0000000000..6b3fea7bb4
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_eval.rb
@@ -0,0 +1,157 @@
+require 'test/unit'
+
+class TestEval < Test::Unit::TestCase
+ # eval with binding
+ def test_ev
+ local1 = "local1"
+ lambda {
+ local2 = "local2"
+ return binding
+ }.call
+ end
+
+ def test_eval
+ assert_nil(eval(""))
+ $bad=false
+ eval 'while false; $bad = true; print "foo\n" end'
+ assert(!$bad)
+
+ assert(eval('TRUE'))
+ assert(eval('true'))
+ assert(!eval('NIL'))
+ assert(!eval('nil'))
+ assert(!eval('FALSE'))
+ assert(!eval('false'))
+
+ $foo = 'assert(true)'
+ begin
+ eval $foo
+ rescue
+ assert(false)
+ end
+
+ assert_equal('assert(true)', eval("$foo"))
+ assert_equal(true, eval("true"))
+ i = 5
+ assert(eval("i == 5"))
+ assert_equal(5, eval("i"))
+ assert(eval("defined? i"))
+
+ $x = test_ev
+ assert_equal("local1", eval("local1", $x)) # normal local var
+ assert_equal("local2", eval("local2", $x)) # nested local var
+ $bad = true
+ begin
+ p eval("local1")
+ rescue NameError # must raise error
+ $bad = false
+ end
+ assert(!$bad)
+
+ # !! use class_eval to avoid nested definition
+ self.class.class_eval %q(
+ module EvTest
+ EVTEST1 = 25
+ evtest2 = 125
+ $x = binding
+ end
+ )
+ assert_equal(25, eval("EVTEST1", $x)) # constant in module
+ assert_equal(125, eval("evtest2", $x)) # local var in module
+ $bad = true
+ begin
+ eval("EVTEST1")
+ rescue NameError # must raise error
+ $bad = false
+ end
+ assert(!$bad)
+
+ x = proc{}
+ eval "i4 = 1", x
+ assert_equal(1, eval("i4", x))
+ x = proc{proc{}}.call
+ eval "i4 = 22", x
+ assert_equal(22, eval("i4", x))
+ $x = []
+ x = proc{proc{}}.call
+ eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
+ assert_equal(8, $x[4].call)
+
+ x = binding
+ eval "i = 1", x
+ assert_equal(1, eval("i", x))
+ x = proc{binding}.call
+ eval "i = 22", x
+ assert_equal(22, eval("i", x))
+ $x = []
+ x = proc{binding}.call
+ eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
+ assert_equal(8, $x[4].call)
+ x = proc{binding}.call
+ eval "for i6 in 1..1; j6=i6; end", x
+ assert(eval("defined? i6", x))
+ assert(eval("defined? j6", x))
+
+ proc {
+ p = binding
+ eval "foo11 = 1", p
+ foo22 = 5
+ proc{foo11=22}.call
+ proc{foo22=55}.call
+ assert_equal(eval("foo11"), eval("foo11", p))
+ assert_equal(1, eval("foo11"))
+ assert_equal(eval("foo22"), eval("foo22", p))
+ assert_equal(55, eval("foo22"))
+ }.call
+
+ p1 = proc{i7 = 0; proc{i7}}.call
+ assert_equal(0, p1.call)
+ eval "i7=5", p1
+ assert_equal(5, p1.call)
+ assert(!defined?(i7))
+
+ p1 = proc{i7 = 0; proc{i7}}.call
+ i7 = nil
+ assert_equal(0, p1.call)
+ eval "i7=1", p1
+ assert_equal(1, p1.call)
+ eval "i7=5", p1
+ assert_equal(5, p1.call)
+ assert_nil(i7)
+ end
+
+ def test_nil_instance_eval_cvar # [ruby-dev:24103]
+ def nil.test_binding
+ binding
+ end
+ bb = eval("nil.instance_eval \"binding\"", nil.test_binding)
+ assert_raise(NameError) { eval("@@a", bb) }
+ class << nil
+ remove_method :test_binding
+ end
+ end
+
+ def test_fixnum_instance_eval_cvar # [ruby-dev:24213]
+ assert_raise(NameError) { 1.instance_eval "@@a" }
+ end
+
+ def test_cvar_scope_with_instance_eval # [ruby-dev:24223]
+ Fixnum.class_eval "@@test_cvar_scope_with_instance_eval = 1" # depends on [ruby-dev:24229]
+ @@test_cvar_scope_with_instance_eval = 4
+ assert_equal(4, 1.instance_eval("@@test_cvar_scope_with_instance_eval"))
+ Fixnum.__send__(:remove_class_variable, :@@test_cvar_scope_with_instance_eval)
+ end
+
+ def test_eval_and_define_method # [ruby-dev:24228]
+ assert_nothing_raised {
+ def temporally_method_for_test_eval_and_define_method(&block)
+ lambda {
+ class << Object.new; self end.__send__(:define_method, :zzz, &block)
+ }
+ end
+ v = eval("temporally_method_for_test_eval_and_define_method {}")
+ {}[0] = {}
+ v.call
+ }
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_exception.rb b/ruby_1_8_6/test/ruby/test_exception.rb
new file mode 100644
index 0000000000..4c27c52f3c
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_exception.rb
@@ -0,0 +1,187 @@
+require 'test/unit'
+
+class TestException < Test::Unit::TestCase
+ def test_exception
+ begin
+ raise "this must be handled"
+ assert(false)
+ rescue
+ assert(true)
+ end
+
+ $bad = true
+ begin
+ raise "this must be handled no.2"
+ rescue
+ if $bad
+ $bad = false
+ retry
+ assert(false)
+ end
+ end
+ assert(true)
+
+ # exception in rescue clause
+ $string = "this must be handled no.3"
+ e = assert_raises(RuntimeError) do
+ begin
+ raise "exception in rescue clause"
+ rescue
+ raise $string
+ end
+ assert(false)
+ end
+ assert_equal($string, e.message)
+
+ # exception in ensure clause
+ $string = "exception in ensure clause"
+ e = assert_raises(RuntimeError) do
+ begin
+ raise "this must be handled no.4"
+ ensure
+ assert_instance_of(RuntimeError, $!)
+ assert_equal("this must be handled no.4", $!.message)
+ raise "exception in ensure clause"
+ end
+ assert(false)
+ end
+ assert_equal($string, e.message)
+
+ $bad = true
+ begin
+ begin
+ raise "this must be handled no.5"
+ ensure
+ $bad = false
+ end
+ rescue
+ end
+ assert(!$bad)
+
+ $bad = true
+ begin
+ begin
+ raise "this must be handled no.6"
+ ensure
+ $bad = false
+ end
+ rescue
+ end
+ assert(!$bad)
+
+ $bad = true
+ while true
+ begin
+ break
+ ensure
+ $bad = false
+ end
+ end
+ assert(!$bad)
+
+ assert(catch(:foo) {
+ loop do
+ loop do
+ throw :foo, true
+ break
+ end
+ break
+ assert(false) # should no reach here
+ end
+ false
+ })
+
+ end
+
+ def test_else
+ begin
+ assert(true)
+ rescue
+ assert(false)
+ else
+ assert(true)
+ end
+
+ begin
+ assert(true)
+ raise
+ assert(false)
+ rescue
+ assert(true)
+ else
+ assert(false)
+ end
+
+ begin
+ assert(true)
+ begin
+ assert(true)
+ rescue
+ assert(false)
+ else
+ assert(true)
+ end
+ assert(true)
+ rescue
+ assert(false)
+ else
+ assert(true)
+ end
+
+ begin
+ assert(true)
+ begin
+ assert(true)
+ raise
+ assert(false)
+ rescue
+ assert(true)
+ else
+ assert(false)
+ end
+ assert(true)
+ rescue
+ assert(false)
+ else
+ assert(true)
+ end
+
+ begin
+ assert(true)
+ begin
+ assert(true)
+ rescue
+ assert(false)
+ else
+ assert(true)
+ end
+ assert(true)
+ raise
+ assert(false)
+ rescue
+ assert(true)
+ else
+ assert(false)
+ end
+
+ begin
+ assert(true)
+ begin
+ assert(true)
+ raise
+ assert(false)
+ rescue
+ assert(true)
+ else
+ assert(false)
+ end
+ assert(true)
+ raise
+ assert(false)
+ rescue
+ assert(true)
+ else
+ assert(false)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_file.rb b/ruby_1_8_6/test/ruby/test_file.rb
new file mode 100644
index 0000000000..2458dde347
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_file.rb
@@ -0,0 +1,108 @@
+require 'test/unit'
+require 'tempfile'
+$:.replace([File.dirname(File.expand_path(__FILE__))] | $:)
+require 'ut_eof'
+
+class TestFile < Test::Unit::TestCase
+
+ # I don't know Ruby's spec about "unlink-before-close" exactly.
+ # This test asserts current behaviour.
+ def test_unlink_before_close
+ filename = File.basename(__FILE__) + ".#{$$}"
+ w = File.open(filename, "w")
+ w << "foo"
+ w.close
+ r = File.open(filename, "r")
+ begin
+ if /(mswin|bccwin|mingw|emx)/ =~ RUBY_PLATFORM
+ begin
+ File.unlink(filename)
+ assert(false)
+ rescue Errno::EACCES
+ assert(true)
+ end
+ else
+ File.unlink(filename)
+ assert(true)
+ end
+ ensure
+ r.close
+ File.unlink(filename) if File.exist?(filename)
+ end
+ end
+
+ include TestEOF
+ def open_file(content)
+ f = Tempfile.new("test-eof")
+ f << content
+ f.rewind
+ yield f
+ end
+ alias open_file_rw open_file
+
+ include TestEOF::Seek
+
+ def test_fnmatch
+ # from [ruby-dev:22815] and [ruby-dev:22819]
+ assert(true, File.fnmatch('\[1\]' , '[1]'))
+ assert(true, File.fnmatch('*?', 'a'))
+ end
+
+ def test_truncate_wbuf # [ruby-dev:24191]
+ f = Tempfile.new("test-truncate")
+ f.print "abc"
+ f.truncate(0)
+ f.print "def"
+ f.close
+ assert_equal("\0\0\0def", File.read(f.path))
+ end
+
+ def test_truncate_rbuf # [ruby-dev:24197]
+ f = Tempfile.new("test-truncate")
+ f.puts "abc"
+ f.puts "def"
+ f.close
+ f.open
+ assert_equal("abc\n", f.gets)
+ f.truncate(3)
+ assert_equal(nil, f.gets)
+ end
+
+ def test_read_all_extended_file
+ f = Tempfile.new("test-extended-file")
+ assert_nil(f.getc)
+ open(f.path, "w") {|g| g.print "a" }
+ assert_equal("a", f.read)
+ end
+
+ def test_gets_extended_file
+ f = Tempfile.new("test-extended-file")
+ assert_nil(f.getc)
+ open(f.path, "w") {|g| g.print "a" }
+ assert_equal("a", f.gets("a"))
+ end
+
+ def test_gets_para_extended_file
+ f = Tempfile.new("test-extended-file")
+ assert_nil(f.getc)
+ open(f.path, "w") {|g| g.print "\na" }
+ assert_equal("a", f.gets(""))
+ end
+
+ def test_each_byte_extended_file
+ f = Tempfile.new("test-extended-file")
+ assert_nil(f.getc)
+ open(f.path, "w") {|g| g.print "a" }
+ result = []
+ f.each_byte {|b| result << b }
+ assert_equal([?a], result)
+ end
+
+ def test_getc_extended_file
+ f = Tempfile.new("test-extended-file")
+ assert_nil(f.getc)
+ open(f.path, "w") {|g| g.print "a" }
+ assert_equal(?a, f.getc)
+ end
+
+end
diff --git a/ruby_1_8_6/test/ruby/test_float.rb b/ruby_1_8_6/test/ruby/test_float.rb
new file mode 100644
index 0000000000..d559ce5cab
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_float.rb
@@ -0,0 +1,113 @@
+require 'test/unit'
+
+class TestFloat < Test::Unit::TestCase
+ def test_float
+ assert_equal(2, 2.6.floor)
+ assert_equal(-3, (-2.6).floor)
+ assert_equal(3, 2.6.ceil)
+ assert_equal(-2, (-2.6).ceil)
+ assert_equal(2, 2.6.truncate)
+ assert_equal(-2, (-2.6).truncate)
+ assert_equal(3, 2.6.round)
+ assert_equal(-2, (-2.4).truncate)
+ assert((13.4 % 1 - 0.4).abs < 0.0001)
+ end
+
+ def nan_test(x,y)
+ extend Test::Unit::Assertions
+ assert(x != y)
+ assert_equal(false, (x < y))
+ assert_equal(false, (x > y))
+ assert_equal(false, (x <= y))
+ assert_equal(false, (x >= y))
+ end
+ def test_nan
+ nan = 0.0/0
+ nan_test(nan, nan)
+ nan_test(nan, 0)
+ nan_test(nan, 1)
+ nan_test(nan, -1)
+ nan_test(nan, 1000)
+ nan_test(nan, -1000)
+ nan_test(nan, 1_000_000_000_000)
+ nan_test(nan, -1_000_000_000_000)
+ nan_test(nan, 100.0);
+ nan_test(nan, -100.0);
+ nan_test(nan, 0.001);
+ nan_test(nan, -0.001);
+ nan_test(nan, 1.0/0);
+ nan_test(nan, -1.0/0);
+ end
+
+ def test_precision
+ u = 3.7517675036461267e+17
+ v = sprintf("%.16e", u).to_f
+ assert_in_delta(u, v, u.abs * Float::EPSILON)
+ assert_in_delta(u, v, v.abs * Float::EPSILON)
+ end
+
+ def test_symmetry_bignum # [ruby-bugs-ja:118]
+ a = 100000000000000000000000
+ b = 100000000000000000000000.0
+ assert_equal(a == b, b == a)
+ end
+
+ def test_strtod
+ a = Float("0")
+ assert(a.abs < Float::EPSILON)
+ a = Float("0.0")
+ assert(a.abs < Float::EPSILON)
+ a = Float("+0.0")
+ assert(a.abs < Float::EPSILON)
+ a = Float("-0.0")
+ assert(a.abs < Float::EPSILON)
+ a = Float("0.0000000000000000001")
+ assert(a != 0.0)
+ a = Float("+0.0000000000000000001")
+ assert(a != 0.0)
+ a = Float("-0.0000000000000000001")
+ assert(a != 0.0)
+ a = Float(".0")
+ assert(a.abs < Float::EPSILON)
+ a = Float("+.0")
+ assert(a.abs < Float::EPSILON)
+ a = Float("-.0")
+ assert(a.abs < Float::EPSILON)
+ assert(a.abs < Float::EPSILON)
+ assert_raise(ArgumentError){Float(".")}
+ assert_raise(ArgumentError){Float("+")}
+ assert_raise(ArgumentError){Float("+.")}
+ assert_raise(ArgumentError){Float("-")}
+ assert_raise(ArgumentError){Float("-.")}
+ assert_raise(ArgumentError){Float("1e")}
+ # add expected behaviour here.
+ end
+
+ def test_divmod
+ assert_equal([2, 3.5], 11.5.divmod(4))
+ assert_equal([-3, -0.5], 11.5.divmod(-4))
+ assert_equal([-3, 0.5], (-11.5).divmod(4))
+ assert_equal([2, -3.5], (-11.5).divmod(-4))
+ end
+
+ def test_div
+ assert_equal(2, 11.5.div(4))
+ assert_equal(-3, 11.5.div(-4))
+ assert_equal(-3, (-11.5).div(4))
+ assert_equal(2, (-11.5).div(-4))
+ end
+
+ def test_modulo
+ assert_equal(3.5, 11.5.modulo(4))
+ assert_equal(-0.5, 11.5.modulo(-4))
+ assert_equal(0.5, (-11.5).modulo(4))
+ assert_equal(-3.5, (-11.5).modulo(-4))
+ end
+
+ def test_remainder
+ assert_equal(3.5, 11.5.remainder(4))
+ assert_equal(3.5, 11.5.remainder(-4))
+ assert_equal(-3.5, (-11.5).remainder(4))
+ assert_equal(-3.5, (-11.5).remainder(-4))
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_gc.rb b/ruby_1_8_6/test/ruby/test_gc.rb
new file mode 100644
index 0000000000..d0b4e3df77
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_gc.rb
@@ -0,0 +1,30 @@
+require 'test/unit'
+
+class TestGc < Test::Unit::TestCase
+ class S
+ def initialize(a)
+ @a = a
+ end
+ end
+
+ def test_gc
+ assert_nothing_raised do
+ 1.upto(10000) {
+ tmp = [0,1,2,3,4,5,6,7,8,9]
+ }
+ tmp = nil
+ end
+ l=nil
+ 100000.times {
+ l = S.new(l)
+ }
+ GC.start
+ assert true # reach here or dumps core
+ l = []
+ 100000.times {
+ l.push([l])
+ }
+ GC.start
+ assert true # reach here or dumps core
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_hash.rb b/ruby_1_8_6/test/ruby/test_hash.rb
new file mode 100644
index 0000000000..5bec012bf8
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_hash.rb
@@ -0,0 +1,74 @@
+require 'test/unit'
+
+class TestHash < Test::Unit::TestCase
+ def test_hash
+ x = {1=>2, 2=>4, 3=>6}
+ y = {1, 2, 2, 4, 3, 6}
+
+ assert_equal(2, x[1])
+
+ assert(begin
+ for k,v in y
+ raise if k*2 != v
+ end
+ true
+ rescue
+ false
+ end)
+
+ assert_equal(3, x.length)
+ assert(x.has_key?(1))
+ assert(x.has_value?(4))
+ assert_equal([4,6], x.values_at(2,3))
+ assert_equal({1=>2, 2=>4, 3=>6}, x)
+
+ z = y.keys.join(":")
+ assert_equal("1:2:3", z)
+
+ z = y.values.join(":")
+ assert_equal("2:4:6", z)
+ assert_equal(x, y)
+
+ y.shift
+ assert_equal(2, y.length)
+
+ z = [1,2]
+ y[z] = 256
+ assert_equal(256, y[z])
+
+ x = Hash.new(0)
+ x[1] = 1
+ assert_equal(1, x[1])
+ assert_equal(0, x[2])
+
+ x = Hash.new([])
+ assert_equal([], x[22])
+ assert_same(x[22], x[22])
+
+ x = Hash.new{[]}
+ assert_equal([], x[22])
+ assert_not_same(x[22], x[22])
+
+ x = Hash.new{|h,k| z = k; h[k] = k*2}
+ z = 0
+ assert_equal(44, x[22])
+ assert_equal(22, z)
+ z = 0
+ assert_equal(44, x[22])
+ assert_equal(0, z)
+ x.default = 5
+ assert_equal(5, x[23])
+
+ x = Hash.new
+ def x.default(k)
+ $z = k
+ self[k] = k*2
+ end
+ $z = 0
+ assert_equal(44, x[22])
+ assert_equal(22, $z)
+ $z = 0
+ assert_equal(44, x[22])
+ assert_equal(0, $z)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_ifunless.rb b/ruby_1_8_6/test/ruby/test_ifunless.rb
new file mode 100644
index 0000000000..bffc794512
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_ifunless.rb
@@ -0,0 +1,14 @@
+require 'test/unit'
+
+class TestIfunless < Test::Unit::TestCase
+ def test_if_unless
+ $x = 'test';
+ assert(if $x == $x then true else false end)
+ $bad = false
+ unless $x == $x
+ $bad = true
+ end
+ assert(!$bad)
+ assert(unless $x != $x then true else false end)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_io.rb b/ruby_1_8_6/test/ruby/test_io.rb
new file mode 100644
index 0000000000..642c8f4430
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_io.rb
@@ -0,0 +1,11 @@
+require 'test/unit'
+
+class TestIO < Test::Unit::TestCase
+ def test_gets_rs
+ r, w = IO.pipe
+ w.print "\377xyz"
+ w.close
+ assert_equal("\377", r.gets("\377"), "[ruby-dev:24460]")
+ r.close
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_iterator.rb b/ruby_1_8_6/test/ruby/test_iterator.rb
new file mode 100644
index 0000000000..2cd48b29a4
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_iterator.rb
@@ -0,0 +1,477 @@
+require 'test/unit'
+
+class Array
+ def iter_test1
+ collect{|e| [e, yield(e)]}.sort{|a,b|a[1]<=>b[1]}
+ end
+ def iter_test2
+ a = collect{|e| [e, yield(e)]}
+ a.sort{|a,b|a[1]<=>b[1]}
+ end
+end
+
+class TestIterator < Test::Unit::TestCase
+ def ttt
+ assert(iterator?)
+ end
+
+ def test_iterator
+ assert(!iterator?)
+
+ ttt{}
+
+ # yield at top level !! here's not toplevel
+ assert(!defined?(yield))
+ end
+
+ def test_array
+ $x = [1, 2, 3, 4]
+ $y = []
+
+ # iterator over array
+ for i in $x
+ $y.push i
+ end
+ assert_equal($x, $y)
+ end
+
+ def tt
+ 1.upto(10) {|i|
+ yield i
+ }
+ end
+
+ def tt2(dummy)
+ yield 1
+ end
+
+ def tt3(&block)
+ tt2(raise(ArgumentError,""),&block)
+ end
+
+ def test_nested_iterator
+ i = 0
+ tt{|i| break if i == 5}
+ assert_equal(5, i)
+
+ assert_raises(ArgumentError) do
+ tt3{}
+ end
+ end
+
+ def tt4 &block
+ tt2(raise(ArgumentError,""),&block)
+ end
+
+ def test_block_argument_without_paren
+ assert_raises(ArgumentError) do
+ tt4{}
+ end
+ end
+
+ # iterator break/redo/next/retry
+ def test_break
+ done = true
+ loop{
+ break
+ done = false # should not reach here
+ }
+ assert(done)
+
+ done = false
+ $bad = false
+ loop {
+ break if done
+ done = true
+ next
+ $bad = true # should not reach here
+ }
+ assert(!$bad)
+
+ done = false
+ $bad = false
+ loop {
+ break if done
+ done = true
+ redo
+ $bad = true # should not reach here
+ }
+ assert(!$bad)
+
+ $x = []
+ for i in 1 .. 7
+ $x.push i
+ end
+ assert_equal(7, $x.size)
+ assert_equal([1, 2, 3, 4, 5, 6, 7], $x)
+
+ $done = false
+ $x = []
+ for i in 1 .. 7 # see how retry works in iterator loop
+ if i == 4 and not $done
+ $done = true
+ retry
+ end
+ $x.push(i)
+ end
+ assert_equal(10, $x.size)
+ assert_equal([1, 2, 3, 1, 2, 3, 4, 5, 6, 7], $x)
+ end
+
+ def test_append_method_to_built_in_class
+ $x = [[1,2],[3,4],[5,6]]
+ assert_equal($x.iter_test1{|x|x}, $x.iter_test2{|x|x})
+ end
+
+ class IterTest
+ def initialize(e); @body = e; end
+
+ def each0(&block); @body.each(&block); end
+ def each1(&block); @body.each {|*x| block.call(*x) } end
+ def each2(&block); @body.each {|*x| block.call(x) } end
+ def each3(&block); @body.each {|x| block.call(*x) } end
+ def each4(&block); @body.each {|x| block.call(x) } end
+ def each5; @body.each {|*x| yield(*x) } end
+ def each6; @body.each {|*x| yield(x) } end
+ def each7; @body.each {|x| yield(*x) } end
+ def each8; @body.each {|x| yield(x) } end
+
+ def f(a)
+ a
+ end
+ end
+
+ def test_itertest
+ assert_equal([1], IterTest.new(nil).method(:f).to_proc.call([1]))
+ m = /\w+/.match("abc")
+ assert_equal([m], IterTest.new(nil).method(:f).to_proc.call([m]))
+
+ IterTest.new([0]).each0 {|x| assert_equal(0, x)}
+ IterTest.new([1]).each1 {|x| assert_equal(1, x)}
+ IterTest.new([2]).each2 {|x| assert_equal([2], x)}
+ IterTest.new([3]).each3 {|x| assert_equal(3, x)}
+ IterTest.new([4]).each4 {|x| assert_equal(4, x)}
+ IterTest.new([5]).each5 {|x| assert_equal(5, x)}
+ IterTest.new([6]).each6 {|x| assert_equal([6], x)}
+ IterTest.new([7]).each7 {|x| assert_equal(7, x)}
+ IterTest.new([8]).each8 {|x| assert_equal(8, x)}
+
+ IterTest.new([[0]]).each0 {|x| assert_equal([0], x)}
+ IterTest.new([[1]]).each1 {|x| assert_equal([1], x)}
+ IterTest.new([[2]]).each2 {|x| assert_equal([[2]], x)}
+ IterTest.new([[3]]).each3 {|x| assert_equal(3, x)}
+ IterTest.new([[4]]).each4 {|x| assert_equal([4], x)}
+ IterTest.new([[5]]).each5 {|x| assert_equal([5], x)}
+ IterTest.new([[6]]).each6 {|x| assert_equal([[6]], x)}
+ IterTest.new([[7]]).each7 {|x| assert_equal(7, x)}
+ IterTest.new([[8]]).each8 {|x| assert_equal([8], x)}
+
+ IterTest.new([[0,0]]).each0 {|x| assert_equal([0,0], x)}
+ IterTest.new([[8,8]]).each8 {|x| assert_equal([8,8], x)}
+ end
+
+ def m(var)
+ var
+ end
+
+ def m1
+ m(block_given?)
+ end
+
+ def m2
+ m(block_given?,&proc{})
+ end
+
+ def test_block_given
+ assert(m1{p 'test'})
+ assert(m2{p 'test'})
+ assert(!m1())
+ assert(!m2())
+ end
+
+ def m3(var, &block)
+ m(yield(var), &block)
+ end
+
+ def m4(&block)
+ m(m1(), &block)
+ end
+
+ def test_block_passing
+ assert(!m4())
+ assert(!m4 {})
+ assert_equal(100, m3(10) {|x|x*x})
+ end
+
+ class C
+ include Enumerable
+ def initialize
+ @a = [1,2,3]
+ end
+ def each(&block)
+ @a.each(&block)
+ end
+ end
+
+ def test_collect
+ assert_equal([1,2,3], C.new.collect{|n| n})
+ end
+
+ def test_proc
+ assert_instance_of(Proc, lambda{})
+ assert_instance_of(Proc, Proc.new{})
+ lambda{|a|assert_equal(a, 1)}.call(1)
+ end
+
+ def test_block
+ assert_instance_of(NilClass, get_block)
+ assert_instance_of(Proc, get_block{})
+ end
+
+ def test_argument
+ assert_nothing_raised {lambda{||}.call}
+ assert_raises(ArgumentError) {lambda{||}.call(1)}
+ assert_nothing_raised {lambda{|a,|}.call(1)}
+ assert_raises(ArgumentError) {lambda{|a,|}.call()}
+ assert_raises(ArgumentError) {lambda{|a,|}.call(1,2)}
+ end
+
+ def get_block(&block)
+ block
+ end
+
+ def test_get_block
+ assert_instance_of(Proc, get_block{})
+ assert_nothing_raised {get_block{||}.call()}
+ assert_nothing_raised {get_block{||}.call(1)}
+ assert_nothing_raised {get_block{|a,|}.call(1)}
+ assert_nothing_raised {get_block{|a,|}.call()}
+ assert_nothing_raised {get_block{|a,|}.call(1,2)}
+
+ assert_nothing_raised {get_block(&lambda{||}).call()}
+ assert_raises(ArgumentError) {get_block(&lambda{||}).call(1)}
+ assert_nothing_raised {get_block(&lambda{|a,|}).call(1)}
+ assert_raises(ArgumentError) {get_block(&lambda{|a,|}).call(1,2)}
+
+ block = get_block{11}
+ assert_instance_of(Proc, block)
+ assert_instance_of(Proc, block.to_proc)
+ assert_equal(block.clone.call, 11)
+ assert_instance_of(Proc, get_block(&block))
+
+ lambda = lambda{44}
+ assert_instance_of(Proc, lambda)
+ assert_instance_of(Proc, lambda.to_proc)
+ assert_equal(lambda.clone.call, 44)
+ assert_instance_of(Proc, get_block(&lambda))
+
+ assert_equal(1, Proc.new{|a,| a}.call(1,2,3))
+ assert_nothing_raised {Proc.new{|a,|}.call(1,2)}
+ end
+
+ def return1_test
+ Proc.new {
+ return 55
+ }.call + 5
+ end
+
+ def test_return1
+ assert_equal(55, return1_test())
+ end
+
+ def return2_test
+ lambda {
+ return 55
+ }.call + 5
+ end
+
+ def test_return2
+ assert_equal(60, return2_test())
+ end
+
+ def proc_call(&b)
+ b.call
+ end
+ def proc_yield()
+ yield
+ end
+ def proc_return1
+ proc_call{return 42}+1
+ end
+
+ def test_proc_return1
+ assert_equal(42, proc_return1())
+ end
+
+ def proc_return2
+ proc_yield{return 42}+1
+ end
+
+ def test_proc_return2
+ assert_equal(42, proc_return2())
+ end
+
+ def test_ljump
+ block = get_block{11}
+ lambda = lambda{44}
+ assert_raises(LocalJumpError) {get_block{break}.call}
+ assert_nothing_raised {lambda{break}.call}
+ assert_instance_of(LocalJumpError, (get_block{break}.call rescue $!))
+
+ assert_equal(-1, block.arity)
+ assert_equal(-1, lambda.arity)
+ assert_equal(0, lambda{||}.arity)
+ assert_equal(1, lambda{|a|}.arity)
+ assert_equal(1, lambda{|a,|}.arity)
+ assert_equal(2, lambda{|a,b|}.arity)
+ end
+
+ def marity_test(m)
+ method = method(m)
+ assert_equal(method.arity, method.to_proc.arity)
+ end
+
+ def test_marity
+ marity_test(:assert)
+ marity_test(:marity_test)
+ marity_test(:p)
+
+ lambda(&method(:assert)).call(true)
+ lambda(&get_block{|a,n| assert(a,n)}).call(true, "marity")
+ end
+
+ def foo
+ yield([:key, :value])
+ end
+ def bar(&blk)
+ blk.call([:key, :value])
+ end
+
+ def test_yield_vs_call
+ foo{|k,v| assert_equal([:key, :value], [k,v])}
+ bar{|k,v| assert_equal([:key, :value], [k,v])}
+ end
+
+ class H
+ def each
+ yield [:key, :value]
+ end
+ end
+
+ def test_assoc_yield
+ [{:key=>:value}, H.new].each {|h|
+ h.each{|a| assert_equal([:key, :value], a)}
+ h.each{|*a| assert_equal([[:key, :value]], a)}
+ h.each{|k,v| assert_equal([:key, :value], [k,v])}
+ }
+ end
+
+ class ITER_TEST1
+ def a
+ block_given?
+ end
+ end
+
+ class ITER_TEST2 < ITER_TEST1
+ include Test::Unit::Assertions
+ def a
+ assert(super)
+ super
+ end
+ end
+
+ def test_iter_test2
+ assert(ITER_TEST2.new.a {})
+ end
+
+ class ITER_TEST3
+ def foo x
+ return yield if block_given?
+ x
+ end
+ end
+
+ class ITER_TEST4 < ITER_TEST3
+ include Test::Unit::Assertions
+ def foo x
+ assert_equal(super, yield)
+ assert_equal(x, super(x, &nil))
+ end
+ end
+
+ def test_iter4
+ ITER_TEST4.new.foo(44){55}
+ end
+
+ def test_break__nested_loop1
+ _test_break__nested_loop1 do
+ break
+ end
+ end
+
+ def _test_break__nested_loop1
+ while true
+ yield
+ end
+ assert(false, "must not reach here")
+ end
+
+ def test_break__nested_loop2
+ _test_break__nested_loop2 do
+ break
+ end
+ end
+
+ def _test_break__nested_loop2
+ until false
+ yield
+ end
+ assert(false, "must not reach here")
+ end
+
+ def test_break__nested_loop3
+ _test_break__nested_loop3 do
+ break
+ end
+ end
+
+ def _test_break__nested_loop3
+ loop do
+ yield
+ end
+ assert(false, "must not reach here")
+ end
+
+ def test_break_from_enum
+ result = ["a"].inject("ng") {|x,y| break "ok"}
+ assert_equal("ok", result)
+ end
+
+ def _test_return_trace_func(x)
+ set_trace_func(proc {})
+ [].fetch(2) {return x}
+ ensure
+ set_trace_func(nil)
+ end
+
+ def test_return_trace_func
+ ok = "returned gracefully"
+ result = "skipped"
+ result = _test_return_trace_func(ok)
+ ensure
+ assert_equal(ok, result)
+ return
+ end
+
+ class IterString < ::String
+ def ===(other)
+ super if !block_given?
+ end
+ end
+
+ # Check that the block passed to an iterator
+ # does not get propagated inappropriately
+ def test_block_given_within_iterator
+ assert_equal(["b"], ["a", "b", "c"].grep(IterString.new("b")) {|s| s})
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_marshal.rb b/ruby_1_8_6/test/ruby/test_marshal.rb
new file mode 100644
index 0000000000..9c9fd9470b
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_marshal.rb
@@ -0,0 +1,48 @@
+require 'test/unit'
+dir = File.dirname(File.expand_path(__FILE__))
+orgpath = $:.dup
+begin
+ $:.push(dir)
+ require 'marshaltestlib'
+ensure
+ $:.replace(orgpath)
+end
+
+class TestMarshal < Test::Unit::TestCase
+ include MarshalTestLib
+
+ def encode(o)
+ Marshal.dump(o)
+ end
+
+ def decode(s)
+ Marshal.load(s)
+ end
+
+ def fact(n)
+ return 1 if n == 0
+ f = 1
+ while n>0
+ f *= n
+ n -= 1
+ end
+ return f
+ end
+
+ StrClone=String.clone;
+
+ def test_marshal
+ $x = [1,2,3,[4,5,"foo"],{1=>"bar"},2.5,fact(30)]
+ $y = Marshal.dump($x)
+ assert_equal($x, Marshal.load($y))
+
+ assert_instance_of(StrClone, Marshal.load(Marshal.dump(StrClone.new("abc"))))
+
+ [[1,2,3,4], [81, 2, 118, 3146]].each { |w,x,y,z|
+ a = (x.to_f + y.to_f / z.to_f) * Math.exp(w.to_f / (x.to_f + y.to_f / z.to_f))
+ ma = Marshal.dump(a)
+ b = Marshal.load(ma)
+ assert_equal(a, b)
+ }
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_math.rb b/ruby_1_8_6/test/ruby/test_math.rb
new file mode 100644
index 0000000000..e1e49dba01
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_math.rb
@@ -0,0 +1,12 @@
+require 'test/unit'
+
+class TestMath < Test::Unit::TestCase
+ def test_math
+ assert_equal(2, Math.sqrt(4))
+
+ self.class.class_eval {
+ include Math
+ }
+ assert_equal(2, sqrt(4))
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_method.rb b/ruby_1_8_6/test/ruby/test_method.rb
new file mode 100644
index 0000000000..ef28098dce
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_method.rb
@@ -0,0 +1,53 @@
+require 'test/unit'
+
+class TestMethod < Test::Unit::TestCase
+ def m0() end
+ def m1(a) end
+ def m2(a, b) end
+ def mo1(a = nil, &b) end
+ def mo2(a, b = nil) end
+ def mo3(*a) end
+ def mo4(a, *b, &c) end
+
+ class Base
+ def foo() :base end
+ def bar() :bar end
+ end
+ module SuperBar
+ def bar() super end
+ end
+ class Derived < Base
+ include SuperBar
+ def foo() :derived end
+ end
+
+ def test_arity
+ assert_equal(0, method(:m0).arity)
+ assert_equal(1, method(:m1).arity)
+ assert_equal(2, method(:m2).arity)
+ assert_equal(-1, method(:mo1).arity)
+ assert_equal(-2, method(:mo2).arity)
+ assert_equal(-1, method(:mo3).arity)
+ assert_equal(-2, method(:mo4).arity)
+ end
+
+ def test_unbind
+ assert_equal(:derived, Derived.new.foo)
+ um = Derived.new.method(:foo).unbind
+ assert_instance_of(UnboundMethod, um)
+ Derived.class_eval do
+ def foo() :changed end
+ end
+ assert_equal(:changed, Derived.new.foo)
+ assert_equal(:derived, um.bind(Derived.new).call)
+ assert_raise(TypeError) do
+ um.bind(Base.new)
+ end
+ end
+
+ def test_method_super
+ assert_nothing_raised do
+ assert_equal(:bar, Derived.new.method(:bar).call)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_objectspace.rb b/ruby_1_8_6/test/ruby/test_objectspace.rb
new file mode 100644
index 0000000000..a2d0164954
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_objectspace.rb
@@ -0,0 +1,36 @@
+require 'test/unit'
+
+class TestObjectSpace < Test::Unit::TestCase
+ def self.deftest_id2ref(obj)
+ /:(\d+)/ =~ caller[0]
+ file = $`
+ line = $1.to_i
+ code = <<"End"
+ define_method("test_id2ref_#{line}") {\
+ o = ObjectSpace._id2ref(obj.object_id);\
+ assert_same(obj, o, "didn't round trip: \#{obj.inspect}");\
+ }
+End
+ eval code, binding, file, line
+ end
+
+ deftest_id2ref(-0x4000000000000001)
+ deftest_id2ref(-0x4000000000000000)
+ deftest_id2ref(-0x40000001)
+ deftest_id2ref(-0x40000000)
+ deftest_id2ref(-1)
+ deftest_id2ref(0)
+ deftest_id2ref(1)
+ deftest_id2ref(0x3fffffff)
+ deftest_id2ref(0x40000000)
+ deftest_id2ref(0x3fffffffffffffff)
+ deftest_id2ref(0x4000000000000000)
+ deftest_id2ref(:a)
+ deftest_id2ref(:abcdefghijilkjl)
+ deftest_id2ref(:==)
+ deftest_id2ref(Object.new)
+ deftest_id2ref(self)
+ deftest_id2ref(true)
+ deftest_id2ref(false)
+ deftest_id2ref(nil)
+end
diff --git a/ruby_1_8_6/test/ruby/test_pack.rb b/ruby_1_8_6/test/ruby/test_pack.rb
new file mode 100644
index 0000000000..e67465b33a
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_pack.rb
@@ -0,0 +1,60 @@
+require 'test/unit'
+
+class TestPack < Test::Unit::TestCase
+ def test_pack
+ $format = "c2x5CCxsdils_l_a6";
+ # Need the expression in here to force ary[5] to be numeric. This avoids
+ # test2 failing because ary2 goes str->numeric->str and ary does not.
+ ary = [1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,-32767,-123456,"abcdef"]
+ $x = ary.pack($format)
+ ary2 = $x.unpack($format)
+
+ assert_equal(ary.length, ary2.length)
+ assert_equal(ary.join(':'), ary2.join(':'))
+ assert_match(/def/, $x)
+
+ $x = [-1073741825]
+ assert_equal($x, $x.pack("q").unpack("q"))
+
+ $x = [-1]
+ assert_equal($x, $x.pack("l").unpack("l"))
+ end
+
+ def test_pack_N
+ assert_equal "\000\000\000\000", [0].pack('N')
+ assert_equal "\000\000\000\001", [1].pack('N')
+ assert_equal "\000\000\000\002", [2].pack('N')
+ assert_equal "\000\000\000\003", [3].pack('N')
+ assert_equal "\377\377\377\376", [4294967294].pack('N')
+ assert_equal "\377\377\377\377", [4294967295].pack('N')
+
+ assert_equal "\200\000\000\000", [2**31].pack('N')
+ assert_equal "\177\377\377\377", [-2**31-1].pack('N')
+ assert_equal "\377\377\377\377", [-1].pack('N')
+
+ assert_equal "\000\000\000\001\000\000\000\001", [1,1].pack('N*')
+ assert_equal "\000\000\000\001\000\000\000\001\000\000\000\001", [1,1,1].pack('N*')
+ end
+
+ def test_unpack_N
+ assert_equal 1, "\000\000\000\001".unpack('N')[0]
+ assert_equal 2, "\000\000\000\002".unpack('N')[0]
+ assert_equal 3, "\000\000\000\003".unpack('N')[0]
+ assert_equal 3, "\000\000\000\003".unpack('N')[0]
+ assert_equal 4294967295, "\377\377\377\377".unpack('N')[0]
+ assert_equal [1,1], "\000\000\000\001\000\000\000\001".unpack('N*')
+ assert_equal [1,1,1], "\000\000\000\001\000\000\000\001\000\000\000\001".unpack('N*')
+ end
+
+ def test_pack_U
+ assert_raises(RangeError) { [-0x40000001].pack("U") }
+ assert_raises(RangeError) { [-0x40000000].pack("U") }
+ assert_raises(RangeError) { [-1].pack("U") }
+ assert_equal "\000", [0].pack("U")
+ assert_equal "\374\277\277\277\277\277", [0x3fffffff].pack("U")
+ assert_equal "\375\200\200\200\200\200", [0x40000000].pack("U")
+ assert_equal "\375\277\277\277\277\277", [0x7fffffff].pack("U")
+ assert_raises(RangeError) { [0x80000000].pack("U") }
+ assert_raises(RangeError) { [0x100000000].pack("U") }
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_path.rb b/ruby_1_8_6/test/ruby/test_path.rb
new file mode 100644
index 0000000000..63dbd07346
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_path.rb
@@ -0,0 +1,224 @@
+require 'test/unit'
+
+class TestPath < Test::Unit::TestCase
+ def test_path
+ assert_equal("a", File.basename("a"))
+ assert_equal("b", File.basename("a/b"))
+ assert_equal("b", File.basename("a/b/"))
+ assert_equal("/", File.basename("/"))
+ assert_equal("/", File.basename("//"))
+ assert_equal("/", File.basename("///"))
+ assert_equal("b", File.basename("a/b////"))
+ assert_equal("a", File.basename("a.rb", ".rb"))
+ assert_equal("a", File.basename("a.rb///", ".rb"))
+ assert_equal("a", File.basename("a.rb///", ".*"))
+ assert_equal("a.rb", File.basename("a.rb///", ".c"))
+ assert_equal(".", File.dirname("a"))
+ assert_equal("/", File.dirname("/"))
+ assert_equal("/", File.dirname("/a"))
+ assert_equal("a", File.dirname("a/b"))
+ assert_equal("a/b", File.dirname("a/b/c"))
+ assert_equal("/a/b", File.dirname("/a/b/c"))
+ assert_equal("/a", File.dirname("/a/b/"))
+ assert_equal("/a", File.dirname("/a/b///"))
+ case Dir.pwd
+ when %r'\A\w:'
+ assert_match(/\A\w:\/\z/, File.expand_path(".", "/"))
+ assert_match(/\A\w:\/a\z/, File.expand_path("a", "/"))
+ dosish = true
+ when %r'\A//'
+ assert_match(%r'\A//[^/]+/[^/]+\z', File.expand_path(".", "/"))
+ assert_match(%r'\A//[^/]+/[^/]+/a\z', File.expand_path(".", "/"))
+ dosish = true
+ else
+ assert_equal("/", File.expand_path(".", "/"))
+ assert_equal("/sub", File.expand_path("sub", "/"))
+ end
+ if dosish
+ assert_equal("//machine/share", File.expand_path("/", "//machine/share/sub"))
+ assert_equal("//machine/share/dir", File.expand_path("/dir", "//machine/share/sub"))
+ assert_equal("z:/", File.expand_path("/", "z:/sub"))
+ assert_equal("z:/dir", File.expand_path("/dir", "z:/sub"))
+ end
+ assert_equal("//", File.expand_path(".", "//"))
+ assert_equal("//sub", File.expand_path("sub", "//"))
+ end
+
+ def test_dirname # [ruby-dev:27738]
+ if /(bcc|ms)win\d|mingw|cygwin|djgpp|human|emx/ =~ RUBY_PLATFORM
+ # DOSISH_DRIVE_LETTER
+ assert_equal('C:.', File.dirname('C:'))
+ assert_equal('C:.', File.dirname('C:a'))
+ assert_equal('C:.', File.dirname('C:a/'))
+ assert_equal('C:a', File.dirname('C:a/b'))
+
+ assert_equal('C:/', File.dirname('C:/'))
+ assert_equal('C:/', File.dirname('C:/a'))
+ assert_equal('C:/', File.dirname('C:/a/'))
+ assert_equal('C:/a', File.dirname('C:/a/b'))
+
+ assert_equal('C:/', File.dirname('C://'))
+ assert_equal('C:/', File.dirname('C://a'))
+ assert_equal('C:/', File.dirname('C://a/'))
+ assert_equal('C:/a', File.dirname('C://a/b'))
+
+ assert_equal('C:/', File.dirname('C:///'))
+ assert_equal('C:/', File.dirname('C:///a'))
+ assert_equal('C:/', File.dirname('C:///a/'))
+ assert_equal('C:/a', File.dirname('C:///a/b'))
+ else
+ # others
+ assert_equal('.', File.dirname('C:'))
+ assert_equal('.', File.dirname('C:a'))
+ assert_equal('.', File.dirname('C:a/'))
+ assert_equal('C:a', File.dirname('C:a/b'))
+
+ assert_equal('.', File.dirname('C:/'))
+ assert_equal('C:', File.dirname('C:/a'))
+ assert_equal('C:', File.dirname('C:/a/'))
+ assert_equal('C:/a', File.dirname('C:/a/b'))
+
+ assert_equal('.', File.dirname('C://'))
+ assert_equal('C:', File.dirname('C://a'))
+ assert_equal('C:', File.dirname('C://a/'))
+ # not spec.
+ #assert_equal('C://a', File.dirname('C://a/b'))
+
+ assert_equal('.', File.dirname('C:///'))
+ assert_equal('C:', File.dirname('C:///a'))
+ assert_equal('C:', File.dirname('C:///a/'))
+ # not spec.
+ #assert_equal('C:///a', File.dirname('C:///a/b'))
+ end
+
+ assert_equal('.', File.dirname(''))
+ assert_equal('.', File.dirname('a'))
+ assert_equal('.', File.dirname('a/'))
+ assert_equal('a', File.dirname('a/b'))
+
+ assert_equal('/', File.dirname('/'))
+ assert_equal('/', File.dirname('/a'))
+ assert_equal('/', File.dirname('/a/'))
+ assert_equal('/a', File.dirname('/a/b'))
+
+ if /(bcc|ms|cyg)win|mingw|djgpp|human|emx/ =~ RUBY_PLATFORM
+ # DOSISH_UNC
+ assert_equal('//', File.dirname('//'))
+ assert_equal('//a', File.dirname('//a'))
+ assert_equal('//a', File.dirname('//a/'))
+ assert_equal('//a/b', File.dirname('//a/b'))
+ assert_equal('//a/b', File.dirname('//a/b/'))
+ assert_equal('//a/b', File.dirname('//a/b/c'))
+
+ assert_equal('//', File.dirname('///'))
+ assert_equal('//a', File.dirname('///a'))
+ assert_equal('//a', File.dirname('///a/'))
+ assert_equal('//a/b', File.dirname('///a/b'))
+ assert_equal('//a/b', File.dirname('///a/b/'))
+ assert_equal('//a/b', File.dirname('///a/b/c'))
+ else
+ # others
+ assert_equal('/', File.dirname('//'))
+ assert_equal('/', File.dirname('//a'))
+ assert_equal('/', File.dirname('//a/'))
+ assert_equal('/a', File.dirname('//a/b'))
+ assert_equal('/a', File.dirname('//a/b/'))
+ assert_equal('/a/b', File.dirname('//a/b/c'))
+
+ assert_equal('/', File.dirname('///'))
+ assert_equal('/', File.dirname('///a'))
+ assert_equal('/', File.dirname('///a/'))
+ assert_equal('/a', File.dirname('///a/b'))
+ assert_equal('/a', File.dirname('///a/b/'))
+ assert_equal('/a/b', File.dirname('///a/b/c'))
+ end
+ end
+
+ def test_basename # [ruby-dev:27766]
+ if /(bcc|ms)win\d|mingw|cygwin|djgpp|human|emx/ =~ RUBY_PLATFORM
+ # DOSISH_DRIVE_LETTER
+ assert_equal('', File.basename('C:'))
+ assert_equal('a', File.basename('C:a'))
+ assert_equal('a', File.basename('C:a/'))
+ assert_equal('b', File.basename('C:a/b'))
+
+ assert_equal('/', File.basename('C:/'))
+ assert_equal('a', File.basename('C:/a'))
+ assert_equal('a', File.basename('C:/a/'))
+ assert_equal('b', File.basename('C:/a/b'))
+
+ assert_equal('/', File.basename('C://'))
+ assert_equal('a', File.basename('C://a'))
+ assert_equal('a', File.basename('C://a/'))
+ assert_equal('b', File.basename('C://a/b'))
+
+ assert_equal('/', File.basename('C:///'))
+ assert_equal('a', File.basename('C:///a'))
+ assert_equal('a', File.basename('C:///a/'))
+ assert_equal('b', File.basename('C:///a/b'))
+ else
+ # others
+ assert_equal('C:', File.basename('C:'))
+ assert_equal('C:a', File.basename('C:a'))
+ assert_equal('C:a', File.basename('C:a/'))
+ assert_equal('b', File.basename('C:a/b'))
+
+ assert_equal('C:', File.basename('C:/'))
+ assert_equal('a', File.basename('C:/a'))
+ assert_equal('a', File.basename('C:/a/'))
+ assert_equal('b', File.basename('C:/a/b'))
+
+ assert_equal('C:', File.basename('C://'))
+ assert_equal('a', File.basename('C://a'))
+ assert_equal('a', File.basename('C://a/'))
+ assert_equal('b', File.basename('C://a/b'))
+
+ assert_equal('C:', File.basename('C:///'))
+ assert_equal('a', File.basename('C:///a'))
+ assert_equal('a', File.basename('C:///a/'))
+ assert_equal('b', File.basename('C:///a/b'))
+ end
+
+ assert_equal('', File.basename(''))
+ assert_equal('a', File.basename('a'))
+ assert_equal('a', File.basename('a/'))
+ assert_equal('b', File.basename('a/b'))
+
+ assert_equal('/', File.basename('/'))
+ assert_equal('a', File.basename('/a'))
+ assert_equal('a', File.basename('/a/'))
+ assert_equal('b', File.basename('/a/b'))
+
+ if /(bcc|ms|cyg)win|mingw|djgpp|human|emx/ =~ RUBY_PLATFORM
+ # DOSISH_UNC
+ assert_equal('/', File.basename('//'))
+ assert_equal('/', File.basename('//a'))
+ assert_equal('/', File.basename('//a/'))
+ assert_equal('/', File.basename('//a/b'))
+ assert_equal('/', File.basename('//a/b/'))
+ assert_equal('c', File.basename('//a/b/c'))
+
+ assert_equal('/', File.basename('///'))
+ assert_equal('/', File.basename('///a'))
+ assert_equal('/', File.basename('///a/'))
+ assert_equal('/', File.basename('///a/b'))
+ assert_equal('/', File.basename('///a/b/'))
+ assert_equal('c', File.basename('///a/b/c'))
+ else
+ # others
+ assert_equal('/', File.basename('//'))
+ assert_equal('a', File.basename('//a'))
+ assert_equal('a', File.basename('//a/'))
+ assert_equal('b', File.basename('//a/b'))
+ assert_equal('b', File.basename('//a/b/'))
+ assert_equal('c', File.basename('//a/b/c'))
+
+ assert_equal('/', File.basename('///'))
+ assert_equal('a', File.basename('///a'))
+ assert_equal('a', File.basename('///a/'))
+ assert_equal('b', File.basename('///a/b'))
+ assert_equal('b', File.basename('///a/b/'))
+ assert_equal('c', File.basename('///a/b/c'))
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_pipe.rb b/ruby_1_8_6/test/ruby/test_pipe.rb
new file mode 100644
index 0000000000..c3b4d29c0a
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_pipe.rb
@@ -0,0 +1,18 @@
+require 'test/unit'
+$:.replace([File.dirname(File.expand_path(__FILE__))] | $:)
+require 'ut_eof'
+require 'envutil'
+
+class TestPipe < Test::Unit::TestCase
+ include TestEOF
+ def open_file(content)
+ r, w = IO.pipe
+ w << content
+ w.close
+ begin
+ yield r
+ ensure
+ r.close
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_proc.rb b/ruby_1_8_6/test/ruby/test_proc.rb
new file mode 100644
index 0000000000..f0b78ffb23
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_proc.rb
@@ -0,0 +1,89 @@
+require 'test/unit'
+
+class TestProc < Test::Unit::TestCase
+ def test_proc
+ p1 = proc{|i| i}
+ assert_equal(2, p1.call(2))
+ assert_equal(3, p1.call(3))
+
+ p1 = proc{|i| i*2}
+ assert_equal(4, p1.call(2))
+ assert_equal(6, p1.call(3))
+
+ p2 = nil
+ x=0
+
+ proc{
+ iii=5 # nested local variable
+ p1 = proc{|i|
+ iii = i
+ }
+ p2 = proc {
+ x = iii # nested variables shared by procs
+ }
+ # scope of nested variables
+ assert(defined?(iii))
+ }.call
+ assert(!defined?(iii)) # out of scope
+
+ loop{iii=5; assert(eval("defined? iii")); break}
+ loop {
+ iii = 10
+ def self.dyna_var_check
+ loop {
+ assert(!defined?(iii))
+ break
+ }
+ end
+ dyna_var_check
+ break
+ }
+ p1.call(5)
+ p2.call
+ assert_equal(5, x)
+ end
+
+ def assert_arity(n)
+ meta = class << self; self; end
+ meta.class_eval {define_method(:foo, Proc.new)}
+ assert_equal(n, method(:foo).arity)
+ end
+
+ def test_arity
+ assert_equal(-1, proc{}.arity)
+ assert_equal(0, proc{||}.arity)
+ assert_equal(1, proc{|x|}.arity)
+ assert_equal(2, proc{|x, y|}.arity)
+ assert_equal(-2, proc{|x, *y|}.arity)
+ assert_equal(-1, proc{|*x|}.arity)
+ assert_equal(-1, proc{|*|}.arity)
+
+ assert_arity(-1) {}
+ assert_arity(0) {||}
+ assert_arity(1) {|x|}
+ assert_arity(2) {|x, y|}
+ assert_arity(-2) {|x, *y|}
+ assert_arity(-1) {|*x|}
+ assert_arity(-1) {|*|}
+ end
+
+ # [ruby-dev:22592]
+ def m(x)
+ lambda { x }
+ end
+ def test_eq
+ # [ruby-dev:22592]
+ a = m(1)
+ b = m(2)
+ assert_not_equal(a, b)
+ assert_not_equal(a.call, b.call)
+
+ # [ruby-dev:22599]
+ assert_not_equal(proc {||}, proc {|x,y|})
+
+ # [ruby-dev:22601]
+ a = lambda {|x| lambda {} }.call(1)
+ b = lambda {}
+ assert_not_equal(a, b)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_process.rb b/ruby_1_8_6/test/ruby/test_process.rb
new file mode 100644
index 0000000000..93eb871edc
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_process.rb
@@ -0,0 +1,41 @@
+require 'test/unit'
+
+class TestProcess < Test::Unit::TestCase
+ def test_rlimit_availability
+ begin
+ Process.getrlimit(nil)
+ rescue NotImplementedError
+ assert_raise(NotImplementedError) { Process.setrlimit }
+ rescue TypeError
+ assert_raise(ArgumentError) { Process.setrlimit }
+ end
+ end
+
+ def rlimit_exist?
+ Process.getrlimit(nil)
+ rescue NotImplementedError
+ return false
+ rescue TypeError
+ return true
+ end
+
+ def test_rlimit_nofile
+ return unless rlimit_exist?
+ pid = fork {
+ cur_nofile, max_nofile = Process.getrlimit(Process::RLIMIT_NOFILE)
+ begin
+ Process.setrlimit(Process::RLIMIT_NOFILE, 0, max_nofile)
+ rescue Errno::EINVAL
+ exit 0
+ end
+ begin
+ IO.pipe
+ rescue Errno::EMFILE
+ exit 0
+ end
+ exit 1
+ }
+ Process.wait pid
+ assert_equal(0, $?.to_i)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_rand.rb b/ruby_1_8_6/test/ruby/test_rand.rb
new file mode 100644
index 0000000000..e2fd127f9c
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_rand.rb
@@ -0,0 +1,131 @@
+require 'test/unit'
+
+class TestRand < Test::Unit::TestCase
+ def test_mt
+ srand(0x00000456_00000345_00000234_00000123)
+ %w(1067595299 955945823 477289528 4107218783 4228976476).each {|w|
+ assert_equal(w.to_i, rand(0x100000000))
+ }
+ end
+
+ def test_0x3fffffff
+ srand(0)
+ %w(209652396 398764591 924231285 404868288 441365315).each {|w|
+ assert_equal(w.to_i, rand(0x3fffffff))
+ }
+ end
+
+ def test_0x40000000
+ srand(0)
+ %w(209652396 398764591 924231285 404868288 441365315).each {|w|
+ assert_equal(w.to_i, rand(0x40000000))
+ }
+ end
+
+ def test_0x40000001
+ srand(0)
+ %w(209652396 398764591 924231285 441365315 192771779).each {|w|
+ assert_equal(w.to_i, rand(0x40000001))
+ }
+ end
+
+ def test_0xffffffff
+ srand(0)
+ %w(2357136044 2546248239 3071714933 3626093760 2588848963).each {|w|
+ assert_equal(w.to_i, rand(0xffffffff))
+ }
+ end
+
+ def test_0x100000000
+ srand(0)
+ %w(2357136044 2546248239 3071714933 3626093760 2588848963).each {|w|
+ assert_equal(w.to_i, rand(0x100000000))
+ }
+ end
+
+ def test_0x100000001
+ srand(0)
+ %w(2546248239 1277901399 243580376 1171049868 2051556033).each {|w|
+ assert_equal(w.to_i, rand(0x100000001))
+ }
+ end
+
+ def test_rand_0x100000000
+ srand(311702798)
+ %w(4119812344 3870378946 80324654 4294967296 410016213).each {|w|
+ assert_equal(w.to_i, rand(0x100000001))
+ }
+ end
+
+ def test_0x1000000000000
+ srand(0)
+ %w(11736396900911
+ 183025067478208
+ 197104029029115
+ 130583529618791
+ 180361239846611).each {|w|
+ assert_equal(w.to_i, rand(0x1000000000000))
+ }
+ end
+
+ def test_0x1000000000001
+ srand(0)
+ %w(187121911899765
+ 197104029029115
+ 180361239846611
+ 236336749852452
+ 208739549485656).each {|w|
+ assert_equal(w.to_i, rand(0x1000000000001))
+ }
+ end
+
+ def test_0x3fffffffffffffff
+ srand(0)
+ %w(900450186894289455
+ 3969543146641149120
+ 1895649597198586619
+ 827948490035658087
+ 3203365596207111891).each {|w|
+ assert_equal(w.to_i, rand(0x3fffffffffffffff))
+ }
+ end
+
+ def test_0x4000000000000000
+ srand(0)
+ %w(900450186894289455
+ 3969543146641149120
+ 1895649597198586619
+ 827948490035658087
+ 3203365596207111891).each {|w|
+ assert_equal(w.to_i, rand(0x4000000000000000))
+ }
+ end
+
+ def test_0x4000000000000001
+ srand(0)
+ %w(900450186894289455
+ 3969543146641149120
+ 1895649597198586619
+ 827948490035658087
+ 2279347887019741461).each {|w|
+ assert_equal(w.to_i, rand(0x4000000000000001))
+ }
+ end
+
+ def test_neg_0x10000000000
+ ws = %w(455570294424 1073054410371 790795084744 2445173525 1088503892627)
+ srand(3)
+ ws.each {|w| assert_equal(w.to_i, rand(0x10000000000)) }
+ srand(3)
+ ws.each {|w| assert_equal(w.to_i, rand(-0x10000000000)) }
+ end
+
+ def test_neg_0x10000
+ ws = %w(2732 43567 42613 52416 45891)
+ srand(0)
+ ws.each {|w| assert_equal(w.to_i, rand(0x10000)) }
+ srand(0)
+ ws.each {|w| assert_equal(w.to_i, rand(-0x10000)) }
+ end
+
+end
diff --git a/ruby_1_8_6/test/ruby/test_range.rb b/ruby_1_8_6/test/ruby/test_range.rb
new file mode 100644
index 0000000000..455175087d
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_range.rb
@@ -0,0 +1,17 @@
+require 'test/unit'
+
+class TestRange < Test::Unit::TestCase
+ def test_range_string
+ # XXX: Is this really the test of Range?
+ assert_equal([], ("a" ... "a").to_a)
+ assert_equal(["a"], ("a" .. "a").to_a)
+ assert_equal(["a"], ("a" ... "b").to_a)
+ assert_equal(["a", "b"], ("a" .. "b").to_a)
+ end
+
+ def test_evaluation_order
+ arr = [1,2]
+ r = (arr.shift)..(arr.shift)
+ assert_equal(1..2, r, "[ruby-dev:26383]")
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_readpartial.rb b/ruby_1_8_6/test/ruby/test_readpartial.rb
new file mode 100644
index 0000000000..3877e21f85
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_readpartial.rb
@@ -0,0 +1,74 @@
+require 'test/unit'
+require 'timeout'
+require 'fcntl'
+
+class TestReadPartial < Test::Unit::TestCase
+ def make_pipe
+ r, w = IO.pipe
+ begin
+ yield r, w
+ ensure
+ r.close unless r.closed?
+ w.close unless w.closed?
+ end
+ end
+
+ def pipe
+ make_pipe {|r, w|
+ yield r, w
+ }
+ return unless defined?(Fcntl::F_SETFL)
+ return unless defined?(Fcntl::F_GETFL)
+ return unless defined?(Fcntl::O_NONBLOCK)
+ make_pipe {|r, w|
+ r.fcntl(Fcntl::F_SETFL, r.fcntl(Fcntl::F_GETFL) | Fcntl::O_NONBLOCK)
+ yield r, w
+ }
+ end
+
+ def test_length_zero
+ pipe {|r, w|
+ assert_equal('', r.readpartial(0))
+ }
+ end
+
+ def test_closed_pipe
+ pipe {|r, w|
+ w << 'abc'
+ w.close
+ assert_equal('ab', r.readpartial(2))
+ assert_equal('c', r.readpartial(2))
+ assert_raises(EOFError) { r.readpartial(2) }
+ assert_raises(EOFError) { r.readpartial(2) }
+ }
+ end
+
+ if !File::ALT_SEPARATOR # read on pipe cannot timeout on Windows.
+ def test_open_pipe
+ pipe {|r, w|
+ w << 'abc'
+ assert_equal('ab', r.readpartial(2))
+ assert_equal('c', r.readpartial(2))
+ assert_raises(TimeoutError) {
+ timeout(0.1) { r.readpartial(2) }
+ }
+ }
+ end
+
+ def test_with_stdio
+ pipe {|r, w|
+ w << "abc\ndef\n"
+ assert_equal("abc\n", r.gets)
+ w << "ghi\n"
+ assert_equal("de", r.readpartial(2))
+ assert_equal("f\n", r.readpartial(4096))
+ assert_equal("ghi\n", r.readpartial(4096))
+ assert_raises(TimeoutError) {
+ timeout(0.1) { r.readpartial(2) }
+ }
+ }
+ end
+ end
+
+end
+
diff --git a/ruby_1_8_6/test/ruby/test_settracefunc.rb b/ruby_1_8_6/test/ruby/test_settracefunc.rb
new file mode 100644
index 0000000000..39e1b035d8
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_settracefunc.rb
@@ -0,0 +1,138 @@
+require 'test/unit'
+
+class TestSetTraceFunc < Test::Unit::TestCase
+ def foo; end;
+
+ def bar
+ events = []
+ set_trace_func(Proc.new { |event, file, lineno, mid, bidning, klass|
+ events << [event, lineno, mid, klass]
+ })
+ return events
+ end
+
+ def test_event
+ events = []
+ set_trace_func(Proc.new { |event, file, lineno, mid, bidning, klass|
+ events << [event, lineno, mid, klass]
+ })
+ a = 1
+ foo
+ a
+ b = 1 + 2
+ if b == 3
+ case b
+ when 2
+ c = "b == 2"
+ when 3
+ c = "b == 3"
+ end
+ end
+ begin
+ raise "error"
+ rescue
+ end
+ eval("class Foo; end")
+ set_trace_func nil
+
+ assert_equal(["line", 19, :test_event, TestSetTraceFunc],
+ events.shift) # a = 1
+ assert_equal(["line", 20, :test_event, TestSetTraceFunc],
+ events.shift) # foo
+ assert_equal(["call", 4, :foo, TestSetTraceFunc],
+ events.shift) # foo
+ assert_equal(["return", 4, :foo, TestSetTraceFunc],
+ events.shift) # foo
+ assert_equal(["line", 21, :test_event, TestSetTraceFunc],
+ events.shift) # a
+ assert_equal(["line", 22, :test_event, TestSetTraceFunc],
+ events.shift) # b = 1 + 2
+ assert_equal(["c-call", 22, :+, Fixnum],
+ events.shift) # 1 + 2
+ assert_equal(["c-return", 22, :+, Fixnum],
+ events.shift) # 1 + 2
+ assert_equal(["line", 23, :test_event, TestSetTraceFunc],
+ events.shift) # if b == 3
+ assert_equal(["line", 23, :test_event, TestSetTraceFunc],
+ events.shift) # if b == 3
+ assert_equal(["c-call", 23, :==, Fixnum],
+ events.shift) # b == 3
+ assert_equal(["c-return", 23, :==, Fixnum],
+ events.shift) # b == 3
+ assert_equal(["line", 24, :test_event, TestSetTraceFunc],
+ events.shift) # case b
+ assert_equal(["line", 25, :test_event, TestSetTraceFunc],
+ events.shift) # when 2
+ assert_equal(["c-call", 25, :===, Kernel],
+ events.shift) # when 2
+ assert_equal(["c-call", 25, :==, Fixnum],
+ events.shift) # when 2
+ assert_equal(["c-return", 25, :==, Fixnum],
+ events.shift) # when 2
+ assert_equal(["c-return", 25, :===, Kernel],
+ events.shift) # when 2
+ assert_equal(["line", 27, :test_event, TestSetTraceFunc],
+ events.shift) # when 3
+ assert_equal(["c-call", 27, :===, Kernel],
+ events.shift) # when 3
+ assert_equal(["c-return", 27, :===, Kernel],
+ events.shift) # when 3
+ assert_equal(["line", 28, :test_event, TestSetTraceFunc],
+ events.shift) # c = "b == 3"
+ assert_equal(["line", 31, :test_event, TestSetTraceFunc],
+ events.shift) # begin
+ assert_equal(["line", 32, :test_event, TestSetTraceFunc],
+ events.shift) # raise "error"
+ assert_equal(["c-call", 32, :raise, Kernel],
+ events.shift) # raise "error"
+ assert_equal(["c-call", 32, :new, Class],
+ events.shift) # raise "error"
+ assert_equal(["c-call", 32, :initialize, Exception],
+ events.shift) # raise "error"
+ assert_equal(["c-return", 32, :initialize, Exception],
+ events.shift) # raise "error"
+ assert_equal(["c-return", 32, :new, Class],
+ events.shift) # raise "error"
+ assert_equal(["c-call", 32, :backtrace, Exception],
+ events.shift) # raise "error"
+ assert_equal(["c-return", 32, :backtrace, Exception],
+ events.shift) # raise "error"
+ assert_equal(["c-call", 32, :set_backtrace, Exception],
+ events.shift) # raise "error"
+ assert_equal(["c-return", 32, :set_backtrace, Exception],
+ events.shift) # raise "error"
+ assert_equal(["raise", 32, :test_event, TestSetTraceFunc],
+ events.shift) # raise "error"
+ assert_equal(["c-return", 32, :raise, Kernel],
+ events.shift) # raise "error"
+ assert_equal(["line", 35, :test_event, TestSetTraceFunc],
+ events.shift) # eval(<<EOF)
+ assert_equal(["c-call", 35, :eval, Kernel],
+ events.shift) # eval(<<EOF)
+ assert_equal(["line", 1, :test_event, TestSetTraceFunc],
+ events.shift) # class Foo
+ assert_equal(["c-call", 1, :inherited, Class],
+ events.shift) # class Foo
+ assert_equal(["c-return", 1, :inherited, Class],
+ events.shift) # class Foo
+ assert_equal(["class", 1, :test_event, TestSetTraceFunc],
+ events.shift) # class Foo
+ assert_equal(["end", 1, :test_event, TestSetTraceFunc],
+ events.shift) # class Foo
+ assert_equal(["c-return", 35, :eval, Kernel],
+ events.shift) # eval(<<EOF)
+ assert_equal(["line", 36, :test_event, TestSetTraceFunc],
+ events.shift) # set_trace_func nil
+ assert_equal(["c-call", 36, :set_trace_func, Kernel],
+ events.shift) # set_trace_func nil
+ assert_equal([], events)
+
+ events = bar
+ set_trace_func(nil)
+ assert_equal(["line", 11, :bar, TestSetTraceFunc], events.shift)
+ assert_equal(["return", 7, :bar, TestSetTraceFunc], events.shift)
+ assert_equal(["line", 131, :test_event, TestSetTraceFunc], events.shift)
+ assert_equal(["c-call", 131, :set_trace_func, Kernel], events.shift)
+ assert_equal([], events)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_signal.rb b/ruby_1_8_6/test/ruby/test_signal.rb
new file mode 100644
index 0000000000..43e16b8c79
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_signal.rb
@@ -0,0 +1,68 @@
+require 'test/unit'
+require 'timeout'
+
+class TestSignal < Test::Unit::TestCase
+ def have_fork?
+ begin
+ fork{}
+ true
+ rescue NotImplementedError
+ false
+ end
+ end
+
+ def test_signal
+ defined?(Process.kill) or return
+ begin
+ $x = 0
+ oldtrap = trap "SIGINT", proc{|sig| $x = 2}
+ Process.kill "SIGINT", $$
+ sleep 0.1
+ assert_equal(2, $x)
+
+ trap "SIGINT", proc{raise "Interrupt"}
+
+ x = assert_raises(RuntimeError) do
+ Process.kill "SIGINT", $$
+ sleep 0.1
+ end
+ assert(x)
+ assert_match(/Interrupt/, x.message)
+ ensure
+ trap "SIGINT", oldtrap
+ end
+ end
+
+ def test_exit_action
+ return unless have_fork? # snip this test
+ begin
+ r, w = IO.pipe
+ r0, w0 = IO.pipe
+ pid = fork {
+ trap(:USR1, "EXIT")
+ w0.close
+ w.syswrite("a")
+ Thread.start { Thread.pass }
+ r0.sysread(4096)
+ }
+ r.sysread(1)
+ sleep 0.1
+ assert_nothing_raised("[ruby-dev:26128]") {
+ Process.kill(:USR1, pid)
+ begin
+ Timeout.timeout(10) {
+ Process.waitpid pid
+ }
+ rescue Timeout::Error
+ Process.kill(:TERM, pid)
+ raise
+ end
+ }
+ ensure
+ r.close
+ w.close
+ r0.close
+ w0.close
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_string.rb b/ruby_1_8_6/test/ruby/test_string.rb
new file mode 100644
index 0000000000..f8938cad84
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_string.rb
@@ -0,0 +1,19 @@
+require 'test/unit'
+
+class TestString < Test::Unit::TestCase
+ def check_sum(str, bits=16)
+ sum = 0
+ str.each_byte {|c| sum += c}
+ sum = sum & ((1 << bits) - 1) if bits != 0
+ assert_equal(sum, str.sum(bits))
+ end
+ def test_sum
+ assert_equal(0, "".sum)
+ assert_equal(294, "abc".sum)
+ check_sum("abc")
+ check_sum("\x80")
+ 0.upto(70) {|bits|
+ check_sum("xyz", bits)
+ }
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_stringchar.rb b/ruby_1_8_6/test/ruby/test_stringchar.rb
new file mode 100644
index 0000000000..34934e87bd
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_stringchar.rb
@@ -0,0 +1,166 @@
+require 'test/unit'
+
+class TestStringchar < Test::Unit::TestCase
+ def test_string
+ assert_equal("abcd", "abcd")
+ assert_match(/abcd/, "abcd")
+ assert("abcd" === "abcd")
+ # compile time string concatenation
+ assert_equal("abcd", "ab" "cd")
+ assert_equal("22aacd44", "#{22}aa" "cd#{44}")
+ assert_equal("22aacd445566", "#{22}aa" "cd#{44}" "55" "#{66}")
+ assert("abc" !~ /^$/)
+ assert("abc\n" !~ /^$/)
+ assert("abc" !~ /^d*$/)
+ assert_equal(3, ("abc" =~ /d*$/))
+ assert("" =~ /^$/)
+ assert("\n" =~ /^$/)
+ assert("a\n\n" =~ /^$/)
+ assert("abcabc" =~ /.*a/); assert_equal("abca", $&)
+ assert("abcabc" =~ /.*c/); assert_equal("abcabc", $&)
+ assert("abcabc" =~ /.*?a/); assert_equal("a", $&)
+ assert("abcabc" =~ /.*?c/); assert_equal("abc", $&)
+ assert(/(.|\n)*?\n(b|\n)/ =~ "a\nb\n\n"); assert_equal("a\nb", $&)
+
+ assert(/^(ab+)+b/ =~ "ababb"); assert_equal("ababb", $&)
+ assert(/^(?:ab+)+b/ =~ "ababb"); assert_equal("ababb", $&)
+ assert(/^(ab+)+/ =~ "ababb"); assert_equal("ababb", $&)
+ assert(/^(?:ab+)+/ =~ "ababb"); assert_equal("ababb", $&)
+
+ assert(/(\s+\d+){2}/ =~ " 1 2"); assert_equal(" 1 2", $&)
+ assert(/(?:\s+\d+){2}/ =~ " 1 2"); assert_equal(" 1 2", $&)
+
+ $x = <<END;
+ABCD
+ABCD
+END
+ $x.gsub!(/((.|\n)*?)B((.|\n)*?)D/){$1+$3}
+ assert_equal("AC\nAC\n", $x)
+
+ assert("foobar" =~ /foo(?=(bar)|(baz))/)
+ assert("foobaz" =~ /foo(?=(bar)|(baz))/)
+
+ $foo = "abc"
+ assert_equal("abc = abc", "#$foo = abc")
+ assert_equal("abc = abc", "#{$foo} = abc")
+
+ foo = "abc"
+ assert_equal("abc = abc", "#{foo} = abc")
+
+ assert_equal('-----', '-' * 5)
+ assert_equal('-', '-' * 1)
+ assert_equal('', '-' * 0)
+
+ foo = '-'
+ assert_equal('-----', foo * 5)
+ assert_equal('-', foo * 1)
+ assert_equal('', foo * 0)
+
+ $x = "a.gif"
+ assert_equal("gif", $x.sub(/.*\.([^\.]+)$/, '\1'))
+ assert_equal("b.gif", $x.sub(/.*\.([^\.]+)$/, 'b.\1'))
+ assert_equal("", $x.sub(/.*\.([^\.]+)$/, '\2'))
+ assert_equal("ab", $x.sub(/.*\.([^\.]+)$/, 'a\2b'))
+ assert_equal("<a.gif>", $x.sub(/.*\.([^\.]+)$/, '<\&>'))
+ end
+
+ def test_char
+ # character constants(assumes ASCII)
+ assert_equal(?a, "a"[0])
+ assert_equal(?a, ?a)
+ assert_equal(1, ?\C-a)
+ assert_equal(225, ?\M-a)
+ assert_equal(129, ?\M-\C-a)
+ assert_equal(?A, "a".upcase![0])
+ assert_equal(?a, "A".downcase![0])
+ assert_equal("ABC", "abc".tr!("a-z", "A-Z"))
+ assert_equal("ABC", "aabbcccc".tr_s!("a-z", "A-Z"))
+ assert_equal("abc", "abcc".squeeze!("a-z"))
+ assert_equal("ad", "abcd".delete!("bc"))
+
+ $x = "abcdef"
+ $y = [ ?a, ?b, ?c, ?d, ?e, ?f ]
+ $bad = false
+ $x.each_byte {|i|
+ if i != $y.shift
+ $bad = true
+ break
+ end
+ }
+ assert(!$bad)
+
+ s = "a string"
+ s[0..s.size]="another string"
+ assert_equal("another string", s)
+
+ s = <<EOS
+#{
+[1,2,3].join(",")
+}
+EOS
+ assert_equal("1,2,3\n", s)
+ assert_equal(926381, "Just".to_i(36))
+ assert_equal(-23200231779, "-another".to_i(36))
+ assert_equal("ruby", 1299022.to_s(36))
+ assert_equal("-hacker", -1045307475.to_s(36))
+ assert_equal(265419172580680477752431643787347, "Just_another_Ruby_hacker".to_i(36))
+ assert_equal("-justanotherrubyhacker", -265419172580680477752431643787347.to_s(36))
+
+ a = []
+ (0..255).each {|n|
+ ch = [n].pack("C")
+ a.push ch if /a#{Regexp.quote ch}b/x =~ "ab"
+ }
+ assert_equal(0, a.size)
+ end
+
+ def test_bang
+ s = "aBc"
+ s.upcase
+ assert_equal("aBc", s)
+ s.upcase!
+ assert_equal("ABC", s)
+
+ s = "aBc"
+ s.downcase
+ assert_equal("aBc", s)
+ s.downcase!
+ assert_equal("abc", s)
+
+ s = "aBc"
+ s.swapcase
+ assert_equal("aBc", s)
+ s.swapcase!
+ assert_equal("AbC", s)
+
+ s = "aBc"
+ s.capitalize
+ assert_equal("aBc", s)
+ s.capitalize!
+ assert_equal("Abc", s)
+
+ s = "aBc"
+ s.tr("a-z", "A-Z")
+ assert_equal("aBc", s)
+ s.tr!("a-z", "A-Z")
+ assert_equal("ABC", s)
+
+ s = "aaBBcc"
+ s.tr_s("a-z", "A-Z")
+ assert_equal("aaBBcc", s)
+ s.tr_s!("a-z", "A-Z")
+ assert_equal("ABBC", s)
+
+ s = "aaBBcc"
+ s.squeeze("a-z")
+ assert_equal("aaBBcc", s)
+ s.squeeze!("a-z")
+ assert_equal("aBBc", s)
+
+ s = "aaBBcc"
+ s.delete("a-z")
+ assert_equal("aaBBcc", s)
+ s.delete!("a-z")
+ assert_equal("BB", s)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_struct.rb b/ruby_1_8_6/test/ruby/test_struct.rb
new file mode 100644
index 0000000000..fa1bb1549a
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_struct.rb
@@ -0,0 +1,24 @@
+require 'test/unit'
+
+class TestStruct < Test::Unit::TestCase
+ def test_struct
+ struct_test = Struct.new("Test", :foo, :bar)
+ assert_equal(Struct::Test, struct_test)
+
+ test = struct_test.new(1, 2)
+ assert_equal(1, test.foo)
+ assert_equal(2, test.bar)
+ assert_equal(1, test[0])
+ assert_equal(2, test[1])
+
+ a, b = test.to_a
+ assert_equal(1, a)
+ assert_equal(2, b)
+
+ test[0] = 22
+ assert_equal(22, test.foo)
+
+ test.bar = 47
+ assert_equal(47, test.bar)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_super.rb b/ruby_1_8_6/test/ruby/test_super.rb
new file mode 100644
index 0000000000..900fe997e6
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_super.rb
@@ -0,0 +1,134 @@
+require 'test/unit'
+
+class TestSuper < Test::Unit::TestCase
+ class Base
+ def single(a) a end
+ def double(a, b) [a,b] end
+ def array(*a) a end
+ def optional(a = 0) a end
+ end
+ class Single1 < Base
+ def single(*) super end
+ end
+ class Single2 < Base
+ def single(a,*) super end
+ end
+ class Double1 < Base
+ def double(*) super end
+ end
+ class Double2 < Base
+ def double(a,*) super end
+ end
+ class Double3 < Base
+ def double(a,b,*) super end
+ end
+ class Array1 < Base
+ def array(*) super end
+ end
+ class Array2 < Base
+ def array(a,*) super end
+ end
+ class Array3 < Base
+ def array(a,b,*) super end
+ end
+ class Array4 < Base
+ def array(a,b,c,*) super end
+ end
+ class Optional1 < Base
+ def optional(a = 1) super end
+ end
+ class Optional2 < Base
+ def optional(a, b = 1) super end
+ end
+ class Optional3 < Base
+ def single(a = 1) super end
+ end
+ class Optional4 < Base
+ def array(a = 1, *) super end
+ end
+ class Optional5 < Base
+ def array(a = 1, b = 2, *) super end
+ end
+
+ def test_single1
+ assert_equal(1, Single1.new.single(1))
+ end
+ def test_single2
+ assert_equal(1, Single2.new.single(1))
+ end
+ def test_double1
+ assert_equal([1, 2], Double1.new.double(1, 2))
+ end
+ def test_double2
+ assert_equal([1, 2], Double2.new.double(1, 2))
+ end
+ def test_double3
+ assert_equal([1, 2], Double3.new.double(1, 2))
+ end
+ def test_array1
+ assert_equal([], Array1.new.array())
+ assert_equal([1], Array1.new.array(1))
+ end
+ def test_array2
+ assert_equal([1], Array2.new.array(1))
+ assert_equal([1,2], Array2.new.array(1, 2))
+ end
+ def test_array3
+ assert_equal([1,2], Array3.new.array(1, 2))
+ assert_equal([1,2,3], Array3.new.array(1, 2, 3))
+ end
+ def test_array4
+ assert_equal([1,2,3], Array4.new.array(1, 2, 3))
+ assert_equal([1,2,3,4], Array4.new.array(1, 2, 3, 4))
+ end
+ def test_optional1
+ assert_equal(9, Optional1.new.optional(9))
+ assert_equal(1, Optional1.new.optional)
+ end
+ def test_optional2
+ assert_raise(ArgumentError) do
+ # call Base#optional with 2 arguments; the 2nd arg is supplied
+ assert_equal(9, Optional2.new.optional(9))
+ end
+ assert_raise(ArgumentError) do
+ # call Base#optional with 2 arguments
+ assert_equal(9, Optional2.new.optional(9, 2))
+ end
+ end
+ def test_optional3
+ assert_equal(9, Optional3.new.single(9))
+ # call Base#single with 1 argument; the arg is supplied
+ assert_equal(1, Optional3.new.single)
+ end
+ def test_optional4
+ assert_equal([1], Optional4.new.array)
+ assert_equal([9], Optional4.new.array(9))
+ assert_equal([9, 8], Optional4.new.array(9, 8))
+ end
+ def test_optional5
+ assert_equal([1, 2], Optional5.new.array)
+ assert_equal([9, 2], Optional5.new.array(9))
+ assert_equal([9, 8], Optional5.new.array(9, 8))
+ assert_equal([9, 8, 7], Optional5.new.array(9, 8, 7))
+ end
+
+ class A
+ def tt(aa)
+ "A#tt"
+ end
+
+ def uu(a)
+ class << self
+ define_method(:tt) do |sym|
+ super
+ end
+ end
+ end
+ end
+
+ def test_define_method # [ruby-core:03856]
+ a = A.new
+ a.uu(12)
+ assert_equal("A#tt", a.tt(12))
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_symbol.rb b/ruby_1_8_6/test/ruby/test_symbol.rb
new file mode 100644
index 0000000000..2ccfe64c92
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_symbol.rb
@@ -0,0 +1,77 @@
+require 'test/unit'
+
+class TestSymbol < Test::Unit::TestCase
+ # [ruby-core:3573]
+
+ def assert_eval_inspected(sym)
+ n = sym.inspect
+ assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(n))}
+ end
+
+ def test_inspect_invalid
+ # 2) Symbol#inspect sometimes returns invalid symbol representations:
+ assert_eval_inspected(:"!")
+ assert_eval_inspected(:"=")
+ assert_eval_inspected(:"0")
+ assert_eval_inspected(:"$1")
+ assert_eval_inspected(:"@1")
+ assert_eval_inspected(:"@@1")
+ assert_eval_inspected(:"@")
+ assert_eval_inspected(:"@@")
+ end
+
+ def assert_inspect_evaled(n)
+ assert_nothing_raised(SyntaxError) {assert_equal(n, eval(n).inspect)}
+ end
+
+ def test_inspect_suboptimal
+ # 3) Symbol#inspect sometimes returns suboptimal symbol representations:
+ assert_inspect_evaled(':foo')
+ assert_inspect_evaled(':foo!')
+ assert_inspect_evaled(':bar?')
+ assert_inspect_evaled(':<<')
+ assert_inspect_evaled(':>>')
+ assert_inspect_evaled(':<=')
+ assert_inspect_evaled(':>=')
+ assert_inspect_evaled(':=~')
+ assert_inspect_evaled(':==')
+ assert_inspect_evaled(':===')
+ assert_raise(SyntaxError) {eval ':='}
+ assert_inspect_evaled(':*')
+ assert_inspect_evaled(':**')
+ assert_raise(SyntaxError) {eval ':***'}
+ assert_inspect_evaled(':+')
+ assert_inspect_evaled(':-')
+ assert_inspect_evaled(':+@')
+ assert_inspect_evaled(':-@')
+ assert_inspect_evaled(':|')
+ assert_inspect_evaled(':^')
+ assert_inspect_evaled(':&')
+ assert_inspect_evaled(':/')
+ assert_inspect_evaled(':%')
+ assert_inspect_evaled(':~')
+ assert_inspect_evaled(':`')
+ assert_inspect_evaled(':[]')
+ assert_inspect_evaled(':[]=')
+ assert_raise(SyntaxError) {eval ':||'}
+ assert_raise(SyntaxError) {eval ':&&'}
+ assert_raise(SyntaxError) {eval ':['}
+ end
+
+ def test_inspect_dollar
+ # 4) :$- always treats next character literally:
+ sym = "$-".intern
+ assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(':$-'))}
+ assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(":$-\n"))}
+ assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(":$- "))}
+ assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(":$-#"))}
+ assert_raise(SyntaxError) {eval ':$-('}
+ end
+
+ def test_inspect_number
+ # 5) Inconsistency between :$0 and :$1? The first one is valid, but the
+ # latter isn't.
+ assert_inspect_evaled(':$0')
+ assert_inspect_evaled(':$1')
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_system.rb b/ruby_1_8_6/test/ruby/test_system.rb
new file mode 100644
index 0000000000..f3a71598f7
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_system.rb
@@ -0,0 +1,64 @@
+require 'test/unit'
+$:.replace([File.dirname(File.expand_path(__FILE__))] | $:)
+require 'envutil'
+
+class TestSystem < Test::Unit::TestCase
+ def valid_syntax?(code, fname)
+ eval("BEGIN {return true}\n#{code}", nil, fname, 0)
+ end
+
+ def test_system
+ ruby = EnvUtil.rubybin
+ assert_equal("foobar\n", `echo foobar`)
+ assert_equal('foobar', `#{ruby} -e 'print "foobar"'`)
+
+ tmp = open("script_tmp", "w")
+ tmp.print "print $zzz\n";
+ tmp.close
+
+ assert_equal('true', `#{ruby} -s script_tmp -zzz`)
+ assert_equal('555', `#{ruby} -s script_tmp -zzz=555`)
+
+ tmp = open("script_tmp", "w")
+ tmp.print "#! /usr/local/bin/ruby -s\n";
+ tmp.print "print $zzz\n";
+ tmp.close
+
+ assert_equal('678', `#{ruby} script_tmp -zzz=678`)
+
+ tmp = open("script_tmp", "w")
+ tmp.print "this is a leading junk\n";
+ tmp.print "#! /usr/local/bin/ruby -s\n";
+ tmp.print "print $zzz\n";
+ tmp.print "__END__\n";
+ tmp.print "this is a trailing junk\n";
+ tmp.close
+
+ assert_equal('nil', `#{ruby} -x script_tmp`)
+ assert_equal('555', `#{ruby} -x script_tmp -zzz=555`)
+
+ tmp = open("script_tmp", "w")
+ for i in 1..5
+ tmp.print i, "\n"
+ end
+ tmp.close
+
+ `#{ruby} -i.bak -pe 'sub(/^[0-9]+$/){$&.to_i * 5}' script_tmp`
+ tmp = open("script_tmp", "r")
+ while tmp.gets
+ assert_equal(0, $_.to_i % 5)
+ end
+ tmp.close
+
+ File.unlink "script_tmp" or `/bin/rm -f "script_tmp"`
+ File.unlink "script_tmp.bak" or `/bin/rm -f "script_tmp.bak"`
+ end
+
+ def test_syntax
+ assert_nothing_raised(Exception) do
+ for script in Dir[File.expand_path("../../../{lib,sample,ext}/**/*.rb", __FILE__)]
+ valid_syntax? IO::read(script), script
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_time.rb b/ruby_1_8_6/test/ruby/test_time.rb
new file mode 100644
index 0000000000..ad9b64ae0e
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_time.rb
@@ -0,0 +1,74 @@
+require 'test/unit'
+
+class TestTime < Test::Unit::TestCase
+ def test_time_add()
+ assert_equal(Time.utc(2000, 3, 21, 3, 30) + 3 * 3600,
+ Time.utc(2000, 3, 21, 6, 30))
+ assert_equal(Time.utc(2000, 3, 21, 3, 30) + (-3 * 3600),
+ Time.utc(2000, 3, 21, 0, 30))
+ assert_equal(0, (Time.at(1.1) + 0.9).usec)
+ end
+
+ def test_time_subt()
+ assert_equal(Time.utc(2000, 3, 21, 3, 30) - 3 * 3600,
+ Time.utc(2000, 3, 21, 0, 30))
+ assert_equal(Time.utc(2000, 3, 21, 3, 30) - (-3 * 3600),
+ Time.utc(2000, 3, 21, 6, 30))
+ assert_equal(900000, (Time.at(1.1) - 0.2).usec)
+ end
+
+ def test_time_time()
+ assert_equal(Time.utc(2000, 3, 21, 3, 30) \
+ -Time.utc(2000, 3, 21, 0, 30), 3*3600)
+ assert_equal(Time.utc(2000, 3, 21, 0, 30) \
+ -Time.utc(2000, 3, 21, 3, 30), -3*3600)
+ end
+
+ def negative_time_t?
+ begin
+ Time.at(-1)
+ true
+ rescue ArgumentError
+ false
+ end
+ end
+
+ def test_timegm
+ if negative_time_t?
+ assert_equal(-0x80000000, Time.utc(1901, 12, 13, 20, 45, 52).tv_sec)
+ assert_equal(-2, Time.utc(1969, 12, 31, 23, 59, 58).tv_sec)
+ assert_equal(-1, Time.utc(1969, 12, 31, 23, 59, 59).tv_sec)
+ end
+
+ assert_equal(0, Time.utc(1970, 1, 1, 0, 0, 0).tv_sec) # the Epoch
+ assert_equal(1, Time.utc(1970, 1, 1, 0, 0, 1).tv_sec)
+ assert_equal(31535999, Time.utc(1970, 12, 31, 23, 59, 59).tv_sec)
+ assert_equal(31536000, Time.utc(1971, 1, 1, 0, 0, 0).tv_sec)
+ assert_equal(78796799, Time.utc(1972, 6, 30, 23, 59, 59).tv_sec)
+
+ # 1972-06-30T23:59:60Z is the first leap second.
+ if Time.utc(1972, 7, 1, 0, 0, 0) - Time.utc(1972, 6, 30, 23, 59, 59) == 1
+ # no leap second.
+ assert_equal(78796800, Time.utc(1972, 7, 1, 0, 0, 0).tv_sec)
+ assert_equal(78796801, Time.utc(1972, 7, 1, 0, 0, 1).tv_sec)
+ assert_equal(946684800, Time.utc(2000, 1, 1, 0, 0, 0).tv_sec)
+ assert_equal(0x7fffffff, Time.utc(2038, 1, 19, 3, 14, 7).tv_sec)
+ else
+ # leap seconds supported.
+ assert_equal(2, Time.utc(1972, 7, 1, 0, 0, 0) - Time.utc(1972, 6, 30, 23, 59, 59))
+ assert_equal(78796800, Time.utc(1972, 6, 30, 23, 59, 60).tv_sec)
+ assert_equal(78796801, Time.utc(1972, 7, 1, 0, 0, 0).tv_sec)
+ assert_equal(78796802, Time.utc(1972, 7, 1, 0, 0, 1).tv_sec)
+ assert_equal(946684822, Time.utc(2000, 1, 1, 0, 0, 0).tv_sec)
+ end
+ end
+
+ def test_huge_difference # [ruby-dev:22619]
+ if negative_time_t?
+ assert_equal(Time.at(-0x80000000), Time.at(0x7fffffff) - 0xffffffff)
+ assert_equal(Time.at(-0x80000000), Time.at(0x7fffffff) + (-0xffffffff))
+ assert_equal(Time.at(0x7fffffff), Time.at(-0x80000000) + 0xffffffff)
+ assert_equal(Time.at(0x7fffffff), Time.at(-0x80000000) - (-0xffffffff))
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_trace.rb b/ruby_1_8_6/test/ruby/test_trace.rb
new file mode 100644
index 0000000000..6adfe0bf64
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_trace.rb
@@ -0,0 +1,21 @@
+require 'test/unit'
+
+class TestTrace < Test::Unit::TestCase
+ def test_trace
+ $x = 1234
+ $y = 0
+ trace_var :$x, proc{$y = $x}
+ $x = 40414
+ assert_equal($x, $y)
+
+ untrace_var :$x
+ $x = 19660208
+ assert_not_equal($x, $y)
+
+ trace_var :$x, proc{$x *= 2}
+ $x = 5
+ assert_equal(10, $x)
+
+ untrace_var :$x
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_variable.rb b/ruby_1_8_6/test/ruby/test_variable.rb
new file mode 100644
index 0000000000..8726160826
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_variable.rb
@@ -0,0 +1,53 @@
+require 'test/unit'
+
+class TestVariable < Test::Unit::TestCase
+ class Gods
+ @@rule = "Uranus"
+ def ruler0
+ @@rule
+ end
+
+ def self.ruler1 # <= per method definition style
+ @@rule
+ end
+ class << self # <= multiple method definition style
+ def ruler2
+ @@rule
+ end
+ end
+ end
+
+ module Olympians
+ @@rule ="Zeus"
+ def ruler3
+ @@rule
+ end
+ end
+
+ class Titans < Gods
+ @@rule = "Cronus"
+ include Olympians # OK to cause warning (intentional)
+ end
+
+ def test_variable
+ assert_instance_of(Fixnum, $$)
+
+ # read-only variable
+ assert_raises(NameError) do
+ $$ = 5
+ end
+
+ foobar = "foobar"
+ $_ = foobar
+ assert_equal(foobar, $_)
+
+ assert_equal("Cronus", Gods.new.ruler0)
+ assert_equal("Cronus", Gods.ruler1)
+ assert_equal("Cronus", Gods.ruler2)
+ assert_equal("Cronus", Titans.ruler1)
+ assert_equal("Cronus", Titans.ruler2)
+ atlas = Titans.new
+ assert_equal("Cronus", atlas.ruler0)
+ assert_equal("Zeus", atlas.ruler3)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/test_whileuntil.rb b/ruby_1_8_6/test/ruby/test_whileuntil.rb
new file mode 100644
index 0000000000..6faed31160
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/test_whileuntil.rb
@@ -0,0 +1,77 @@
+require 'test/unit'
+
+class TestWhileuntil < Test::Unit::TestCase
+ def test_while
+ tmp = open("while_tmp", "w")
+ tmp.print "tvi925\n";
+ tmp.print "tvi920\n";
+ tmp.print "vt100\n";
+ tmp.print "Amiga\n";
+ tmp.print "paper\n";
+ tmp.close
+
+ tmp = open("while_tmp", "r")
+ assert_instance_of(File, tmp)
+
+ while line = tmp.gets()
+ break if /vt100/ =~ line
+ end
+
+ assert(!tmp.eof?)
+ assert_match(/vt100/, line)
+ tmp.close
+
+ tmp = open("while_tmp", "r")
+ while line = tmp.gets()
+ next if /vt100/ =~ line
+ assert_no_match(/vt100/, line)
+ end
+ assert(tmp.eof?)
+ assert_no_match(/vt100/, line)
+ tmp.close
+
+ tmp = open("while_tmp", "r")
+ while tmp.gets()
+ line = $_
+ gsub(/vt100/, 'VT100')
+ if $_ != line
+ $_.gsub!('VT100', 'Vt100')
+ redo
+ end
+ assert_no_match(/vt100/, $_)
+ assert_no_match(/VT100/, $_)
+ end
+ assert(tmp.eof?)
+ tmp.close
+
+ sum=0
+ for i in 1..10
+ sum += i
+ i -= 1
+ if i > 0
+ redo
+ end
+ end
+ assert_equal(220, sum)
+
+ tmp = open("while_tmp", "r")
+ while line = tmp.gets()
+ break if 3
+ assert_no_match(/vt100/, line)
+ assert_no_match(/Amiga/, line)
+ assert_no_match(/paper/, line)
+ end
+ tmp.close
+
+ File.unlink "while_tmp" or `/bin/rm -f "while_tmp"`
+ assert(!File.exist?("while_tmp"))
+ end
+
+ def test_until
+ i = 0
+ until i>4
+ i+=1
+ end
+ assert(i>4)
+ end
+end
diff --git a/ruby_1_8_6/test/ruby/ut_eof.rb b/ruby_1_8_6/test/ruby/ut_eof.rb
new file mode 100644
index 0000000000..e6f6eddd6f
--- /dev/null
+++ b/ruby_1_8_6/test/ruby/ut_eof.rb
@@ -0,0 +1,128 @@
+require 'test/unit'
+
+module TestEOF
+ def test_eof_0
+ open_file("") {|f|
+ assert_equal("", f.read(0))
+ assert_equal("", f.read(0))
+ assert_equal("", f.read)
+ assert_nil(f.read(0))
+ assert_nil(f.read(0))
+ }
+ open_file("") {|f|
+ assert_nil(f.read(1))
+ assert_equal("", f.read)
+ assert_nil(f.read(1))
+ }
+ open_file("") {|f|
+ s = "x"
+ assert_equal("", f.read(nil, s))
+ assert_equal("", s)
+ }
+ open_file("") {|f|
+ s = "x"
+ assert_nil(f.read(10, s))
+ assert_equal("", s)
+ }
+ end
+
+ def test_eof_0_rw
+ return unless respond_to? :open_file_rw
+ open_file_rw("") {|f|
+ assert_equal("", f.read)
+ assert_equal("", f.read)
+ assert_equal(0, f.syswrite(""))
+ assert_equal("", f.read)
+ }
+ end
+
+ def test_eof_1
+ open_file("a") {|f|
+ assert_equal("", f.read(0))
+ assert_equal("a", f.read(1))
+ assert_equal("" , f.read(0))
+ assert_equal("" , f.read(0))
+ assert_equal("", f.read)
+ assert_nil(f.read(0))
+ assert_nil(f.read(0))
+ }
+ open_file("a") {|f|
+ assert_equal("a", f.read(1))
+ assert_nil(f.read(1))
+ }
+ open_file("a") {|f|
+ assert_equal("a", f.read(2))
+ assert_nil(f.read(1))
+ assert_equal("", f.read)
+ assert_nil(f.read(1))
+ }
+ open_file("a") {|f|
+ assert_equal("a", f.read)
+ assert_nil(f.read(1))
+ assert_equal("", f.read)
+ assert_nil(f.read(1))
+ }
+ open_file("a") {|f|
+ assert_equal("a", f.read(2))
+ assert_equal("", f.read)
+ assert_equal("", f.read)
+ }
+ open_file("a") {|f|
+ assert_equal("a", f.read)
+ assert_nil(f.read(0))
+ }
+ open_file("a") {|f|
+ s = "x"
+ assert_equal("a", f.read(nil, s))
+ assert_equal("a", s)
+ }
+ open_file("a") {|f|
+ s = "x"
+ assert_equal("a", f.read(10, s))
+ assert_equal("a", s)
+ }
+ end
+
+ def test_eof_2
+ open_file("") {|f|
+ assert_equal("", f.read)
+ assert(f.eof?)
+ }
+ end
+
+ def test_eof_3
+ open_file("") {|f|
+ assert(f.eof?)
+ }
+ end
+
+ module Seek
+ def open_file_seek(content, pos)
+ open_file(content) do |f|
+ f.seek(pos)
+ yield f
+ end
+ end
+
+ def test_eof_0_seek
+ open_file_seek("", 10) {|f|
+ assert_equal(10, f.pos)
+ assert_equal("", f.read(0))
+ assert_equal("", f.read)
+ assert_nil(f.read(0))
+ assert_equal("", f.read)
+ }
+ end
+
+ def test_eof_1_seek
+ open_file_seek("a", 10) {|f|
+ assert_equal("", f.read)
+ assert_equal("", f.read)
+ }
+ open_file_seek("a", 1) {|f|
+ assert_equal("", f.read)
+ assert_equal("", f.read)
+ }
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/runner.rb b/ruby_1_8_6/test/runner.rb
new file mode 100644
index 0000000000..d274bc8929
--- /dev/null
+++ b/ruby_1_8_6/test/runner.rb
@@ -0,0 +1,7 @@
+require 'test/unit'
+
+rcsid = %w$Id$
+Version = rcsid[2].scan(/\d+/).collect!(&method(:Integer)).freeze
+Release = rcsid[3].freeze
+
+exit Test::Unit::AutoRunner.run(true, File.dirname($0))
diff --git a/ruby_1_8_6/test/sdbm/test_sdbm.rb b/ruby_1_8_6/test/sdbm/test_sdbm.rb
new file mode 100644
index 0000000000..8789d719dd
--- /dev/null
+++ b/ruby_1_8_6/test/sdbm/test_sdbm.rb
@@ -0,0 +1,534 @@
+require 'test/unit'
+
+begin
+ require 'sdbm'
+rescue LoadError
+end
+
+class TestSDBM < Test::Unit::TestCase
+ def setup
+ @path = "tmptest_sdbm_"
+ assert_instance_of(SDBM, @sdbm = SDBM.new(@path))
+ end
+ def teardown
+ assert_nil(@sdbm.close)
+ ObjectSpace.each_object(SDBM) do |obj|
+ obj.close unless obj.closed?
+ end
+ File.delete *Dir.glob("tmptest_sdbm*").to_a
+ p Dir.glob("tmptest_sdbm*") if $DEBUG
+ end
+
+ def check_size(expect, sdbm=@sdbm)
+ assert_equal(expect, sdbm.size)
+ n = 0
+ sdbm.each { n+=1 }
+ assert_equal(expect, n)
+ if expect == 0
+ assert_equal(true, sdbm.empty?)
+ else
+ assert_equal(false, sdbm.empty?)
+ end
+ end
+
+ def have_fork?
+ begin
+ fork{}
+ true
+ rescue NotImplementedError
+ false
+ end
+ end
+
+ def test_version
+ assert(! SDBM.const_defined?(:VERSION))
+ end
+
+ def test_s_new_has_no_block
+ # SDBM.new ignore the block
+ foo = true
+ assert_instance_of(SDBM, sdbm = SDBM.new("tmptest_sdbm") { foo = false })
+ assert_equal(foo, true)
+ assert_nil(sdbm.close)
+ end
+ def test_s_open_no_create
+ assert_nil(sdbm = SDBM.open("tmptest_sdbm", nil))
+ ensure
+ sdbm.close if sdbm
+ end
+ def test_s_open_with_block
+ assert_equal(SDBM.open("tmptest_sdbm") { :foo }, :foo)
+ end
+=begin
+ # Is it guaranteed on many OS?
+ def test_s_open_lock_one_process
+ # locking on one process
+ assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644))
+ assert_raise(Errno::EWOULDBLOCK) {
+ begin
+ SDBM.open("tmptest_sdbm", 0644)
+ rescue Errno::EAGAIN
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ end
+=end
+
+ def test_s_open_nolock
+ # sdbm 1.8.0 specific
+ if not defined? SDBM::NOLOCK
+ return
+ end
+ return unless have_fork? # snip this test
+
+ fork() {
+ assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644,
+ SDBM::NOLOCK))
+ sleep 2
+ }
+ sleep 1
+ begin
+ sdbm2 = nil
+ assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ assert_instance_of(SDBM, sdbm2 = SDBM.open("tmptest_sdbm", 0644))
+ }
+ ensure
+ Process.wait
+ sdbm2.close if sdbm2
+ end
+
+ p Dir.glob("tmptest_sdbm*") if $DEBUG
+
+ fork() {
+ assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ sdbm2 = nil
+ assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ # this test is failed on Cygwin98 (???)
+ assert_instance_of(SDBM, sdbm2 = SDBM.open("tmptest_sdbm", 0644,
+ SDBM::NOLOCK))
+ }
+ ensure
+ Process.wait
+ sdbm2.close if sdbm2
+ end
+ end
+
+ def test_s_open_error
+ return if /(ms|bcc)win|mingw|djgpp/ =~ RUBY_PLATFORM
+ assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0))
+ assert_raise(Errno::EACCES) {
+ SDBM.open("tmptest_sdbm", 0)
+ }
+ sdbm.close
+ end
+
+ def test_close
+ assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm"))
+ assert_nil(sdbm.close)
+
+ # closed SDBM file
+ assert_raise(SDBMError) { sdbm.close }
+ end
+
+ def test_aref
+ assert_equal('bar', @sdbm['foo'] = 'bar')
+ assert_equal('bar', @sdbm['foo'])
+
+ assert_nil(@sdbm['bar'])
+ end
+
+ def test_fetch
+ assert_equal('bar', @sdbm['foo']='bar')
+ assert_equal('bar', @sdbm.fetch('foo'))
+
+ # key not found
+ assert_raise(IndexError) {
+ @sdbm.fetch('bar')
+ }
+
+ # test for `ifnone' arg
+ assert_equal('baz', @sdbm.fetch('bar', 'baz'))
+
+ # test for `ifnone' block
+ assert_equal('foobar', @sdbm.fetch('bar') {|key| 'foo' + key })
+ end
+
+ def test_aset
+ num = 0
+ 2.times {|i|
+ assert_equal('foo', @sdbm['foo'] = 'foo')
+ assert_equal('foo', @sdbm['foo'])
+ assert_equal('bar', @sdbm['foo'] = 'bar')
+ assert_equal('bar', @sdbm['foo'])
+
+ num += 1 if i == 0
+ assert_equal(num, @sdbm.size)
+
+ # assign nil
+ assert_equal('', @sdbm['bar'] = '')
+ assert_equal('', @sdbm['bar'])
+
+ num += 1 if i == 0
+ assert_equal(num, @sdbm.size)
+
+ # empty string
+ assert_equal('', @sdbm[''] = '')
+ assert_equal('', @sdbm[''])
+
+ num += 1 if i == 0
+ assert_equal(num, @sdbm.size)
+
+ # Fixnum
+ assert_equal('200', @sdbm['100'] = '200')
+ assert_equal('200', @sdbm['100'])
+
+ num += 1 if i == 0
+ assert_equal(num, @sdbm.size)
+
+ # Big key and value
+ assert_equal('y' * 100, @sdbm['x' * 100] = 'y' * 100)
+ assert_equal('y' * 100, @sdbm['x' * 100])
+
+ num += 1 if i == 0
+ assert_equal(num, @sdbm.size)
+ }
+ end
+
+ def test_index
+ assert_equal('bar', @sdbm['foo'] = 'bar')
+ assert_equal('foo', @sdbm.index('bar'))
+ assert_nil(@sdbm['bar'])
+ end
+
+ def test_indexes
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+ assert_equal(values.reverse, @sdbm.indexes(*keys.reverse))
+ end
+
+ def test_values_at
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+ assert_equal(values.reverse, @sdbm.values_at(*keys.reverse))
+ end
+
+ def test_select_with_block
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+ ret = @sdbm.select {|k,v|
+ assert_equal(k.upcase, v)
+ k != "bar"
+ }
+ assert_equal([['baz', 'BAZ'], ['foo', 'FOO']],
+ ret.sort)
+ end
+
+ def test_length
+ num = 10
+ assert_equal(0, @sdbm.size)
+ num.times {|i|
+ i = i.to_s
+ @sdbm[i] = i
+ }
+ assert_equal(num, @sdbm.size)
+
+ @sdbm.shift
+
+ assert_equal(num - 1, @sdbm.size)
+ end
+
+ def test_empty?
+ assert_equal(true, @sdbm.empty?)
+ @sdbm['foo'] = 'FOO'
+ assert_equal(false, @sdbm.empty?)
+ end
+
+ def test_each_pair
+ n = 0
+ @sdbm.each_pair { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+
+ n = 0
+ ret = @sdbm.each_pair {|key, val|
+ assert_not_nil(i = keys.index(key))
+ assert_equal(val, values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@sdbm, ret)
+ end
+
+ def test_each_value
+ n = 0
+ @sdbm.each_value { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+
+ n = 0
+ ret = @sdbm.each_value {|val|
+ assert_not_nil(key = @sdbm.index(val))
+ assert_not_nil(i = keys.index(key))
+ assert_equal(val, values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@sdbm, ret)
+ end
+
+ def test_each_key
+ n = 0
+ @sdbm.each_key { n += 1 }
+ assert_equal(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+
+ n = 0
+ ret = @sdbm.each_key {|key|
+ assert_not_nil(i = keys.index(key))
+ assert_equal(@sdbm[key], values[i])
+
+ n += 1
+ }
+ assert_equal(keys.size, n)
+ assert_equal(@sdbm, ret)
+ end
+
+ def test_keys
+ assert_equal([], @sdbm.keys)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+
+ assert_equal(keys.sort, @sdbm.keys.sort)
+ assert_equal(values.sort, @sdbm.values.sort)
+ end
+
+ def test_values
+ test_keys
+ end
+
+ def test_shift
+ assert_nil(@sdbm.shift)
+ assert_equal(0, @sdbm.size)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+
+ ret_keys = []
+ ret_values = []
+ while ret = @sdbm.shift
+ ret_keys.push ret[0]
+ ret_values.push ret[1]
+
+ assert_equal(keys.size - ret_keys.size, @sdbm.size)
+ end
+
+ assert_equal(keys.sort, ret_keys.sort)
+ assert_equal(values.sort, ret_values.sort)
+ end
+
+ def test_delete
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ key = keys[1]
+
+ assert_nil(@sdbm.delete(key))
+ assert_equal(0, @sdbm.size)
+
+ @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
+
+ assert_equal('BAR', @sdbm.delete(key))
+ assert_nil(@sdbm[key])
+ assert_equal(2, @sdbm.size)
+
+ assert_nil(@sdbm.delete(key))
+ end
+ def test_delete_with_block
+ key = 'no called block'
+ @sdbm[key] = 'foo'
+ assert_equal('foo', @sdbm.delete(key) {|k| k.replace 'called block'})
+ assert_equal('no called block', key)
+ assert_equal(0, @sdbm.size)
+
+ key = 'no called block'
+ assert_equal(:blockval,
+ @sdbm.delete(key) {|k| k.replace 'called block'; :blockval})
+ assert_equal('called block', key)
+ assert_equal(0, @sdbm.size)
+ end
+
+ def test_delete_if
+ v = "0"
+ 100.times {@sdbm[v] = v; v = v.next}
+
+ ret = @sdbm.delete_if {|key, val| key.to_i < 50}
+ assert_equal(@sdbm, ret)
+ check_size(50, @sdbm)
+
+ ret = @sdbm.delete_if {|key, val| key.to_i >= 50}
+ assert_equal(@sdbm, ret)
+ check_size(0, @sdbm)
+
+ # break
+ v = "0"
+ 100.times {@sdbm[v] = v; v = v.next}
+ check_size(100, @sdbm)
+ n = 0;
+ @sdbm.delete_if {|key, val|
+ break if n > 50
+ n+=1
+ true
+ }
+ assert_equal(51, n)
+ check_size(49, @sdbm)
+
+ @sdbm.clear
+
+ # raise
+ v = "0"
+ 100.times {@sdbm[v] = v; v = v.next}
+ check_size(100, @sdbm)
+ n = 0;
+ begin
+ @sdbm.delete_if {|key, val|
+ raise "runtime error" if n > 50
+ n+=1
+ true
+ }
+ rescue
+ end
+ assert_equal(51, n)
+ check_size(49, @sdbm)
+ end
+
+ def test_reject
+ v = "0"
+ 100.times {@sdbm[v] = v; v = v.next}
+
+ hash = @sdbm.reject {|key, val| key.to_i < 50}
+ assert_instance_of(Hash, hash)
+ assert_equal(100, @sdbm.size)
+
+ assert_equal(50, hash.size)
+ hash.each_pair {|key,val|
+ assert_equal(false, key.to_i < 50)
+ assert_equal(key, val)
+ }
+
+ hash = @sdbm.reject {|key, val| key.to_i < 100}
+ assert_instance_of(Hash, hash)
+ assert_equal(true, hash.empty?)
+ end
+
+ def test_clear
+ v = "1"
+ 100.times {v = v.next; @sdbm[v] = v}
+
+ assert_equal(@sdbm, @sdbm.clear)
+
+ # validate SDBM#size
+ i = 0
+ @sdbm.each { i += 1 }
+ assert_equal(@sdbm.size, i)
+ assert_equal(0, i)
+ end
+
+ def test_invert
+ v = "0"
+ 100.times {@sdbm[v] = v; v = v.next}
+
+ hash = @sdbm.invert
+ assert_instance_of(Hash, hash)
+ assert_equal(100, hash.size)
+ hash.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_update
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @sdbm["101"] = "101"
+ @sdbm.update hash
+ assert_equal(101, @sdbm.size)
+ @sdbm.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_replace
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @sdbm["101"] = "101"
+ @sdbm.replace hash
+ assert_equal(100, @sdbm.size)
+ @sdbm.each_pair {|key, val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_haskey?
+ assert_equal('bar', @sdbm['foo']='bar')
+ assert_equal(true, @sdbm.has_key?('foo'))
+ assert_equal(false, @sdbm.has_key?('bar'))
+ end
+
+ def test_has_value?
+ assert_equal('bar', @sdbm['foo']='bar')
+ assert_equal(true, @sdbm.has_value?('bar'))
+ assert_equal(false, @sdbm.has_value?('foo'))
+ end
+
+ def test_to_a
+ v = "0"
+ 100.times {v = v.next; @sdbm[v] = v}
+
+ ary = @sdbm.to_a
+ assert_instance_of(Array, ary)
+ assert_equal(100, ary.size)
+ ary.each {|key,val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+
+ def test_to_hash
+ v = "0"
+ 100.times {v = v.next; @sdbm[v] = v}
+
+ hash = @sdbm.to_hash
+ assert_instance_of(Hash, hash)
+ assert_equal(100, hash.size)
+ hash.each {|key,val|
+ assert_equal(key.to_i, val.to_i)
+ }
+ end
+end
diff --git a/ruby_1_8_6/test/soap/asp.net/hello.wsdl b/ruby_1_8_6/test/soap/asp.net/hello.wsdl
new file mode 100644
index 0000000000..b94129c152
--- /dev/null
+++ b/ruby_1_8_6/test/soap/asp.net/hello.wsdl
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="utf-8"?>
+<wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
+xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+xmlns:s="http://www.w3.org/2001/XMLSchema"
+xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
+xmlns:tns="http://localhost/WebService/"
+xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
+xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
+targetNamespace="http://localhost/WebService/"
+xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
+ <wsdl:types>
+ <s:schema elementFormDefault="qualified"
+targetNamespace="http://localhost/WebService/">
+ <s:element name="HelloWorld">
+ <s:complexType />
+ </s:element>
+ <s:element name="HelloWorldResponse">
+ <s:complexType>
+ <s:sequence>
+ <s:element minOccurs="0" maxOccurs="1"
+name="HelloWorldResult" type="s:string" />
+ </s:sequence>
+ </s:complexType>
+ </s:element>
+ <s:element name="SayHello">
+ <s:complexType>
+ <s:sequence>
+ <s:element minOccurs="0" maxOccurs="1" name="name"
+type="s:string" />
+ </s:sequence>
+ </s:complexType>
+ </s:element>
+ <s:element name="SayHelloResponse">
+ <s:complexType>
+ <s:sequence>
+ <s:element minOccurs="0" maxOccurs="1"
+name="SayHelloResult" type="s:string" />
+ </s:sequence>
+ </s:complexType>
+ </s:element>
+ </s:schema>
+ </wsdl:types>
+ <wsdl:message name="HelloWorldSoapIn">
+ <wsdl:part name="parameters" element="tns:HelloWorld" />
+ </wsdl:message>
+ <wsdl:message name="HelloWorldSoapOut">
+ <wsdl:part name="parameters" element="tns:HelloWorldResponse" />
+ </wsdl:message>
+ <wsdl:message name="SayHelloSoapIn">
+ <wsdl:part name="parameters" element="tns:SayHello" />
+ </wsdl:message>
+ <wsdl:message name="SayHelloSoapOut">
+ <wsdl:part name="parameters" element="tns:SayHelloResponse" />
+ </wsdl:message>
+ <wsdl:portType name="Service1Soap">
+ <wsdl:operation name="HelloWorld">
+ <wsdl:input message="tns:HelloWorldSoapIn" />
+ <wsdl:output message="tns:HelloWorldSoapOut" />
+ </wsdl:operation>
+ <wsdl:operation name="SayHello">
+ <wsdl:input message="tns:SayHelloSoapIn" />
+ <wsdl:output message="tns:SayHelloSoapOut" />
+ </wsdl:operation>
+ </wsdl:portType>
+ <wsdl:binding name="Service1Soap" type="tns:Service1Soap">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
+style="document" />
+ <wsdl:operation name="HelloWorld">
+ <soap:operation
+soapAction="http://localhost/WebService/HelloWorld" style="document" />
+ <wsdl:input>
+ <soap:body use="literal" />
+ </wsdl:input>
+ <wsdl:output>
+ <soap:body use="literal" />
+ </wsdl:output>
+ </wsdl:operation>
+ <wsdl:operation name="SayHello">
+ <soap:operation soapAction="http://localhost/WebService/SayHello"
+style="document" />
+ <wsdl:input>
+ <soap:body use="literal" />
+ </wsdl:input>
+ <wsdl:output>
+ <soap:body use="literal" />
+ </wsdl:output>
+ </wsdl:operation>
+ </wsdl:binding>
+ <wsdl:service name="Service1">
+ <documentation xmlns="http://schemas.xmlsoap.org/wsdl/" />
+ <wsdl:port name="Service1Soap" binding="tns:Service1Soap">
+ <soap:address
+location="http://localhost/WebService/Service1.asmx" />
+ </wsdl:port>
+ </wsdl:service>
+</wsdl:definitions>
diff --git a/ruby_1_8_6/test/soap/asp.net/test_aspdotnet.rb b/ruby_1_8_6/test/soap/asp.net/test_aspdotnet.rb
new file mode 100644
index 0000000000..7d5f3fd288
--- /dev/null
+++ b/ruby_1_8_6/test/soap/asp.net/test_aspdotnet.rb
@@ -0,0 +1,111 @@
+require 'test/unit'
+require 'soap/rpc/standaloneServer'
+require 'soap/rpc/driver'
+
+
+module SOAP; module ASPDotNet
+
+
+class TestASPDotNet < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = "http://localhost/WebService/"
+
+ def on_init
+ add_document_method(
+ self,
+ Namespace + 'SayHello',
+ 'sayHello',
+ XSD::QName.new(Namespace, 'SayHello'),
+ XSD::QName.new(Namespace, 'SayHelloResponse')
+ )
+ end
+
+ def sayHello(arg)
+ name = arg['name']
+ "Hello #{name}"
+ end
+ end
+
+ Port = 17171
+ Endpoint = "http://localhost:#{Port}/"
+
+ def setup
+ setup_server
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', Server::Namespace, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_document_method
+ @client = SOAP::RPC::Driver.new(Endpoint, Server::Namespace)
+ @client.wiredump_dev = STDOUT if $DEBUG
+ @client.add_document_method('sayHello', Server::Namespace + 'SayHello',
+ XSD::QName.new(Server::Namespace, 'SayHello'),
+ XSD::QName.new(Server::Namespace, 'SayHelloResponse'))
+ assert_equal("Hello Mike", @client.sayHello(:name => "Mike"))
+ end
+
+ def test_aspdotnethandler
+ @client = SOAP::RPC::Driver.new(Endpoint, Server::Namespace)
+ @client.wiredump_dev = STDOUT if $DEBUG
+ @client.add_method_with_soapaction('sayHello', Server::Namespace + 'SayHello', 'name')
+ @client.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace
+ assert_equal("Hello Mike", @client.sayHello("Mike"))
+ end
+
+ if defined?(HTTPAccess2)
+
+ # qualified!
+ REQUEST_ASPDOTNETHANDLER =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:sayHello xmlns:n1="http://localhost/WebService/">
+ <n1:name>Mike</n1:name>
+ </n1:sayHello>
+ </env:Body>
+</env:Envelope>]
+
+ def test_aspdotnethandler_envelope
+ @client = SOAP::RPC::Driver.new(Endpoint, Server::Namespace)
+ @client.wiredump_dev = str = ''
+ @client.add_method_with_soapaction('sayHello', Server::Namespace + 'SayHello', 'name')
+ @client.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace
+ assert_equal("Hello Mike", @client.sayHello("Mike"))
+ assert_equal(REQUEST_ASPDOTNETHANDLER, parse_requestxml(str))
+ end
+
+ def parse_requestxml(str)
+ str.split(/\r?\n\r?\n/)[3]
+ end
+
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/soap/calc/calc.rb b/ruby_1_8_6/test/soap/calc/calc.rb
new file mode 100644
index 0000000000..6bc78803b3
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/calc.rb
@@ -0,0 +1,17 @@
+module CalcService
+ def self.add(lhs, rhs)
+ lhs + rhs
+ end
+
+ def self.sub(lhs, rhs)
+ lhs - rhs
+ end
+
+ def self.multi(lhs, rhs)
+ lhs * rhs
+ end
+
+ def self.div(lhs, rhs)
+ lhs / rhs
+ end
+end
diff --git a/ruby_1_8_6/test/soap/calc/calc2.rb b/ruby_1_8_6/test/soap/calc/calc2.rb
new file mode 100644
index 0000000000..69495730e7
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/calc2.rb
@@ -0,0 +1,29 @@
+class CalcService2
+ def initialize(value = 0)
+ @value = value
+ end
+
+ def set_value(value)
+ @value = value
+ end
+
+ def get_value
+ @value
+ end
+
+ def +(rhs)
+ @value + rhs
+ end
+
+ def -(rhs)
+ @value - rhs
+ end
+
+ def *(rhs)
+ @value * rhs
+ end
+
+ def /(rhs)
+ @value / rhs
+ end
+end
diff --git a/ruby_1_8_6/test/soap/calc/server.cgi b/ruby_1_8_6/test/soap/calc/server.cgi
new file mode 100644
index 0000000000..1eb0d1d864
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/server.cgi
@@ -0,0 +1,13 @@
+require 'soap/rpc/cgistub'
+
+class CalcServer < SOAP::RPC::CGIStub
+ def initialize(*arg)
+ super
+
+ require 'calc'
+ servant = CalcService
+ add_servant(servant, 'http://tempuri.org/calcService')
+ end
+end
+
+status = CalcServer.new('CalcServer', nil).start
diff --git a/ruby_1_8_6/test/soap/calc/server.rb b/ruby_1_8_6/test/soap/calc/server.rb
new file mode 100644
index 0000000000..a93774d909
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/server.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'calc'
+
+class CalcServer < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+
+ servant = CalcService
+ add_servant(servant, 'http://tempuri.org/calcService')
+ end
+end
+
+if $0 == __FILE__
+ status = CalcServer.new('CalcServer', nil, '0.0.0.0', 17171).start
+end
diff --git a/ruby_1_8_6/test/soap/calc/server2.rb b/ruby_1_8_6/test/soap/calc/server2.rb
new file mode 100644
index 0000000000..01c6d75289
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/server2.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'calc2'
+
+class CalcServer2 < SOAP::RPC::StandaloneServer
+ def on_init
+ servant = CalcService2.new
+ add_method(servant, 'set_value', 'newValue')
+ add_method(servant, 'get_value')
+ add_method_as(servant, '+', 'add', 'lhs')
+ add_method_as(servant, '-', 'sub', 'lhs')
+ add_method_as(servant, '*', 'multi', 'lhs')
+ add_method_as(servant, '/', 'div', 'lhs')
+ end
+end
+
+if $0 == __FILE__
+ status = CalcServer2.new('CalcServer', 'http://tempuri.org/calcService', '0.0.0.0', 17171).start
+end
diff --git a/ruby_1_8_6/test/soap/calc/test_calc.rb b/ruby_1_8_6/test/soap/calc/test_calc.rb
new file mode 100644
index 0000000000..88738716a6
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/test_calc.rb
@@ -0,0 +1,49 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'server.rb'
+
+
+module SOAP
+module Calc
+
+
+class TestCalc < Test::Unit::TestCase
+ Port = 17171
+
+ def setup
+ @server = CalcServer.new(self.class.name, nil, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/"
+ @calc = SOAP::RPC::Driver.new(@endpoint, 'http://tempuri.org/calcService')
+ @calc.add_method('add', 'lhs', 'rhs')
+ @calc.add_method('sub', 'lhs', 'rhs')
+ @calc.add_method('multi', 'lhs', 'rhs')
+ @calc.add_method('div', 'lhs', 'rhs')
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @calc.reset_stream
+ end
+
+ def test_calc
+ assert_equal(3, @calc.add(1, 2))
+ assert_equal(-1.1, @calc.sub(1.1, 2.2))
+ assert_equal(2.42, @calc.multi(1.1, 2.2))
+ assert_equal(2, @calc.div(5, 2))
+ assert_equal(2.5, @calc.div(5.0, 2))
+ assert_equal(1.0/0.0, @calc.div(1.1, 0))
+ assert_raises(ZeroDivisionError) do
+ @calc.div(1, 0)
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/calc/test_calc2.rb b/ruby_1_8_6/test/soap/calc/test_calc2.rb
new file mode 100644
index 0000000000..f334b29bdb
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/test_calc2.rb
@@ -0,0 +1,53 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'server2.rb'
+
+
+module SOAP
+module Calc
+
+
+class TestCalc2 < Test::Unit::TestCase
+ Port = 17171
+
+ def setup
+ @server = CalcServer2.new('CalcServer', 'http://tempuri.org/calcService', '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/"
+ @var = SOAP::RPC::Driver.new(@endpoint, 'http://tempuri.org/calcService')
+ @var.wiredump_dev = STDERR if $DEBUG
+ @var.add_method('set_value', 'newValue')
+ @var.add_method('get_value')
+ @var.add_method_as('+', 'add', 'rhs')
+ @var.add_method_as('-', 'sub', 'rhs')
+ @var.add_method_as('*', 'multi', 'rhs')
+ @var.add_method_as('/', 'div', 'rhs')
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @var.reset_stream
+ end
+
+ def test_calc2
+ assert_equal(1, @var.set_value(1))
+ assert_equal(3, @var + 2)
+ assert_equal(-1.2, @var - 2.2)
+ assert_equal(2.2, @var * 2.2)
+ assert_equal(0, @var / 2)
+ assert_equal(0.5, @var / 2.0)
+ assert_raises(ZeroDivisionError) do
+ @var / 0
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/calc/test_calc_cgi.rb b/ruby_1_8_6/test/soap/calc/test_calc_cgi.rb
new file mode 100644
index 0000000000..d28830629f
--- /dev/null
+++ b/ruby_1_8_6/test/soap/calc/test_calc_cgi.rb
@@ -0,0 +1,69 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'logger'
+require 'webrick'
+require 'rbconfig'
+
+
+module SOAP
+module Calc
+
+
+class TestCalcCGI < Test::Unit::TestCase
+ # This test shuld be run after installing ruby.
+ RUBYBIN = File.join(
+ Config::CONFIG["bindir"],
+ Config::CONFIG["ruby_install_name"] + Config::CONFIG["EXEEXT"]
+ )
+ RUBYBIN << " -d" if $DEBUG
+
+ Port = 17171
+
+ def setup
+ logger = Logger.new(STDERR)
+ logger.level = Logger::Severity::ERROR
+ @server = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Logger => logger,
+ :Port => Port,
+ :AccessLog => [],
+ :DocumentRoot => File.dirname(File.expand_path(__FILE__)),
+ :CGIPathEnv => ENV['PATH'],
+ :CGIInterpreter => RUBYBIN
+ )
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/server.cgi"
+ @calc = SOAP::RPC::Driver.new(@endpoint, 'http://tempuri.org/calcService')
+ @calc.wiredump_dev = STDERR if $DEBUG
+ @calc.add_method('add', 'lhs', 'rhs')
+ @calc.add_method('sub', 'lhs', 'rhs')
+ @calc.add_method('multi', 'lhs', 'rhs')
+ @calc.add_method('div', 'lhs', 'rhs')
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @calc.reset_stream
+ end
+
+ def test_calc_cgi
+ assert_equal(3, @calc.add(1, 2))
+ assert_equal(-1.1, @calc.sub(1.1, 2.2))
+ assert_equal(2.42, @calc.multi(1.1, 2.2))
+ assert_equal(2, @calc.div(5, 2))
+ assert_equal(2.5, @calc.div(5.0, 2))
+ assert_equal(1.0/0.0, @calc.div(1.1, 0))
+ assert_raises(ZeroDivisionError) do
+ @calc.div(1, 0)
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/fault/test_customfault.rb b/ruby_1_8_6/test/soap/fault/test_customfault.rb
new file mode 100644
index 0000000000..2f7bc2be6e
--- /dev/null
+++ b/ruby_1_8_6/test/soap/fault/test_customfault.rb
@@ -0,0 +1,58 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'soap/rpc/standaloneServer'
+
+
+module SOAP
+module Fault
+
+
+class TestCustomFault < Test::Unit::TestCase
+ Port = 17171
+
+ class CustomFaultServer < SOAP::RPC::StandaloneServer
+ def on_init
+ add_method(self, 'fault', 'msg')
+ end
+
+ def fault(msg)
+ SOAPFault.new(SOAPString.new("mycustom"),
+ SOAPString.new("error: #{msg}"),
+ SOAPString.new(self.class.name))
+ end
+ end
+
+ def setup
+ @server = CustomFaultServer.new('customfault', 'urn:customfault', '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/"
+ @client = SOAP::RPC::Driver.new(@endpoint, 'urn:customfault')
+ @client.wiredump_dev = STDERR if $DEBUG
+ @client.add_method("fault", "msg")
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @client.reset_stream
+ end
+
+ def test_custom_fault
+ begin
+ @client.fault("message")
+ assert(false, 'exception not raised')
+ rescue SOAP::FaultError => e
+ assert(true, 'exception raised')
+ assert_equal('error: message', e.message)
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/header/server.cgi b/ruby_1_8_6/test/soap/header/server.cgi
new file mode 100644
index 0000000000..2a188538d9
--- /dev/null
+++ b/ruby_1_8_6/test/soap/header/server.cgi
@@ -0,0 +1,119 @@
+require 'pstore'
+require 'soap/rpc/cgistub'
+require 'soap/header/simplehandler'
+
+
+class AuthHeaderPortServer < SOAP::RPC::CGIStub
+ PortName = 'http://tempuri.org/authHeaderPort'
+ SupportPortName = 'http://tempuri.org/authHeaderSupportPort'
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+ SessionDB = File.join(File.expand_path(File.dirname(__FILE__)), 'session.pstoredb')
+
+ class AuthHeaderService
+ def self.create
+ new
+ end
+
+ def deposit(amt)
+ "deposit #{amt} OK"
+ end
+
+ def withdrawal(amt)
+ "withdrawal #{amt} OK"
+ end
+ end
+
+ class AuthHeaderSupportService
+ def delete_sessiondb
+ File.unlink(SessionDB) if File.file?(SessionDB)
+ backup = SessionDB + "~"
+ File.unlink(backup) if File.file?(backup)
+ end
+ end
+
+ def initialize(*arg)
+ super
+ add_rpc_servant(AuthHeaderService.new, PortName)
+ add_rpc_servant(AuthHeaderSupportService.new, SupportPortName)
+ add_rpc_headerhandler(ServerAuthHeaderHandler.new)
+ end
+
+ class ServerAuthHeaderHandler < SOAP::Header::SimpleHandler
+ Users = {
+ 'NaHi' => 'passwd',
+ 'HiNa' => 'wspass'
+ }
+
+ def initialize
+ super(MyHeaderName)
+ @db = PStore.new(SessionDB)
+ @db.transaction do
+ @db["root"] = {} unless @db.root?("root")
+ end
+ @userid = @sessionid = nil
+ end
+
+ def login(userid, passwd)
+ userid and passwd and Users[userid] == passwd
+ end
+
+ def auth(sessionid)
+ in_sessiondb do |root|
+ root[sessionid][0]
+ end
+ end
+
+ def create_session(userid)
+ in_sessiondb do |root|
+ while true
+ key = create_sessionkey
+ break unless root[key]
+ end
+ root[key] = [userid]
+ key
+ end
+ end
+
+ def destroy_session(sessionkey)
+ in_sessiondb do |root|
+ root.delete(sessionkey)
+ end
+ end
+
+ def on_simple_outbound
+ { "sessionid" => @sessionid }
+ end
+
+ def on_simple_inbound(my_header, mu)
+ succeeded = false
+ userid = my_header["userid"]
+ passwd = my_header["passwd"]
+ if login(userid, passwd)
+ succeeded = true
+ elsif sessionid = my_header["sessionid"]
+ if userid = auth(sessionid)
+ destroy_session(sessionid)
+ succeeded = true
+ end
+ end
+ raise RuntimeError.new("authentication failed") unless succeeded
+ @userid = userid
+ @sessionid = create_session(userid)
+ end
+
+ private
+
+ def create_sessionkey
+ Time.now.usec.to_s
+ end
+
+ def in_sessiondb
+ @db.transaction do
+ yield(@db["root"])
+ end
+ end
+ end
+end
+
+
+status = AuthHeaderPortServer.new('AuthHeaderPortServer', nil).start
diff --git a/ruby_1_8_6/test/soap/header/test_authheader.rb b/ruby_1_8_6/test/soap/header/test_authheader.rb
new file mode 100644
index 0000000000..47e1e76b82
--- /dev/null
+++ b/ruby_1_8_6/test/soap/header/test_authheader.rb
@@ -0,0 +1,240 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'soap/rpc/standaloneServer'
+require 'soap/header/simplehandler'
+
+
+module SOAP
+module Header
+
+
+class TestAuthHeader < Test::Unit::TestCase
+ Port = 17171
+ PortName = 'http://tempuri.org/authHeaderPort'
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+ DummyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "dummy")
+
+ class AuthHeaderPortServer < SOAP::RPC::StandaloneServer
+ class AuthHeaderService
+ def self.create
+ new
+ end
+
+ def deposit(amt)
+ "deposit #{amt} OK"
+ end
+
+ def withdrawal(amt)
+ "withdrawal #{amt} OK"
+ end
+ end
+
+ def initialize(*arg)
+ super
+ add_rpc_servant(AuthHeaderService.new, PortName)
+ ServerAuthHeaderHandler.init
+ add_request_headerhandler(ServerAuthHeaderHandler)
+ end
+
+ class ServerAuthHeaderHandler < SOAP::Header::SimpleHandler
+ class << self
+ def create
+ new
+ end
+
+ def init
+ @users = {
+ 'NaHi' => 'passwd',
+ 'HiNa' => 'wspass'
+ }
+ @sessions = {}
+ end
+
+ def login(userid, passwd)
+ userid and passwd and @users[userid] == passwd
+ end
+
+ def auth(sessionid)
+ @sessions[sessionid][0]
+ end
+
+ def create_session(userid)
+ while true
+ key = create_sessionkey
+ break unless @sessions[key]
+ end
+ @sessions[key] = [userid]
+ key
+ end
+
+ def destroy_session(sessionkey)
+ @sessions.delete(sessionkey)
+ end
+
+ def sessions
+ @sessions
+ end
+
+ private
+
+ def create_sessionkey
+ Time.now.usec.to_s
+ end
+ end
+
+ def initialize
+ super(MyHeaderName)
+ @userid = @sessionid = nil
+ end
+
+ def on_simple_outbound
+ { "sessionid" => @sessionid }
+ end
+
+ def on_simple_inbound(my_header, mu)
+ auth = false
+ userid = my_header["userid"]
+ passwd = my_header["passwd"]
+ if self.class.login(userid, passwd)
+ auth = true
+ elsif sessionid = my_header["sessionid"]
+ if userid = self.class.auth(sessionid)
+ self.class.destroy_session(sessionid)
+ auth = true
+ end
+ end
+ raise RuntimeError.new("authentication failed") unless auth
+ @userid = userid
+ @sessionid = self.class.create_session(userid)
+ end
+ end
+ end
+
+ class ClientAuthHeaderHandler < SOAP::Header::SimpleHandler
+ def initialize(userid, passwd, mustunderstand)
+ super(MyHeaderName)
+ @sessionid = nil
+ @userid = userid
+ @passwd = passwd
+ @mustunderstand = mustunderstand
+ end
+
+ def on_simple_outbound
+ if @sessionid
+ { "sessionid" => @sessionid }
+ else
+ { "userid" => @userid, "passwd" => @passwd }
+ end
+ end
+
+ def on_simple_inbound(my_header, mustunderstand)
+ @sessionid = my_header["sessionid"]
+ end
+
+ def sessionid
+ @sessionid
+ end
+ end
+
+ class DummyHeaderHandler < SOAP::Header::SimpleHandler
+ def initialize(mustunderstand)
+ super(DummyHeaderName)
+ @mustunderstand = mustunderstand
+ end
+
+ def on_simple_outbound
+ { XSD::QName.new("foo", "bar") => nil }
+ end
+
+ def on_simple_inbound(my_header, mustunderstand)
+ end
+ end
+
+ def setup
+ @endpoint = "http://localhost:#{Port}/"
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = AuthHeaderPortServer.new(self.class.name, nil, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ @server.start
+ }
+ end
+
+ def setup_client
+ @client = SOAP::RPC::Driver.new(@endpoint, PortName)
+ @client.wiredump_dev = STDERR if $DEBUG
+ @client.add_method('deposit', 'amt')
+ @client.add_method('withdrawal', 'amt')
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def test_success_no_mu
+ h = ClientAuthHeaderHandler.new('NaHi', 'passwd', false)
+ @client.headerhandler << h
+ do_transaction_check(h)
+ end
+
+ def test_success_mu
+ h = ClientAuthHeaderHandler.new('NaHi', 'passwd', true)
+ @client.headerhandler << h
+ do_transaction_check(h)
+ end
+
+ def test_no_mu
+ h = ClientAuthHeaderHandler.new('NaHi', 'passwd', true)
+ @client.headerhandler << h
+ @client.headerhandler << DummyHeaderHandler.new(false)
+ do_transaction_check(h)
+ end
+
+ def test_mu
+ h = ClientAuthHeaderHandler.new('NaHi', 'passwd', true)
+ @client.headerhandler << h
+ @client.headerhandler << (h2 = DummyHeaderHandler.new(true))
+ assert_raise(SOAP::UnhandledMustUnderstandHeaderError) do
+ assert_equal("deposit 150 OK", @client.deposit(150))
+ end
+ @client.headerhandler.delete(h2)
+ @client.headerhandler << (h2 = DummyHeaderHandler.new(false))
+ do_transaction_check(h)
+ end
+
+ def do_transaction_check(h)
+ assert_equal("deposit 150 OK", @client.deposit(150))
+ serversess = AuthHeaderPortServer::ServerAuthHeaderHandler.sessions[h.sessionid]
+ assert_equal("NaHi", serversess[0])
+ assert_equal("withdrawal 120 OK", @client.withdrawal(120))
+ serversess = AuthHeaderPortServer::ServerAuthHeaderHandler.sessions[h.sessionid]
+ assert_equal("NaHi", serversess[0])
+ end
+
+ def test_authfailure
+ h = ClientAuthHeaderHandler.new('NaHi', 'pa', false)
+ @client.headerhandler << h
+ assert_raises(RuntimeError) do
+ @client.deposit(150)
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/header/test_authheader_cgi.rb b/ruby_1_8_6/test/soap/header/test_authheader_cgi.rb
new file mode 100644
index 0000000000..d70b022ad8
--- /dev/null
+++ b/ruby_1_8_6/test/soap/header/test_authheader_cgi.rb
@@ -0,0 +1,121 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'soap/rpc/standaloneServer'
+require 'soap/header/simplehandler'
+require 'logger'
+require 'webrick'
+require 'rbconfig'
+
+
+module SOAP
+module Header
+
+
+class TestAuthHeaderCGI < Test::Unit::TestCase
+ # This test shuld be run after installing ruby.
+ RUBYBIN = File.join(
+ Config::CONFIG["bindir"],
+ Config::CONFIG["ruby_install_name"] + Config::CONFIG["EXEEXT"]
+ )
+ RUBYBIN << " -d" if $DEBUG
+
+ Port = 17171
+ PortName = 'http://tempuri.org/authHeaderPort'
+ SupportPortName = 'http://tempuri.org/authHeaderSupportPort'
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+
+ class ClientAuthHeaderHandler < SOAP::Header::SimpleHandler
+ def initialize(userid, passwd)
+ super(MyHeaderName)
+ @sessionid = nil
+ @userid = userid
+ @passwd = passwd
+ end
+
+ def on_simple_outbound
+ if @sessionid
+ { "sessionid" => @sessionid }
+ else
+ { "userid" => @userid, "passwd" => @passwd }
+ end
+ end
+
+ def on_simple_inbound(my_header, mustunderstand)
+ @sessionid = my_header["sessionid"]
+ end
+
+ def sessionid
+ @sessionid
+ end
+ end
+
+ def setup
+ @endpoint = "http://localhost:#{Port}/"
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @endpoint = "http://localhost:#{Port}/server.cgi"
+ logger = Logger.new(STDERR)
+ logger.level = Logger::Severity::ERROR
+ @server = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Logger => logger,
+ :Port => Port,
+ :AccessLog => [],
+ :DocumentRoot => File.dirname(File.expand_path(__FILE__)),
+ :CGIPathEnv => ENV['PATH'],
+ :CGIInterpreter => RUBYBIN
+ )
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ end
+
+ def setup_client
+ @client = SOAP::RPC::Driver.new(@endpoint, PortName)
+ @client.wiredump_dev = STDERR if $DEBUG
+ @client.add_method('deposit', 'amt')
+ @client.add_method('withdrawal', 'amt')
+ @supportclient = SOAP::RPC::Driver.new(@endpoint, SupportPortName)
+ @supportclient.add_method('delete_sessiondb')
+ end
+
+ def teardown
+ @supportclient.delete_sessiondb
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ @supportclient.reset_stream
+ end
+
+ def test_success
+ h = ClientAuthHeaderHandler.new('NaHi', 'passwd')
+ @client.headerhandler << h
+ assert_equal("deposit 150 OK", @client.deposit(150))
+ assert_equal("withdrawal 120 OK", @client.withdrawal(120))
+ end
+
+ def test_authfailure
+ h = ClientAuthHeaderHandler.new('NaHi', 'pa')
+ @client.headerhandler << h
+ assert_raises(RuntimeError) do
+ @client.deposit(150)
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/header/test_simplehandler.rb b/ruby_1_8_6/test/soap/header/test_simplehandler.rb
new file mode 100644
index 0000000000..75dbd4a550
--- /dev/null
+++ b/ruby_1_8_6/test/soap/header/test_simplehandler.rb
@@ -0,0 +1,116 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'soap/rpc/standaloneServer'
+require 'soap/header/simplehandler'
+
+
+module SOAP
+module Header
+
+
+class TestSimpleHandler < Test::Unit::TestCase
+ Port = 17171
+ PortName = 'http://tempuri.org/authHeaderPort'
+
+ class PingPortServer < SOAP::RPC::StandaloneServer
+ class PingService
+ def self.create
+ new
+ end
+
+ def ping
+ Thread.current[:pingheader]
+ end
+ end
+
+ def initialize(*arg)
+ super
+ add_rpc_servant(PingService.new, PortName)
+ add_request_headerhandler(PingServerHeaderHandler)
+ end
+
+ class PingServerHeaderHandler < SOAP::Header::SimpleHandler
+ MyHeaderName = XSD::QName.new("http://xmlsoap.org/Ping", "PingHeader")
+
+ def self.create
+ new
+ end
+
+ def initialize()
+ super(MyHeaderName)
+ end
+
+ def on_simple_outbound
+ "dummy"
+ end
+
+ def on_simple_inbound(my_header, mu)
+ Thread.current[:pingheader] = my_header
+ end
+ end
+ end
+
+ class PingClientHeaderHandler < SOAP::Header::SimpleHandler
+ MyHeaderName = XSD::QName.new("http://xmlsoap.org/Ping", "PingHeader")
+
+ def initialize(pingHeader)
+ super(MyHeaderName)
+ @pingHeader = pingHeader
+ @mustunderstand = false
+ end
+
+ def on_simple_outbound
+ @pingHeader # --- note, not a Hash
+ end
+
+ def on_simple_inbound(my_header, mustunderstand)
+ Thread.current[:pingheader] = my_header
+ end
+ end
+
+ def setup
+ @endpoint = "http://localhost:#{Port}/"
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = PingPortServer.new(self.class.name, nil, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ @server.start
+ }
+ end
+
+ def setup_client
+ @client = SOAP::RPC::Driver.new(@endpoint, PortName)
+ @client.wiredump_dev = STDERR if $DEBUG
+ @client.add_method('ping')
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def test_string
+ h = PingClientHeaderHandler.new('pingheader')
+ @client.headerhandler << h
+ assert_equal("pingheader", @client.ping)
+ assert_equal("dummy", Thread.current[:pingheader])
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/helloworld/hw_s.rb b/ruby_1_8_6/test/soap/helloworld/hw_s.rb
new file mode 100644
index 0000000000..1a54adb924
--- /dev/null
+++ b/ruby_1_8_6/test/soap/helloworld/hw_s.rb
@@ -0,0 +1,16 @@
+require 'soap/rpc/standaloneServer'
+
+class HelloWorldServer < SOAP::RPC::StandaloneServer
+ def on_init
+ add_method(self, 'hello_world', 'from')
+ end
+
+ def hello_world(from)
+ "Hello World, from #{ from }"
+ end
+end
+
+if $0 == __FILE__
+ server = HelloWorldServer.new('hws', 'urn:hws', '0.0.0.0', 17171)
+ server.start
+end
diff --git a/ruby_1_8_6/test/soap/helloworld/test_helloworld.rb b/ruby_1_8_6/test/soap/helloworld/test_helloworld.rb
new file mode 100644
index 0000000000..40c35b57fb
--- /dev/null
+++ b/ruby_1_8_6/test/soap/helloworld/test_helloworld.rb
@@ -0,0 +1,40 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'hw_s.rb'
+
+
+module SOAP
+module HelloWorld
+
+
+class TestHelloWorld < Test::Unit::TestCase
+ Port = 17171
+
+ def setup
+ @server = HelloWorldServer.new('hws', 'urn:hws', '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/"
+ @client = SOAP::RPC::Driver.new(@endpoint, 'urn:hws')
+ @client.add_method("hello_world", "from")
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @client.reset_stream
+ end
+
+ def test_hello_world
+ assert_equal("Hello World, from NaHi", @client.hello_world("NaHi"))
+ assert_equal("Hello World, from <&>", @client.hello_world("<&>"))
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/marshal/test_digraph.rb b/ruby_1_8_6/test/soap/marshal/test_digraph.rb
new file mode 100644
index 0000000000..d7f30654f8
--- /dev/null
+++ b/ruby_1_8_6/test/soap/marshal/test_digraph.rb
@@ -0,0 +1,56 @@
+require 'test/unit'
+require 'soap/marshal'
+
+
+module SOAP
+module Marshal
+
+
+class Node; include SOAP::Marshallable
+ attr_reader :first, :second, :str
+
+ def initialize(*init_next)
+ @first = init_next[0]
+ @second = init_next[1]
+ end
+end
+
+class TestDigraph < Test::Unit::TestCase
+ def setup
+ @n9 = Node.new
+ @n81 = Node.new(@n9)
+ @n82 = Node.new(@n9)
+ @n7 = Node.new(@n81, @n82)
+ @n61 = Node.new(@n7)
+ @n62 = Node.new(@n7)
+ @n5 = Node.new(@n61, @n62)
+ @n41 = Node.new(@n5)
+ @n42 = Node.new(@n5)
+ @n3 = Node.new(@n41, @n42)
+ @n21 = Node.new(@n3)
+ @n22 = Node.new(@n3)
+ @n1 = Node.new(@n21, @n22)
+ end
+
+ def test_marshal
+ f = File.open("digraph_marshalled_string.soap", "wb")
+ SOAP::Marshal.dump(@n1, f)
+ f.close
+ f = File.open("digraph_marshalled_string.soap")
+ str = f.read
+ f.close
+ newnode = SOAP::Marshal.unmarshal(str)
+ assert_equal(newnode.first.first.__id__, newnode.second.first.__id__)
+ assert_equal(newnode.first.first.first.first.__id__, newnode.second.first.second.first.__id__)
+ end
+
+ def teardown
+ if File.exist?("digraph_marshalled_string.soap")
+ File.unlink("digraph_marshalled_string.soap")
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/marshal/test_marshal.rb b/ruby_1_8_6/test/soap/marshal/test_marshal.rb
new file mode 100644
index 0000000000..5cc30a2b5d
--- /dev/null
+++ b/ruby_1_8_6/test/soap/marshal/test_marshal.rb
@@ -0,0 +1,26 @@
+require 'test/unit'
+require 'soap/marshal'
+dir = File.join(File.dirname(File.expand_path(__FILE__)), '../../ruby')
+orgpath = $:.dup
+begin
+ $:.push(dir)
+ require 'marshaltestlib'
+ensure
+ $:.replace(orgpath)
+end
+
+module SOAP
+module Marshal
+class TestMarshal < Test::Unit::TestCase
+ include MarshalTestLib
+
+ def encode(o)
+ SOAPMarshal.dump(o)
+ end
+
+ def decode(s)
+ SOAPMarshal.load(s)
+ end
+end
+end
+end
diff --git a/ruby_1_8_6/test/soap/marshal/test_struct.rb b/ruby_1_8_6/test/soap/marshal/test_struct.rb
new file mode 100644
index 0000000000..33975c31b0
--- /dev/null
+++ b/ruby_1_8_6/test/soap/marshal/test_struct.rb
@@ -0,0 +1,47 @@
+require 'test/unit'
+require 'soap/marshal'
+
+
+module SOAP
+module Marshal
+
+
+Foo1 = ::Struct.new("Foo1", :m)
+Foo2 = ::Struct.new(:m)
+class Foo3
+ attr_accessor :m
+end
+
+class TestStruct < Test::Unit::TestCase
+ def test_foo1
+ org = Foo1.new
+ org.m = org
+ obj = convert(org)
+ assert_equal(Foo1, obj.class)
+ assert_equal(obj.m, obj)
+ end
+
+ def test_foo2
+ org = Foo2.new
+ org.m = org
+ obj = convert(org)
+ assert_equal(Foo2, obj.class)
+ assert_equal(obj.m, obj)
+ end
+
+ def test_foo3
+ org = Foo3.new
+ org.m = org
+ obj = convert(org)
+ assert_equal(Foo3, obj.class)
+ assert_equal(obj.m, obj)
+ end
+
+ def convert(obj)
+ SOAP::Marshal.unmarshal(SOAP::Marshal.marshal(obj))
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/ssl/README b/ruby_1_8_6/test/soap/ssl/README
new file mode 100644
index 0000000000..98ebcf7c23
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/README
@@ -0,0 +1 @@
+* certificates and keys in this directory is copied from http-access2 test.
diff --git a/ruby_1_8_6/test/soap/ssl/ca.cert b/ruby_1_8_6/test/soap/ssl/ca.cert
new file mode 100644
index 0000000000..bcabbee4ad
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/ca.cert
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIID0DCCArigAwIBAgIBADANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBMB4X
+DTA0MDEzMDAwNDIzMloXDTM2MDEyMjAwNDIzMlowPDELMAkGA1UEBgwCSlAxEjAQ
+BgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMQswCQYDVQQDDAJDQTCCASIw
+DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANbv0x42BTKFEQOE+KJ2XmiSdZpR
+wjzQLAkPLRnLB98tlzs4xo+y4RyY/rd5TT9UzBJTIhP8CJi5GbS1oXEerQXB3P0d
+L5oSSMwGGyuIzgZe5+vZ1kgzQxMEKMMKlzA73rbMd4Jx3u5+jdbP0EDrPYfXSvLY
+bS04n2aX7zrN3x5KdDrNBfwBio2/qeaaj4+9OxnwRvYP3WOvqdW0h329eMfHw0pi
+JI0drIVdsEqClUV4pebT/F+CPUPkEh/weySgo9wANockkYu5ujw2GbLFcO5LXxxm
+dEfcVr3r6t6zOA4bJwL0W/e6LBcrwiG/qPDFErhwtgTLYf6Er67SzLyA66UCAwEA
+AaOB3DCB2TAPBgNVHRMBAf8EBTADAQH/MDEGCWCGSAGG+EIBDQQkFiJSdWJ5L09w
+ZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRJ7Xd380KzBV7f
+USKIQ+O/vKbhDzAOBgNVHQ8BAf8EBAMCAQYwZAYDVR0jBF0wW4AUSe13d/NCswVe
+31EiiEPjv7ym4Q+hQKQ+MDwxCzAJBgNVBAYMAkpQMRIwEAYDVQQKDAlKSU4uR1Iu
+SlAxDDAKBgNVBAsMA1JSUjELMAkGA1UEAwwCQ0GCAQAwDQYJKoZIhvcNAQEFBQAD
+ggEBAIu/mfiez5XN5tn2jScgShPgHEFJBR0BTJBZF6xCk0jyqNx/g9HMj2ELCuK+
+r/Y7KFW5c5M3AQ+xWW0ZSc4kvzyTcV7yTVIwj2jZ9ddYMN3nupZFgBK1GB4Y05GY
+MJJFRkSu6d/Ph5ypzBVw2YMT/nsOo5VwMUGLgS7YVjU+u/HNWz80J3oO17mNZllj
+PvORJcnjwlroDnS58KoJ7GDgejv3ESWADvX1OHLE4cRkiQGeLoEU4pxdCxXRqX0U
+PbwIkZN9mXVcrmPHq8MWi4eC/V7hnbZETMHuWhUoiNdOEfsAXr3iP4KjyyRdwc7a
+d/xgcK06UVQRL/HbEYGiQL056mc=
+-----END CERTIFICATE-----
diff --git a/ruby_1_8_6/test/soap/ssl/client.cert b/ruby_1_8_6/test/soap/ssl/client.cert
new file mode 100644
index 0000000000..ad13c4b735
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/client.cert
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDKDCCAhCgAwIBAgIBAjANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBMB4X
+DTA0MDEzMTAzMTQ1OFoXDTM1MDEyMzAzMTQ1OFowZTELMAkGA1UEBgwCSlAxEjAQ
+BgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMRAwDgYDVQQDDAdleGFtcGxl
+MSIwIAYJKoZIhvcNAQkBDBNleGFtcGxlQGV4YW1wbGUub3JnMIGfMA0GCSqGSIb3
+DQEBAQUAA4GNADCBiQKBgQDRWssrK8Gyr+500hpLjCGR3+AHL8/hEJM5zKi/MgLW
+jTkvsgOwbYwXOiNtAbR9y4/ucDq7EY+cMUMHES4uFaPTcOaAV0aZRmk8AgslN1tQ
+gNS6ew7/Luq3DcVeWkX8PYgR9VG0mD1MPfJ6+IFA5d3vKpdBkBgN4l46jjO0/2Xf
+ewIDAQABo4GPMIGMMAwGA1UdEwEB/wQCMAAwMQYJYIZIAYb4QgENBCQWIlJ1Ynkv
+T3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFOFvay0H7lr2
+xUx6waYEV2bVDYQhMAsGA1UdDwQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYI
+KwYBBQUHAwQwDQYJKoZIhvcNAQEFBQADggEBABd2dYWqbDIWf5sWFvslezxJv8gI
+w64KCJBuyJAiDuf+oazr3016kMzAlt97KecLZDusGNagPrq02UX7YMoQFsWJBans
+cDtHrkM0al5r6/WGexNMgtYbNTYzt/IwodISGBgZ6dsOuhznwms+IBsTNDAvWeLP
+lt2tOqD8kEmjwMgn0GDRuKjs4EoboA3kMULb1p9akDV9ZESU3eOtpS5/G5J5msLI
+9WXbYBjcjvkLuJH9VsJhb+R58Vl0ViemvAHhPilSl1SPWVunGhv6FcIkdBEi1k9F
+e8BNMmsEjFiANiIRvpdLRbiGBt0KrKTndVfsmoKCvY48oCOvnzxtahFxfs8=
+-----END CERTIFICATE-----
diff --git a/ruby_1_8_6/test/soap/ssl/client.key b/ruby_1_8_6/test/soap/ssl/client.key
new file mode 100644
index 0000000000..37bc62f259
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/client.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQDRWssrK8Gyr+500hpLjCGR3+AHL8/hEJM5zKi/MgLWjTkvsgOw
+bYwXOiNtAbR9y4/ucDq7EY+cMUMHES4uFaPTcOaAV0aZRmk8AgslN1tQgNS6ew7/
+Luq3DcVeWkX8PYgR9VG0mD1MPfJ6+IFA5d3vKpdBkBgN4l46jjO0/2XfewIDAQAB
+AoGAZcz8llWErtsV3QB9gNb3S/PNADGjqBFjReva8n3jG2k4sZSibpwWTwUaTNtT
+ZQgjSRKRvH1hk9XwffNAvXAQZNNkuj/16gO2oO45nyLj4dO365ujLptWnVIWDHOE
+uN0GeiZO+VzcCisT0WCq4tvtLeH8svrxzA8cbXIEyOK7NiECQQDwo2zPFyKAZ/Cu
+lDJ6zKT+RjfWwW7DgWzirAlTrt4ViMaW+IaDH29TmQpb4V4NuR3Xi+2Xl4oicu6S
+36TW9+/FAkEA3rgfOQJuLlWSnw1RTGwvnC816a/W7iYYY7B+0U4cDbfWl7IoXT4y
+M8nV/HESooviZLqBwzAYSoj3fFKYBKpGPwJAUO8GN5iWWA2dW3ooiDiv/X1sZmRk
+dojfMFWgRW747tEzya8Ivq0h6kH8w+5GjeMG8Gn1nRiwsulo6Ckj7dEx6QJACyui
+7UIQ8qP6GZ4aYMHgVW4Mvy7Bkeo5OO7GPYs0Xv/EdJFL8vlGnVBXOjUVoS9w6Gpu
+TbLg1QQvnX2rADjmEwJANxZO2GUkaWGsEif8aGW0x5g/IdaMGG27pTWk5zqix7P3
+1UDrdo/JOXhptovhRi06EppIxAxYmbh9vd9VN8Itlw==
+-----END RSA PRIVATE KEY-----
diff --git a/ruby_1_8_6/test/soap/ssl/server.cert b/ruby_1_8_6/test/soap/ssl/server.cert
new file mode 100644
index 0000000000..998ccc5892
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/server.cert
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIC/zCCAeegAwIBAgIBATANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxDjAMBgNVBAMMBVN1YkNB
+MB4XDTA0MDEzMTAzMTMxNloXDTMzMDEyMzAzMTMxNlowQzELMAkGA1UEBgwCSlAx
+EjAQBgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMRIwEAYDVQQDDAlsb2Nh
+bGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANFJTxWqup3nV9dsJAku
+p+WaXnPNIzcpAA3qMGZDJTJsfa8Du7ZxTP0XJK5mETttBrn711cJxAuP3KjqnW9S
+vtZ9lY2sXJ6Zj62sN5LwG3VVe25dI28yR1EsbHjJ5Zjf9tmggMC6am52dxuHbt5/
+vHo4ngJuKE/U+eeGRivMn6gFAgMBAAGjgYUwgYIwDAYDVR0TAQH/BAIwADAxBglg
+hkgBhvhCAQ0EJBYiUnVieS9PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAd
+BgNVHQ4EFgQUpZIyygD9JxFYHHOTEuWOLbCKfckwCwYDVR0PBAQDAgWgMBMGA1Ud
+JQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4IBAQBwAIj5SaBHaA5X31IP
+CFCJiep96awfp7RANO0cuUj+ZpGoFn9d6FXY0g+Eg5wAkCNIzZU5NHN9xsdOpnUo
+zIBbyTfQEPrge1CMWMvL6uGaoEXytq84VTitF/xBTky4KtTn6+es4/e7jrrzeUXQ
+RC46gkHObmDT91RkOEGjHLyld2328jo3DIN/VTHIryDeVHDWjY5dENwpwdkhhm60
+DR9IrNBbXWEe9emtguNXeN0iu1ux0lG1Hc6pWGQxMlRKNvGh0yZB9u5EVe38tOV0
+jQaoNyL7qzcQoXD3Dmbi1p0iRmg/+HngISsz8K7k7MBNVsSclztwgCzTZOBiVtkM
+rRlQ
+-----END CERTIFICATE-----
diff --git a/ruby_1_8_6/test/soap/ssl/server.key b/ruby_1_8_6/test/soap/ssl/server.key
new file mode 100644
index 0000000000..9ba2218a03
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/server.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQDRSU8Vqrqd51fXbCQJLqflml5zzSM3KQAN6jBmQyUybH2vA7u2
+cUz9FySuZhE7bQa5+9dXCcQLj9yo6p1vUr7WfZWNrFyemY+trDeS8Bt1VXtuXSNv
+MkdRLGx4yeWY3/bZoIDAumpudncbh27ef7x6OJ4CbihP1PnnhkYrzJ+oBQIDAQAB
+AoGBAIf4CstW2ltQO7+XYGoex7Hh8s9lTSW/G2vu5Hbr1LTHy3fzAvdq8MvVR12O
+rk9fa+lU9vhzPc0NMB0GIDZ9GcHuhW5hD1Wg9OSCbTOkZDoH3CAFqonjh4Qfwv5W
+IPAFn9KHukdqGXkwEMdErsUaPTy9A1V/aROVEaAY+HJgq/eZAkEA/BP1QMV04WEZ
+Oynzz7/lLizJGGxp2AOvEVtqMoycA/Qk+zdKP8ufE0wbmCE3Qd6GoynavsHb6aGK
+gQobb8zDZwJBANSK6MrXlrZTtEaeZuyOB4mAmRzGzOUVkUyULUjEx2GDT93ujAma
+qm/2d3E+wXAkNSeRpjUmlQXy/2oSqnGvYbMCQQDRM+cYyEcGPUVpWpnj0shrF/QU
+9vSot/X1G775EMTyaw6+BtbyNxVgOIu2J+rqGbn3c+b85XqTXOPL0A2RLYkFAkAm
+syhSDtE9X55aoWsCNZY/vi+i4rvaFoQ/WleogVQAeGVpdo7/DK9t9YWoFBIqth0L
+mGSYFu9ZhvZkvQNV8eYrAkBJ+rOIaLDsmbrgkeDruH+B/9yrm4McDtQ/rgnOGYnH
+LjLpLLOrgUxqpzLWe++EwSLwK2//dHO+SPsQJ4xsyQJy
+-----END RSA PRIVATE KEY-----
diff --git a/ruby_1_8_6/test/soap/ssl/sslsvr.rb b/ruby_1_8_6/test/soap/ssl/sslsvr.rb
new file mode 100644
index 0000000000..4f67eb9485
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/sslsvr.rb
@@ -0,0 +1,57 @@
+require 'webrick/https'
+require 'logger'
+require 'rbconfig'
+
+require 'soap/rpc/httpserver'
+
+class HelloWorldServer < SOAP::RPC::HTTPServer
+private
+
+ def on_init
+ self.level = Logger::Severity::FATAL
+ @default_namespace = 'urn:ssltst'
+ add_method(self, 'hello_world', 'from')
+ end
+
+ def hello_world(from)
+ "Hello World, from #{ from }"
+ end
+end
+
+
+if $0 == __FILE__
+ PORT = 17171
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def cert(filename)
+ OpenSSL::X509::Certificate.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ def key(filename)
+ OpenSSL::PKey::RSA.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ $server = HelloWorldServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => PORT,
+ :AccessLog => [],
+ :SSLEnable => true,
+ :SSLCACertificateFile => File.join(DIR, 'ca.cert'),
+ :SSLCertificate => cert('server.cert'),
+ :SSLPrivateKey => key('server.key'),
+ :SSLVerifyClient => nil, #OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT|OpenSSL::SSL::VERIFY_PEER,
+ :SSLClientCA => cert('ca.cert'),
+ :SSLCertName => nil
+ )
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ $server.start
+ }
+ STDOUT.sync = true
+ puts $$
+ t.join
+end
diff --git a/ruby_1_8_6/test/soap/ssl/subca.cert b/ruby_1_8_6/test/soap/ssl/subca.cert
new file mode 100644
index 0000000000..1e471851b8
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/subca.cert
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDaDCCAlCgAwIBAgIBATANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBMB4X
+DTA0MDEzMDAwNDMyN1oXDTM1MDEyMjAwNDMyN1owPzELMAkGA1UEBgwCSlAxEjAQ
+BgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMQ4wDAYDVQQDDAVTdWJDQTCC
+ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ0Ou7AyRcRXnB/kVHv/6kwe
+ANzgg/DyJfsAUqW90m7Lu1nqyug8gK0RBd77yU0w5HOAMHTVSdpjZK0g2sgx4Mb1
+d/213eL9TTl5MRVEChTvQr8q5DVG/8fxPPE7fMI8eOAzd98/NOAChk+80r4Sx7fC
+kGVEE1bKwY1MrUsUNjOY2d6t3M4HHV3HX1V8ShuKfsHxgCmLzdI8U+5CnQedFgkm
+3e+8tr8IX5RR1wA1Ifw9VadF7OdI/bGMzog/Q8XCLf+WPFjnK7Gcx6JFtzF6Gi4x
+4dp1Xl45JYiVvi9zQ132wu8A1pDHhiNgQviyzbP+UjcB/tsOpzBQF8abYzgEkWEC
+AwEAAaNyMHAwDwYDVR0TAQH/BAUwAwEB/zAxBglghkgBhvhCAQ0EJBYiUnVieS9P
+cGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUlCjXWLsReYzH
+LzsxwVnCXmKoB/owCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQCJ/OyN
+rT8Cq2Y+G2yA/L1EMRvvxwFBqxavqaqHl/6rwsIBFlB3zbqGA/0oec6MAVnYynq4
+c4AcHTjx3bQ/S4r2sNTZq0DH4SYbQzIobx/YW8PjQUJt8KQdKMcwwi7arHP7A/Ha
+LKu8eIC2nsUBnP4NhkYSGhbmpJK+PFD0FVtD0ZIRlY/wsnaZNjWWcnWF1/FNuQ4H
+ySjIblqVQkPuzebv3Ror6ZnVDukn96Mg7kP4u6zgxOeqlJGRe1M949SS9Vudjl8X
+SF4aZUUB9pQGhsqQJVqaz2OlhGOp9D0q54xko/rekjAIcuDjl1mdX4F2WRrzpUmZ
+uY/bPeOBYiVsOYVe
+-----END CERTIFICATE-----
diff --git a/ruby_1_8_6/test/soap/ssl/test_ssl.rb b/ruby_1_8_6/test/soap/ssl/test_ssl.rb
new file mode 100644
index 0000000000..f0a1e18971
--- /dev/null
+++ b/ruby_1_8_6/test/soap/ssl/test_ssl.rb
@@ -0,0 +1,204 @@
+require 'test/unit'
+begin
+ require 'http-access2'
+rescue LoadError
+end
+require 'soap/rpc/driver'
+
+if defined?(HTTPAccess2) and defined?(OpenSSL)
+
+module SOAP; module SSL
+
+
+class TestSSL < Test::Unit::TestCase
+ PORT = 17171
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+ require 'rbconfig'
+ RUBY = File.join(
+ Config::CONFIG["bindir"],
+ Config::CONFIG["ruby_install_name"] + Config::CONFIG["EXEEXT"]
+ )
+
+ def setup
+ @url = "https://localhost:#{PORT}/hello"
+ @serverpid = @client = nil
+ @verify_callback_called = false
+ setup_server
+ setup_client
+ end
+
+ def teardown
+ teardown_client
+ teardown_server
+ end
+
+ def test_options
+ cfg = @client.streamhandler.client.ssl_config
+ assert_nil(cfg.client_cert)
+ assert_nil(cfg.client_key)
+ assert_nil(cfg.client_ca)
+ assert_equal(OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT, cfg.verify_mode)
+ assert_nil(cfg.verify_callback)
+ assert_nil(cfg.timeout)
+ assert_equal(OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_SSLv2, cfg.options)
+ assert_equal("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH", cfg.ciphers)
+ assert_instance_of(OpenSSL::X509::Store, cfg.cert_store)
+ # dummy call to ensure sslsvr initialization finished.
+ assert_raise(OpenSSL::SSL::SSLError) do
+ @client.hello_world("ssl client")
+ end
+ end
+
+ def test_verification
+ cfg = @client.options
+ cfg["protocol.http.ssl_config.verify_callback"] = method(:verify_callback).to_proc
+ @verify_callback_called = false
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ #
+ cfg["protocol.http.ssl_config.client_cert"] = File.join(DIR, "client.cert")
+ cfg["protocol.http.ssl_config.client_key"] = File.join(DIR, "client.key")
+ @verify_callback_called = false
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ #
+ cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "ca.cert")
+ @verify_callback_called = false
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ #
+ cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "subca.cert")
+ @verify_callback_called = false
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ assert(@verify_callback_called)
+ #
+ cfg["protocol.http.ssl_config.verify_depth"] = "1"
+ @verify_callback_called = false
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ #
+ cfg["protocol.http.ssl_config.verify_depth"] = ""
+ cfg["protocol.http.ssl_config.cert_store"] = OpenSSL::X509::Store.new
+ cfg["protocol.http.ssl_config.verify_mode"] = OpenSSL::SSL::VERIFY_PEER.to_s
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ #
+ cfg["protocol.http.ssl_config.verify_mode"] = ""
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ end
+
+ def test_property
+ testpropertyname = File.join(DIR, 'soapclient.properties')
+ File.open(testpropertyname, "w") do |f|
+ f <<<<__EOP__
+protocol.http.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER
+# depth: 1 causes an error (intentional)
+protocol.http.ssl_config.verify_depth = 1
+protocol.http.ssl_config.client_cert = #{File.join(DIR, 'client.cert')}
+protocol.http.ssl_config.client_key = #{File.join(DIR, 'client.key')}
+protocol.http.ssl_config.ca_file = #{File.join(DIR, 'ca.cert')}
+protocol.http.ssl_config.ca_file = #{File.join(DIR, 'subca.cert')}
+protocol.http.ssl_config.ciphers = ALL
+__EOP__
+ end
+ begin
+ @client.loadproperty(testpropertyname)
+ @client.options["protocol.http.ssl_config.verify_callback"] = method(:verify_callback).to_proc
+ @verify_callback_called = false
+ # NG with String
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ # NG with Integer
+ @client.options["protocol.http.ssl_config.verify_depth"] = 0
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ # OK with empty
+ @client.options["protocol.http.ssl_config.verify_depth"] = ""
+ @verify_callback_called = false
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ assert(@verify_callback_called)
+ # OK with nil
+ @client.options["protocol.http.ssl_config.verify_depth"] = nil
+ @verify_callback_called = false
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ assert(@verify_callback_called)
+ # OK with String
+ @client.options["protocol.http.ssl_config.verify_depth"] = "3"
+ @verify_callback_called = false
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ assert(@verify_callback_called)
+ # OK with Integer
+ @client.options["protocol.http.ssl_config.verify_depth"] = 3
+ @verify_callback_called = false
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ assert(@verify_callback_called)
+ ensure
+ File.unlink(testpropertyname)
+ end
+ end
+
+ def test_ciphers
+ cfg = @client.options
+ cfg["protocol.http.ssl_config.client_cert"] = File.join(DIR, 'client.cert')
+ cfg["protocol.http.ssl_config.client_key"] = File.join(DIR, 'client.key')
+ cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "ca.cert")
+ cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "subca.cert")
+ #cfg.timeout = 123
+ cfg["protocol.http.ssl_config.ciphers"] = "!ALL"
+ #
+ ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
+ # depends on OpenSSL version. (?:0.9.8|0.9.7)
+ assert_match(/\A(?:SSL_CTX_set_cipher_list:: no cipher match|no ciphers available)\z/, ssle.message)
+ #
+ cfg["protocol.http.ssl_config.ciphers"] = "ALL"
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
+ end
+
+private
+
+ def q(str)
+ %Q["#{str}"]
+ end
+
+ def setup_server
+ svrcmd = "#{q(RUBY)} "
+ #svrcmd << "-d " if $DEBUG
+ svrcmd << File.join(DIR, "sslsvr.rb")
+ svrout = IO.popen(svrcmd)
+ @serverpid = Integer(svrout.gets.chomp)
+ end
+
+ def setup_client
+ @client = SOAP::RPC::Driver.new(@url, 'urn:ssltst')
+ @client.add_method("hello_world", "from")
+ end
+
+ def teardown_server
+ if @serverpid
+ Process.kill('KILL', @serverpid)
+ Process.waitpid(@serverpid)
+ end
+ end
+
+ def teardown_client
+ @client.reset_stream if @client
+ end
+
+ def verify_callback(ok, cert)
+ @verify_callback_called = true
+ p ["client", ok, cert] if $DEBUG
+ ok
+ end
+end
+
+
+end; end
+
+end
diff --git a/ruby_1_8_6/test/soap/struct/test_struct.rb b/ruby_1_8_6/test/soap/struct/test_struct.rb
new file mode 100644
index 0000000000..d92f4bc18a
--- /dev/null
+++ b/ruby_1_8_6/test/soap/struct/test_struct.rb
@@ -0,0 +1,77 @@
+require 'test/unit'
+require 'soap/rpc/httpserver'
+require 'soap/rpc/driver'
+
+
+module SOAP; module Struct
+
+
+class TestStruct < Test::Unit::TestCase
+ Namespace = "urn:example.com:simpletype-rpc"
+ class Server < ::SOAP::RPC::HTTPServer
+ @@test_struct = ::Struct.new(:one, :two)
+
+ def on_init
+ add_method(self, 'a_method')
+ end
+
+ def a_method
+ @@test_struct.new("string", 1)
+ end
+ end
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new(
+ :Port => Port,
+ :BindAddress => "0.0.0.0",
+ :AccessLog => [],
+ :SOAPDefaultNamespace => Namespace
+ )
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/", Namespace)
+ @client.wiredump_dev = STDERR if $DEBUG
+ @client.add_method('a_method')
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_struct
+ assert_equal("string", @client.a_method.one)
+ assert_equal(1, @client.a_method.two)
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/soap/swa/test_file.rb b/ruby_1_8_6/test/soap/swa/test_file.rb
new file mode 100644
index 0000000000..1ec7aa92a7
--- /dev/null
+++ b/ruby_1_8_6/test/soap/swa/test_file.rb
@@ -0,0 +1,73 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'soap/rpc/standaloneServer'
+require 'soap/attachment'
+
+
+module SOAP
+module SWA
+
+
+class TestFile < Test::Unit::TestCase
+ Port = 17171
+ THIS_FILE = File.expand_path(__FILE__)
+
+ class SwAService
+ def get_file
+ return {
+ 'name' => $0,
+ 'file' => SOAP::Attachment.new(File.open(THIS_FILE)) # closed when GCed.
+ }
+ end
+
+ def put_file(name, file)
+ "File '#{name}' was received ok."
+ end
+ end
+
+ def setup
+ @server = SOAP::RPC::StandaloneServer.new('SwAServer',
+ 'http://www.acmetron.com/soap', '0.0.0.0', Port)
+ @server.add_servant(SwAService.new)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/"
+ @client = SOAP::RPC::Driver.new(@endpoint, 'http://www.acmetron.com/soap')
+ @client.add_method('get_file')
+ @client.add_method('put_file', 'name', 'file')
+ @client.wiredump_dev = STDERR if $DEBUG
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @client.reset_stream
+ end
+
+ def test_get_file
+ assert_equal(
+ File.open(THIS_FILE) { |f| f.read },
+ @client.get_file['file'].content
+ )
+ end
+
+ def test_put_file
+ assert_equal(
+ "File 'foo' was received ok.",
+ @client.put_file('foo',
+ SOAP::Attachment.new(File.open(THIS_FILE)))
+ )
+ assert_equal(
+ "File 'bar' was received ok.",
+ @client.put_file('bar',
+ SOAP::Attachment.new(File.open(THIS_FILE) { |f| f.read }))
+ )
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/soap/test_basetype.rb b/ruby_1_8_6/test/soap/test_basetype.rb
new file mode 100644
index 0000000000..3785873560
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_basetype.rb
@@ -0,0 +1,970 @@
+require 'test/unit'
+require 'soap/baseData'
+
+
+module SOAP
+
+
+class TestSOAP < Test::Unit::TestCase
+ NegativeZero = (-1.0 / (1.0 / 0.0))
+
+ def setup
+ # Nothing to do.
+ end
+
+ def teardown
+ # Nothing to do.
+ end
+
+ def assert_parsed_result(klass, str)
+ o = klass.new(str)
+ assert_equal(str, o.to_s)
+ end
+
+ def test_SOAPNil
+ o = SOAP::SOAPNil.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::NilLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ o = SOAP::SOAPNil.new(nil)
+ assert_equal(true, o.is_nil)
+ assert_equal(nil, o.data)
+ assert_equal("", o.to_s)
+ o = SOAP::SOAPNil.new('var')
+ assert_equal(false, o.is_nil)
+ assert_equal('var', o.data)
+ assert_equal('var', o.to_s)
+ end
+
+ def test_SOAPString
+ o = SOAP::SOAPString.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::StringLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ str = "abc"
+ assert_equal(str, SOAP::SOAPString.new(str).data)
+ assert_equal(str, SOAP::SOAPString.new(str).to_s)
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPString.new("\0")
+ end
+ assert_raises(XSD::ValueSpaceError) do
+ p SOAP::SOAPString.new("\xC0\xC0").to_s
+ end
+ end
+
+ def test_SOAPBoolean
+ o = SOAP::SOAPBoolean.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::BooleanLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ ["true", true],
+ ["1", true],
+ ["false", false],
+ ["0", false],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPBoolean.new(data).data)
+ assert_equal(expected.to_s, SOAP::SOAPBoolean.new(data).to_s)
+ end
+
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPBoolean.new("nil").to_s
+ end
+ end
+
+ def test_SOAPDecimal
+ o = SOAP::SOAPDecimal.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DecimalLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ -9999999999,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ -1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789,
+ ]
+ targets.each do |dec|
+ assert_equal(dec.to_s, SOAP::SOAPDecimal.new(dec).data)
+ end
+
+ targets = [
+ "0",
+ "0.00000001",
+ "1000000000",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123.45678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
+ ]
+ targets.each do |str|
+ assert_equal(str, SOAP::SOAPDecimal.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["0.0", "0"],
+ ["-0.0", "0"],
+ ["+0.0", "0"],
+ ["0.", "0"],
+ [".0", "0"],
+ [
+ "+0.12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "0.1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
+ ],
+ [
+ ".0000012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "0.000001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
+ ],
+ [
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.",
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
+ ],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPDecimal.new(data).to_s)
+ end
+
+ targets = [
+ "0.000000000000a",
+ "00a.0000000000001",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPDecimal.new(d)
+ end
+ end
+ end
+
+ def test_SOAPFloat
+ o = SOAP::SOAPFloat.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::FloatLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 3.14159265358979,
+ 12.34e36,
+ 1.402e-45,
+ -1.402e-45,
+ ]
+ targets.each do |f|
+ assert_equal(f, SOAP::SOAPFloat.new(f).data)
+ end
+
+ targets = [
+ "+3.141592654",
+ "+1.234e+37",
+ "+1.402e-45",
+ "-1.402e-45",
+ ]
+ targets.each do |f|
+ assert_equal(f, SOAP::SOAPFloat.new(f).to_s)
+ end
+
+ targets = [
+ [3, "+3"], # should be 3.0?
+ [-2, "-2"], # ditto
+ [3.14159265358979, "+3.141592654"],
+ [12.34e36, "+1.234e+37"],
+ [1.402e-45, "+1.402e-45"],
+ [-1.402e-45, "-1.402e-45"],
+ ["1.402e", "+1.402"],
+ ["12.34E36", "+1.234e+37"],
+ ["1.402E-45", "+1.402e-45"],
+ ["-1.402E-45", "-1.402e-45"],
+ ["1.402E", "+1.402"],
+ ]
+ targets.each do |f, str|
+ assert_equal(str, SOAP::SOAPFloat.new(f).to_s)
+ end
+
+ assert_equal("+0", SOAP::SOAPFloat.new(+0.0).to_s)
+ assert_equal("-0", SOAP::SOAPFloat.new(NegativeZero).to_s)
+ assert(SOAP::SOAPFloat.new(0.0/0.0).data.nan?)
+ assert_equal("INF", SOAP::SOAPFloat.new(1.0/0.0).to_s)
+ assert_equal(1, SOAP::SOAPFloat.new(1.0/0.0).data.infinite?)
+ assert_equal("-INF", SOAP::SOAPFloat.new(-1.0/0.0).to_s)
+ assert_equal(-1, SOAP::SOAPFloat.new(-1.0/0.0).data.infinite?)
+
+ targets = [
+ "0.000000000000a",
+ "00a.0000000000001",
+ "+-5",
+ "5_0",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPFloat.new(d)
+ end
+ end
+ end
+
+ def test_SOAPDouble
+ o = SOAP::SOAPDouble.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DoubleLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 3.14159265358979,
+ 12.34e36,
+ 1.402e-45,
+ -1.402e-45,
+ ]
+ targets.each do |f|
+ assert_equal(f, SOAP::SOAPDouble.new(f).data)
+ end
+
+ targets = [
+ "+3.14159265358979",
+ "+1.234e+37",
+ "+1.402e-45",
+ "-1.402e-45",
+ ]
+ targets.each do |f|
+ assert_equal(f, SOAP::SOAPDouble.new(f).to_s)
+ end
+
+ targets = [
+ [3, "+3"], # should be 3.0?
+ [-2, "-2"], # ditto.
+ [3.14159265358979, "+3.14159265358979"],
+ [12.34e36, "+1.234e+37"],
+ [1.402e-45, "+1.402e-45"],
+ [-1.402e-45, "-1.402e-45"],
+ ["1.402e", "+1.402"],
+ ["12.34E36", "+1.234e+37"],
+ ["1.402E-45", "+1.402e-45"],
+ ["-1.402E-45", "-1.402e-45"],
+ ["1.402E", "+1.402"],
+ ]
+ targets.each do |f, str|
+ assert_equal(str, SOAP::SOAPDouble.new(f).to_s)
+ end
+
+ assert_equal("+0", SOAP::SOAPFloat.new(+0.0).to_s)
+ assert_equal("-0", SOAP::SOAPFloat.new(NegativeZero).to_s)
+ assert_equal("NaN", SOAP::SOAPDouble.new(0.0/0.0).to_s)
+ assert(SOAP::SOAPDouble.new(0.0/0.0).data.nan?)
+ assert_equal("INF", SOAP::SOAPDouble.new(1.0/0.0).to_s)
+ assert_equal(1, SOAP::SOAPDouble.new(1.0/0.0).data.infinite?)
+ assert_equal("-INF", SOAP::SOAPDouble.new(-1.0/0.0).to_s)
+ assert_equal(-1, SOAP::SOAPDouble.new(-1.0/0.0).data.infinite?)
+
+ targets = [
+ "0.000000000000a",
+ "00a.0000000000001",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPDouble.new(d)
+ end
+ end
+ end
+
+ def test_SOAPDuration
+ o = SOAP::SOAPDuration.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DurationLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "P1Y2M3DT4H5M6S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S",
+ "P0DT3456H7890M1234.5678S",
+ "P1234Y5678M9012D",
+ "-P1234Y5678M9012DT3456H7890M1234.5678S",
+ "P5678M9012DT3456H7890M1234.5678S",
+ "-P1234Y9012DT3456H7890M1234.5678S",
+ "+P1234Y5678MT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT7890M1234.5678S",
+ "-P1234Y5678M9012DT3456H1234.5678S",
+ "+P1234Y5678M9012DT3456H7890M",
+ "P123400000000000Y",
+ "-P567800000000000M",
+ "+P901200000000000D",
+ "P0DT345600000000000H",
+ "-P0DT789000000000000M",
+ "+P0DT123400000000000.000000000005678S",
+ "P1234YT1234.5678S",
+ "-P5678MT7890M",
+ "+P9012DT3456H",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPDuration, str)
+ end
+
+ targets = [
+ ["P0Y0M0DT0H0M0S",
+ "P0D"],
+ ["-P0DT0S",
+ "-P0D"],
+ ["P01234Y5678M9012DT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y005678M9012DT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M0009012DT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M9012DT00003456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M9012DT3456H000007890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M9012DT3456H7890M0000001234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPDuration.new(data).to_s)
+ end
+ end
+
+ def test_SOAPDateTime
+ o = SOAP::SOAPDateTime.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DateTimeLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002-05-18T16:52:20Z",
+ "0001-01-01T00:00:00Z",
+ "9999-12-31T23:59:59Z",
+ "19999-12-31T23:59:59Z",
+ "2002-12-31T23:59:59.999Z",
+ "2002-12-31T23:59:59.001Z",
+ "2002-12-31T23:59:59.99999999999999999999Z",
+ "2002-12-31T23:59:59.00000000000000000001Z",
+ "2002-12-31T23:59:59+09:00",
+ "2002-12-31T23:59:59+00:01",
+ "2002-12-31T23:59:59-00:01",
+ "2002-12-31T23:59:59-23:59",
+ "2002-12-31T23:59:59.00000000000000000001+13:30",
+ "2002-12-31T23:59:59.51375Z",
+ "2002-12-31T23:59:59.51345+12:34",
+ "-2002-05-18T16:52:20Z",
+ "-4711-12-31T23:59:59Z",
+ "-4713-01-01T12:00:00Z",
+ "-19999-12-31T23:59:59Z",
+ "-2002-12-31T23:59:59+00:01",
+ "-0001-12-31T23:59:59.00000000000000000001+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPDateTime, str)
+ end
+
+ targets = [
+ ["2002-12-31T23:59:59.00",
+ "2002-12-31T23:59:59Z"],
+ ["2002-12-31T23:59:59+00:00",
+ "2002-12-31T23:59:59Z"],
+ ["2002-12-31T23:59:59-00:00",
+ "2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59.00",
+ "-2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59+00:00",
+ "-2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59-00:00",
+ "-2002-12-31T23:59:59Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPDateTime.new(data).to_s)
+ d = DateTime.parse(data)
+ d >>= 12 if d.year < 0 # XSDDateTime.year(-1) == DateTime.year(0)
+ assert_equal(expected, SOAP::SOAPDateTime.new(d).to_s)
+ end
+
+ targets = [
+ "1-05-18T16:52:20Z",
+ "05-18T16:52:20Z",
+ "2002-05T16:52:20Z",
+ "2002-05-18T16:52Z",
+ "",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError, d.to_s) do
+ SOAP::SOAPDateTime.new(d)
+ end
+ end
+ end
+
+ def test_SOAPTime
+ o = SOAP::SOAPTime.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::TimeLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "16:52:20Z",
+ "00:00:00Z",
+ "23:59:59Z",
+ "23:59:59.999Z",
+ "23:59:59.001Z",
+ "23:59:59.99999999999999999999Z",
+ "23:59:59.00000000000000000001Z",
+ "23:59:59+09:00",
+ "23:59:59+00:01",
+ "23:59:59-00:01",
+ "23:59:59-23:59",
+ "23:59:59.00000000000000000001+13:30",
+ "23:59:59.51375Z",
+ "23:59:59.51375+12:34",
+ "23:59:59+00:01",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPTime, str)
+ end
+
+ targets = [
+ ["23:59:59.00",
+ "23:59:59Z"],
+ ["23:59:59+00:00",
+ "23:59:59Z"],
+ ["23:59:59-00:00",
+ "23:59:59Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPTime.new(data).to_s)
+ end
+ end
+
+ def test_SOAPDate
+ o = SOAP::SOAPDate.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DateLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002-05-18Z",
+ "0001-01-01Z",
+ "9999-12-31Z",
+ "19999-12-31Z",
+ "2002-12-31+09:00",
+ "2002-12-31+00:01",
+ "2002-12-31-00:01",
+ "2002-12-31-23:59",
+ "2002-12-31+13:30",
+ "-2002-05-18Z",
+ "-19999-12-31Z",
+ "-2002-12-31+00:01",
+ "-0001-12-31+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPDate, str)
+ end
+
+ targets = [
+ ["2002-12-31",
+ "2002-12-31Z"],
+ ["2002-12-31+00:00",
+ "2002-12-31Z"],
+ ["2002-12-31-00:00",
+ "2002-12-31Z"],
+ ["-2002-12-31",
+ "-2002-12-31Z"],
+ ["-2002-12-31+00:00",
+ "-2002-12-31Z"],
+ ["-2002-12-31-00:00",
+ "-2002-12-31Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPDate.new(data).to_s)
+ d = Date.parse(data)
+ d >>= 12 if d.year < 0 # XSDDate.year(-1) == Date.year(0)
+ assert_equal(expected, SOAP::SOAPDate.new(d).to_s)
+ end
+ end
+
+ def test_SOAPGYearMonth
+ o = SOAP::SOAPGYearMonth.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GYearMonthLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002-05Z",
+ "0001-01Z",
+ "9999-12Z",
+ "19999-12Z",
+ "2002-12+09:00",
+ "2002-12+00:01",
+ "2002-12-00:01",
+ "2002-12-23:59",
+ "2002-12+13:30",
+ "-2002-05Z",
+ "-19999-12Z",
+ "-2002-12+00:01",
+ "-0001-12+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPGYearMonth, str)
+ end
+
+ targets = [
+ ["2002-12",
+ "2002-12Z"],
+ ["2002-12+00:00",
+ "2002-12Z"],
+ ["2002-12-00:00",
+ "2002-12Z"],
+ ["-2002-12",
+ "-2002-12Z"],
+ ["-2002-12+00:00",
+ "-2002-12Z"],
+ ["-2002-12-00:00",
+ "-2002-12Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPGYearMonth.new(data).to_s)
+ end
+ end
+
+ def test_SOAPGYear
+ o = SOAP::SOAPGYear.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GYearLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002Z",
+ "0001Z",
+ "9999Z",
+ "19999Z",
+ "2002+09:00",
+ "2002+00:01",
+ "2002-00:01",
+ "2002-23:59",
+ "2002+13:30",
+ "-2002Z",
+ "-19999Z",
+ "-2002+00:01",
+ "-0001+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPGYear, str)
+ end
+
+ targets = [
+ ["2002",
+ "2002Z"],
+ ["2002+00:00",
+ "2002Z"],
+ ["2002-00:00",
+ "2002Z"],
+ ["-2002",
+ "-2002Z"],
+ ["-2002+00:00",
+ "-2002Z"],
+ ["-2002-00:00",
+ "-2002Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPGYear.new(data).to_s)
+ end
+ end
+
+ def test_SOAPGMonthDay
+ o = SOAP::SOAPGMonthDay.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GMonthDayLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "05-18Z",
+ "01-01Z",
+ "12-31Z",
+ "12-31+09:00",
+ "12-31+00:01",
+ "12-31-00:01",
+ "12-31-23:59",
+ "12-31+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPGMonthDay, str)
+ end
+
+ targets = [
+ ["12-31",
+ "12-31Z"],
+ ["12-31+00:00",
+ "12-31Z"],
+ ["12-31-00:00",
+ "12-31Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPGMonthDay.new(data).to_s)
+ end
+ end
+
+ def test_SOAPGDay
+ o = SOAP::SOAPGDay.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GDayLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "18Z",
+ "01Z",
+ "31Z",
+ "31+09:00",
+ "31+00:01",
+ "31-00:01",
+ "31-23:59",
+ "31+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPGDay, str)
+ end
+
+ targets = [
+ ["31",
+ "31Z"],
+ ["31+00:00",
+ "31Z"],
+ ["31-00:00",
+ "31Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPGDay.new(data).to_s)
+ end
+ end
+
+ def test_SOAPGMonth
+ o = SOAP::SOAPGMonth.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GMonthLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "05Z",
+ "01Z",
+ "12Z",
+ "12+09:00",
+ "12+00:01",
+ "12-00:01",
+ "12-23:59",
+ "12+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPGMonth, str)
+ end
+
+ targets = [
+ ["12",
+ "12Z"],
+ ["12+00:00",
+ "12Z"],
+ ["12-00:00",
+ "12Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPGMonth.new(data).to_s)
+ end
+ end
+
+ def test_SOAPHexBinary
+ o = SOAP::SOAPHexBinary.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::HexBinaryLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "abcdef",
+ "\xe3\x81\xaa\xe3\x81\xb2",
+ "\0",
+ "",
+ ]
+ targets.each do |str|
+ assert_equal(str, SOAP::SOAPHexBinary.new(str).string)
+ assert_equal(str.unpack("H*")[0].tr('a-f', 'A-F'),
+ SOAP::SOAPHexBinary.new(str).data)
+ o = SOAP::SOAPHexBinary.new
+ o.set_encoded(str.unpack("H*")[0].tr('a-f', 'A-F'))
+ assert_equal(str, o.string)
+ o.set_encoded(str.unpack("H*")[0].tr('A-F', 'a-f'))
+ assert_equal(str, o.string)
+ end
+
+ targets = [
+ "0FG7",
+ "0fg7",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError, d.to_s) do
+ o = SOAP::SOAPHexBinary.new
+ o.set_encoded(d)
+ p o.string
+ end
+ end
+ end
+
+ def test_SOAPBase64Binary
+ o = SOAP::SOAPBase64.new
+ assert_equal(SOAP::EncodingNamespace, o.type.namespace)
+ assert_equal(SOAP::Base64Literal, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "abcdef",
+ "\xe3\x81\xaa\xe3\x81\xb2",
+ "\0",
+ "",
+ ]
+ targets.each do |str|
+ assert_equal(str, SOAP::SOAPBase64.new(str).string)
+ assert_equal([str].pack("m").chomp, SOAP::SOAPBase64.new(str).data)
+ o = SOAP::SOAPBase64.new
+ o.set_encoded([str].pack("m").chomp)
+ assert_equal(str, o.string)
+ end
+
+ targets = [
+ "-",
+ "*",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError, d.to_s) do
+ o = SOAP::SOAPBase64.new
+ o.set_encoded(d)
+ p o.string
+ end
+ end
+ end
+
+ def test_SOAPAnyURI
+ o = SOAP::SOAPAnyURI.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::AnyURILiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ # Too few tests here I know. Believe uri module. :)
+ targets = [
+ "foo",
+ "http://foo",
+ "http://foo/bar/baz",
+ "http://foo/bar#baz",
+ "http://foo/bar%20%20?a+b",
+ "HTTP://FOO/BAR%20%20?A+B",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPAnyURI, str)
+ end
+ end
+
+ def test_SOAPQName
+ o = SOAP::SOAPQName.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::QNameLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ # More strict test is needed but current implementation allows all non-':'
+ # chars like ' ', C0 or C1...
+ targets = [
+ "foo",
+ "foo:bar",
+ "a:b",
+ ]
+ targets.each do |str|
+ assert_parsed_result(SOAP::SOAPQName, str)
+ end
+ end
+
+
+ ###
+ ## Derived types
+ #
+
+ def test_SOAPInteger
+ o = SOAP::SOAPInteger.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::IntegerLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ -9999999999,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ -1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789,
+ ]
+ targets.each do |int|
+ assert_equal(int, SOAP::SOAPInteger.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "1000000000",
+ "-9999999999",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
+ ]
+ targets.each do |str|
+ assert_equal(str, SOAP::SOAPInteger.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ [
+ "+12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
+ ],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPInteger.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPInteger.new(d)
+ end
+ end
+ end
+
+ def test_SOAPLong
+ o = SOAP::SOAPLong.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::LongLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 123,
+ -123,
+ 9223372036854775807,
+ -9223372036854775808,
+ ]
+ targets.each do |lng|
+ assert_equal(lng, SOAP::SOAPLong.new(lng).data)
+ end
+
+ targets = [
+ "0",
+ "123",
+ "-123",
+ "9223372036854775807",
+ "-9223372036854775808",
+ ]
+ targets.each do |str|
+ assert_equal(str, SOAP::SOAPLong.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPLong.new(data).to_s)
+ end
+
+ targets = [
+ 9223372036854775808,
+ -9223372036854775809,
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPLong.new(d)
+ end
+ end
+ end
+
+ def test_SOAPInt
+ o = SOAP::SOAPInt.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::IntLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 123,
+ -123,
+ 2147483647,
+ -2147483648,
+ ]
+ targets.each do |lng|
+ assert_equal(lng, SOAP::SOAPInt.new(lng).data)
+ end
+
+ targets = [
+ "0",
+ "123",
+ "-123",
+ "2147483647",
+ "-2147483648",
+ ]
+ targets.each do |str|
+ assert_equal(str, SOAP::SOAPInt.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, SOAP::SOAPInt.new(data).to_s)
+ end
+
+ targets = [
+ 2147483648,
+ -2147483649,
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ SOAP::SOAPInt.new(d)
+ end
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/test_envelopenamespace.rb b/ruby_1_8_6/test/soap/test_envelopenamespace.rb
new file mode 100644
index 0000000000..5b7d281341
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_envelopenamespace.rb
@@ -0,0 +1,92 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'webrick'
+require 'logger'
+
+
+module SOAP
+
+
+class TestEnvelopeNamespace < Test::Unit::TestCase
+ Port = 17171
+ TemporaryNamespace = 'urn:foo'
+
+ def setup
+ @logger = Logger.new(STDERR)
+ @logger.level = Logger::Severity::ERROR
+ @url = "http://localhost:#{Port}/"
+ @server = @client = nil
+ @server_thread = nil
+ setup_server
+ setup_client
+ end
+
+ def teardown
+ teardown_client
+ teardown_server
+ end
+
+ def setup_server
+ @server = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Logger => @logger,
+ :Port => Port,
+ :AccessLog => [],
+ :DocumentRoot => File.dirname(File.expand_path(__FILE__))
+ )
+ @server.mount(
+ '/',
+ WEBrick::HTTPServlet::ProcHandler.new(method(:do_server_proc).to_proc)
+ )
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ @client = SOAP::RPC::Driver.new(@url, '')
+ @client.add_method("do_server_proc")
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def do_server_proc(req, res)
+ res['content-type'] = 'text/xml'
+ res.body = <<__EOX__
+<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:env="#{TemporaryNamespace}">
+ <env:Body>
+ <n1:do_server_proc xmlns:n1="urn:foo" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+ <return>hello world</return>
+ </n1:do_server_proc>
+ </env:Body>
+</env:Envelope>
+__EOX__
+ end
+
+ def test_normal
+ assert_raise(SOAP::ResponseFormatError) do
+ @client.do_server_proc
+ end
+ @client.options["soap.envelope.requestnamespace"] = TemporaryNamespace
+ @client.options["soap.envelope.responsenamespace"] = TemporaryNamespace
+ assert_equal('hello world', @client.do_server_proc)
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/test_httpconfigloader.rb b/ruby_1_8_6/test/soap/test_httpconfigloader.rb
new file mode 100644
index 0000000000..b06243f661
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_httpconfigloader.rb
@@ -0,0 +1,39 @@
+require 'test/unit'
+require 'soap/httpconfigloader'
+require 'soap/rpc/driver'
+
+if defined?(HTTPAccess2)
+
+module SOAP
+
+
+class TestHTTPConfigLoader < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def setup
+ @client = SOAP::RPC::Driver.new(nil, nil)
+ end
+
+ def test_property
+ testpropertyname = File.join(DIR, 'soapclient.properties')
+ File.open(testpropertyname, "w") do |f|
+ f <<<<__EOP__
+protocol.http.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER
+# depth: 1 causes an error (intentional)
+protocol.http.ssl_config.verify_depth = 1
+protocol.http.ssl_config.ciphers = ALL
+__EOP__
+ end
+ begin
+ @client.loadproperty(testpropertyname)
+ assert_equal('ALL', @client.options['protocol.http.ssl_config.ciphers'])
+ ensure
+ File.unlink(testpropertyname)
+ end
+ end
+end
+
+
+end
+
+end
diff --git a/ruby_1_8_6/test/soap/test_mapping.rb b/ruby_1_8_6/test/soap/test_mapping.rb
new file mode 100644
index 0000000000..26222e6719
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_mapping.rb
@@ -0,0 +1,59 @@
+require 'test/unit'
+require 'soap/mapping'
+
+
+module SOAP
+
+
+class TestMapping < Test::Unit::TestCase
+ def test_date
+ targets = [
+ ["2002-12-31",
+ "2002-12-31Z"],
+ ["2002-12-31+00:00",
+ "2002-12-31Z"],
+ ["2002-12-31-00:00",
+ "2002-12-31Z"],
+ ["-2002-12-31",
+ "-2002-12-31Z"],
+ ["-2002-12-31+00:00",
+ "-2002-12-31Z"],
+ ["-2002-12-31-00:00",
+ "-2002-12-31Z"],
+ ]
+ targets.each do |str, expectec|
+ d = Date.parse(str)
+ assert_equal(d.class, convert(d).class)
+ assert_equal(d, convert(d))
+ end
+ end
+
+ def test_datetime
+ targets = [
+ ["2002-12-31T23:59:59.00",
+ "2002-12-31T23:59:59Z"],
+ ["2002-12-31T23:59:59+00:00",
+ "2002-12-31T23:59:59Z"],
+ ["2002-12-31T23:59:59-00:00",
+ "2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59.00",
+ "-2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59+00:00",
+ "-2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59-00:00",
+ "-2002-12-31T23:59:59Z"],
+ ]
+ targets.each do |str, expectec|
+ d = DateTime.parse(str)
+ assert_equal(d.class, convert(d).class)
+ assert_equal(d, convert(d))
+ end
+ end
+
+ def convert(obj)
+ SOAP::Mapping.soap2obj(SOAP::Mapping.obj2soap(obj))
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/test_no_indent.rb b/ruby_1_8_6/test/soap/test_no_indent.rb
new file mode 100644
index 0000000000..f49fb7389f
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_no_indent.rb
@@ -0,0 +1,86 @@
+require 'test/unit'
+require 'soap/rpc/standaloneServer'
+require 'soap/rpc/driver'
+
+if defined?(HTTPAccess2)
+
+module SOAP
+
+
+class TestNoIndent < Test::Unit::TestCase
+ Port = 17171
+
+ class NopServer < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+ add_rpc_method(self, 'nop')
+ end
+
+ def nop
+ SOAP::RPC::SOAPVoid.new
+ end
+ end
+
+ def setup
+ @server = NopServer.new(self.class.name, nil, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ @server.start
+ }
+ @endpoint = "http://localhost:#{Port}/"
+ @client = SOAP::RPC::Driver.new(@endpoint)
+ @client.add_rpc_method('nop')
+ end
+
+ def teardown
+ @server.shutdown
+ @t.kill
+ @t.join
+ @client.reset_stream
+ end
+
+ INDENT_XML =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <nop env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+ </nop>
+ </env:Body>
+</env:Envelope>]
+
+ NO_INDENT_XML =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+<env:Body>
+<nop env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+</nop>
+</env:Body>
+</env:Envelope>]
+
+ def test_indent
+ @client.wiredump_dev = str = ''
+ @client.options["soap.envelope.no_indent"] = false
+ @client.nop
+ assert_equal(INDENT_XML, parse_requestxml(str))
+ end
+
+ def test_no_indent
+ @client.wiredump_dev = str = ''
+ @client.options["soap.envelope.no_indent"] = true
+ @client.nop
+ assert_equal(NO_INDENT_XML, parse_requestxml(str))
+ end
+
+ def parse_requestxml(str)
+ str.split(/\r?\n\r?\n/)[3]
+ end
+end
+
+
+end
+
+end
diff --git a/ruby_1_8_6/test/soap/test_property.rb b/ruby_1_8_6/test/soap/test_property.rb
new file mode 100644
index 0000000000..7acd2c8437
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_property.rb
@@ -0,0 +1,424 @@
+require 'test/unit'
+require 'soap/property'
+
+
+module SOAP
+
+
+class TestProperty < Test::Unit::TestCase
+ FrozenError = (RUBY_VERSION >= "1.9.0") ? RuntimeError : TypeError
+
+ def setup
+ @prop = ::SOAP::Property.new
+ end
+
+ def teardown
+ # Nothing to do.
+ end
+
+ def test_s_load
+ propstr = <<__EOP__
+
+# comment1
+
+# comment2\r
+# comment2
+
+\r
+a.b.0 = 1
+a.b.1 = 2
+a.b.2 = 3
+client.protocol.http.proxy=http://myproxy:8080 \r
+client.protocol.http.no_proxy: intranet.example.com,local.example.com\r
+client.protocol.http.protocol_version = 1.0
+foo\\:bar\\=baz = qux
+foo\\\\.bar.baz=\tq\\\\ux\ttab
+ a\\ b = 1
+[ppp.qqq.rrr]
+sss = 3
+ttt.uuu = 4
+
+[ sss.ttt.uuu ]
+vvv.www = 5
+[ ]
+xxx.yyy.zzz = 6
+__EOP__
+ prop = Property.load(propstr)
+ assert_equal(["1", "2", "3"], prop["a.b"].values.sort)
+ assert_equal("intranet.example.com,local.example.com",
+ prop["client.protocol.http.no_proxy"])
+ assert_equal("http://myproxy:8080", prop["client.protocol.http.proxy"])
+ assert_equal("1.0", prop["client.protocol.http.protocol_version"])
+ assert_equal("q\\ux\ttab", prop['foo\.bar.baz'])
+ assert_equal("1", prop['a b'])
+ assert_equal("3", prop['ppp.qqq.rrr.sss'])
+ assert_equal("4", prop['ppp.qqq.rrr.ttt.uuu'])
+ assert_equal("5", prop['sss.ttt.uuu.vvv.www'])
+ assert_equal("6", prop['xxx.yyy.zzz'])
+ end
+
+ def test_load
+ prop = Property.new
+ hooked = false
+ prop.add_hook("foo.bar.baz") do |name, value|
+ assert_equal(["foo", "bar", "baz"], name)
+ assert_equal("123", value)
+ hooked = true
+ end
+ prop.lock
+ prop["foo.bar"].lock
+ prop.load("foo.bar.baz = 123")
+ assert(hooked)
+ assert_raises(FrozenError) do
+ prop.load("foo.bar.qux = 123")
+ end
+ prop.load("foo.baz = 456")
+ assert_equal("456", prop["foo.baz"])
+ end
+
+ def test_initialize
+ prop = ::SOAP::Property.new
+ # store is empty
+ assert_nil(prop["a"])
+ # does hook work?
+ assert_equal(1, prop["a"] = 1)
+ end
+
+ def test_aref
+ # name_to_a
+ assert_nil(@prop[:foo])
+ assert_nil(@prop["foo"])
+ assert_nil(@prop[[:foo]])
+ assert_nil(@prop[["foo"]])
+ assert_raises(ArgumentError) do
+ @prop[1]
+ end
+ @prop[:foo] = :foo
+ assert_equal(:foo, @prop[:foo])
+ assert_equal(:foo, @prop["foo"])
+ assert_equal(:foo, @prop[[:foo]])
+ assert_equal(:foo, @prop[["foo"]])
+ end
+
+ def test_referent
+ # referent(1)
+ assert_nil(@prop["foo.foo"])
+ assert_nil(@prop[["foo", "foo"]])
+ assert_nil(@prop[["foo", :foo]])
+ @prop["foo.foo"] = :foo
+ assert_equal(:foo, @prop["foo.foo"])
+ assert_equal(:foo, @prop[["foo", "foo"]])
+ assert_equal(:foo, @prop[[:foo, "foo"]])
+ # referent(2)
+ @prop["bar.bar.bar"] = :bar
+ assert_equal(:bar, @prop["bar.bar.bar"])
+ assert_equal(:bar, @prop[["bar", "bar", "bar"]])
+ assert_equal(:bar, @prop[[:bar, "bar", :bar]])
+ end
+
+ def test_to_key_and_deref
+ @prop["foo.foo"] = :foo
+ assert_equal(:foo, @prop["fOo.FoO"])
+ assert_equal(:foo, @prop[[:fOO, :FOO]])
+ assert_equal(:foo, @prop[["FoO", :Foo]])
+ # deref_key negative test
+ assert_raises(ArgumentError) do
+ @prop["baz"] = 1
+ @prop["baz.qux"] = 2
+ end
+ end
+
+ def test_hook_name
+ tag = Object.new
+ tested = false
+ @prop.add_hook("foo.bar") do |key, value|
+ assert_raise(FrozenError) do
+ key << "baz"
+ end
+ tested = true
+ end
+ @prop["foo.bar"] = tag
+ assert(tested)
+ end
+
+ def test_value_hook
+ tag = Object.new
+ tested = false
+ @prop.add_hook("FOO.BAR.BAZ") do |key, value|
+ assert_equal(["Foo", "baR", "baZ"], key)
+ assert_equal(tag, value)
+ tested = true
+ end
+ @prop["Foo.baR.baZ"] = tag
+ assert_equal(tag, @prop["foo.bar.baz"])
+ assert(tested)
+ @prop["foo.bar"] = 1 # unhook the above block
+ assert_equal(1, @prop["foo.bar"])
+ end
+
+ def test_key_hook_no_cascade
+ tag = Object.new
+ tested = 0
+ @prop.add_hook do |key, value|
+ assert(false)
+ end
+ @prop.add_hook(false) do |key, value|
+ assert(false)
+ end
+ @prop.add_hook("foo") do |key, value|
+ assert(false)
+ end
+ @prop.add_hook("foo.bar", false) do |key, value|
+ assert(false)
+ end
+ @prop.add_hook("foo.bar.baz") do |key, value|
+ assert(false)
+ end
+ @prop.add_hook("foo.bar.baz.qux", false) do |key, value|
+ assert_equal(["foo", "bar", "baz", "qux"], key)
+ assert_equal(tag, value)
+ tested += 1
+ end
+ @prop["foo.bar.baz.qux"] = tag
+ assert_equal(tag, @prop["foo.bar.baz.qux"])
+ assert_equal(1, tested)
+ end
+
+ def test_key_hook_cascade
+ tag = Object.new
+ tested = 0
+ @prop.add_hook(true) do |key, value|
+ assert_equal(["foo", "bar", "baz", "qux"], key)
+ assert_equal(tag, value)
+ tested += 1
+ end
+ @prop.add_hook("foo", true) do |key, value|
+ assert_equal(["foo", "bar", "baz", "qux"], key)
+ assert_equal(tag, value)
+ tested += 1
+ end
+ @prop.add_hook("foo.bar", true) do |key, value|
+ assert_equal(["foo", "bar", "baz", "qux"], key)
+ assert_equal(tag, value)
+ tested += 1
+ end
+ @prop.add_hook("foo.bar.baz", true) do |key, value|
+ assert_equal(["foo", "bar", "baz", "qux"], key)
+ assert_equal(tag, value)
+ tested += 1
+ end
+ @prop.add_hook("foo.bar.baz.qux", true) do |key, value|
+ assert_equal(["foo", "bar", "baz", "qux"], key)
+ assert_equal(tag, value)
+ tested += 1
+ end
+ @prop["foo.bar.baz.qux"] = tag
+ assert_equal(tag, @prop["foo.bar.baz.qux"])
+ assert_equal(5, tested)
+ end
+
+ def test_keys
+ assert(@prop.keys.empty?)
+ @prop["foo"] = 1
+ @prop["bar"]
+ @prop["BAz"] = 2
+ assert_equal(2, @prop.keys.size)
+ assert(@prop.keys.member?("foo"))
+ assert(@prop.keys.member?("baz"))
+ #
+ assert_nil(@prop["a"])
+ @prop["a.a"] = 1
+ assert_instance_of(::SOAP::Property, @prop["a"])
+ @prop["a.b"] = 1
+ @prop["a.c"] = 1
+ assert_equal(3, @prop["a"].keys.size)
+ assert(@prop["a"].keys.member?("a"))
+ assert(@prop["a"].keys.member?("b"))
+ assert(@prop["a"].keys.member?("c"))
+ end
+
+ def test_lshift
+ assert(@prop.empty?)
+ @prop << 1
+ assert_equal([1], @prop.values)
+ assert_equal(1, @prop["0"])
+ @prop << 1
+ assert_equal([1, 1], @prop.values)
+ assert_equal(1, @prop["1"])
+ @prop << 1
+ assert_equal([1, 1, 1], @prop.values)
+ assert_equal(1, @prop["2"])
+ #
+ @prop["abc.def"] = o = SOAP::Property.new
+ tested = 0
+ o.add_hook do |k, v|
+ tested += 1
+ end
+ @prop["abc.def"] << 1
+ @prop["abc.def"] << 2
+ @prop["abc.def"] << 3
+ @prop["abc.def"] << 4
+ assert_equal(4, tested)
+ end
+
+ def test_lock_each
+ @prop["a.b.c.d.e"] = 1
+ @prop["a.b.d"] = branch = ::SOAP::Property.new
+ @prop["a.b.d.e.f"] = 2
+ @prop.lock
+ assert(@prop.locked?)
+ assert_instance_of(::SOAP::Property, @prop["a"])
+ assert_raises(FrozenError) do
+ @prop["b"]
+ end
+ #
+ @prop["a"].lock
+ assert_raises(FrozenError) do
+ @prop["a"]
+ end
+ assert_instance_of(::SOAP::Property, @prop["a.b"])
+ #
+ @prop["a.b"].lock
+ assert_raises(FrozenError) do
+ @prop["a.b"]
+ end
+ assert_raises(FrozenError) do
+ @prop["a"]
+ end
+ #
+ @prop["a.b.c.d"].lock
+ assert_instance_of(::SOAP::Property, @prop["a.b.c"])
+ assert_raises(FrozenError) do
+ @prop["a.b.c.d"]
+ end
+ assert_instance_of(::SOAP::Property, @prop["a.b.d"])
+ #
+ branch["e"].lock
+ assert_instance_of(::SOAP::Property, @prop["a.b.d"])
+ assert_raises(FrozenError) do
+ @prop["a.b.d.e"]
+ end
+ assert_raises(FrozenError) do
+ branch["e"]
+ end
+ end
+
+ def test_lock_cascade
+ @prop["a.a"] = nil
+ @prop["a.b.c"] = 1
+ @prop["b"] = false
+ @prop.lock(true)
+ assert(@prop.locked?)
+ assert_equal(nil, @prop["a.a"])
+ assert_equal(1, @prop["a.b.c"])
+ assert_equal(false, @prop["b"])
+ assert_raises(FrozenError) do
+ @prop["c"]
+ end
+ assert_raises(FrozenError) do
+ @prop["c"] = 2
+ end
+ assert_raises(FrozenError) do
+ @prop["a.b.R"]
+ end
+ assert_raises(FrozenError) do
+ @prop.add_hook do
+ assert(false)
+ end
+ end
+ assert_raises(FrozenError) do
+ @prop.add_hook("c") do
+ assert(false)
+ end
+ end
+ assert_raises(FrozenError) do
+ @prop.add_hook("a.c") do
+ assert(false)
+ end
+ end
+ assert_nil(@prop["a.a"])
+ @prop["a.a"] = 2
+ assert_equal(2, @prop["a.a"])
+ #
+ @prop.unlock(true)
+ assert_nil(@prop["c"])
+ @prop["c"] = 2
+ assert_equal(2, @prop["c"])
+ @prop["a.d.a.a"] = :foo
+ assert_equal(:foo, @prop["a.d.a.a"])
+ tested = false
+ @prop.add_hook("a.c") do |name, value|
+ assert(true)
+ tested = true
+ end
+ @prop["a.c"] = 3
+ assert(tested)
+ end
+
+ def test_hook_then_lock
+ tested = false
+ @prop.add_hook("a.b.c") do |name, value|
+ assert_equal(["a", "b", "c"], name)
+ tested = true
+ end
+ @prop["a.b"].lock
+ assert(!tested)
+ @prop["a.b.c"] = 5
+ assert(tested)
+ assert_equal(5, @prop["a.b.c"])
+ assert_raises(FrozenError) do
+ @prop["a.b.d"] = 5
+ end
+ end
+
+ def test_lock_unlock_return
+ assert_equal(@prop, @prop.lock)
+ assert_equal(@prop, @prop.unlock)
+ end
+
+ def test_lock_split
+ @prop["a.b.c"] = 1
+ assert_instance_of(::SOAP::Property, @prop["a.b"])
+ @prop["a.b.d"] = branch = ::SOAP::Property.new
+ @prop["a.b.d.e"] = 2
+ assert_equal(branch, @prop["a.b.d"])
+ assert_equal(branch, @prop[:a][:b][:d])
+ @prop.lock(true)
+ # split error 1
+ assert_raises(FrozenError) do
+ @prop["a.b"]
+ end
+ # split error 2
+ assert_raises(FrozenError) do
+ @prop["a"]
+ end
+ @prop["a.b.c"] = 2
+ assert_equal(2, @prop["a.b.c"])
+ # replace error
+ assert_raises(FrozenError) do
+ @prop["a.b.c"] = ::SOAP::Property.new
+ end
+ # override error
+ assert_raises(FrozenError) do
+ @prop["a.b"] = 1
+ end
+ #
+ assert_raises(FrozenError) do
+ @prop["a.b.d"] << 1
+ end
+ assert_raises(FrozenError) do
+ branch << 1
+ end
+ branch.unlock(true)
+ branch << 1
+ branch << 2
+ branch << 3
+ assert_equal(2, @prop["a.b.d.e"])
+ assert_equal(1, @prop["a.b.d.1"])
+ assert_equal(2, @prop["a.b.d.2"])
+ assert_equal(3, @prop["a.b.d.3"])
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/test_soapelement.rb b/ruby_1_8_6/test/soap/test_soapelement.rb
new file mode 100644
index 0000000000..66e2a836a4
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_soapelement.rb
@@ -0,0 +1,122 @@
+require 'test/unit'
+require 'soap/baseData'
+require 'soap/mapping'
+
+
+module SOAP
+
+
+class TestSOAPElement < Test::Unit::TestCase
+ include SOAP
+
+ def setup
+ # Nothing to do.
+ end
+
+ def teardown
+ # Nothing to do.
+ end
+
+ def d(elename = nil, text = nil)
+ elename ||= n(nil, nil)
+ if text
+ SOAPElement.new(elename, text)
+ else
+ SOAPElement.new(elename) # do not merge.
+ end
+ end
+
+ def n(namespace, name)
+ XSD::QName.new(namespace, name)
+ end
+
+ def test_initialize
+ elename = n(nil, nil)
+ obj = d(elename)
+ assert_equal(elename, obj.elename)
+ assert_equal(LiteralNamespace, obj.encodingstyle)
+ assert_equal({}, obj.extraattr)
+ assert_equal([], obj.precedents)
+ assert_equal(nil, obj.qualified)
+ assert_equal(nil, obj.text)
+ assert(obj.members.empty?)
+
+ obj = d("foo", "text")
+ assert_equal(n(nil, "foo"), obj.elename)
+ assert_equal("text", obj.text)
+ end
+
+ def test_add
+ obj = d()
+ child = d("abc")
+ obj.add(child)
+ assert(obj.key?("abc"))
+ assert_same(child, obj["abc"])
+ assert_same(child, obj.abc)
+ def obj.foo; 1; end
+ child = d("foo")
+ obj.add(child)
+ assert_equal(1, obj.foo)
+ assert_equal(child, obj.var_foo)
+ child = d("_?a?b_")
+ obj.add(child)
+ assert_equal(child, obj.__send__('_?a?b_'))
+ end
+
+ def test_member
+ obj = d()
+ c1 = d("c1")
+ obj.add(c1)
+ c2 = d("c2")
+ obj.add(c2)
+ assert(obj.key?("c1"))
+ assert(obj.key?("c2"))
+ assert_equal(c1, obj["c1"])
+ assert_equal(c2, obj["c2"])
+ c22 = d("c22")
+ obj["c2"] = c22
+ assert(obj.key?("c2"))
+ assert_equal(c22, obj["c2"])
+ assert_equal(["c1", "c2"], obj.members.sort)
+ #
+ k_expect = ["c1", "c2"]
+ v_expect = [c1, c22]
+ obj.each do |k, v|
+ assert(k_expect.include?(k))
+ assert(v_expect.include?(v))
+ k_expect.delete(k)
+ v_expect.delete(v)
+ end
+ assert(k_expect.empty?)
+ assert(v_expect.empty?)
+ end
+
+ def test_to_obj
+ obj = d("root")
+ ct1 = d("ct1", "t1")
+ obj.add(ct1)
+ c2 = d("c2")
+ ct2 = d("ct2", "t2")
+ c2.add(ct2)
+ obj.add(c2)
+ assert_equal({ "ct1" => "t1", "c2" => { "ct2" => "t2" }}, obj.to_obj)
+ #
+ assert_equal(nil, d().to_obj)
+ assert_equal("abc", d(nil, "abc").to_obj)
+ assert_equal(nil, d("abc", nil).to_obj)
+ end
+
+ def test_from_obj
+ source = { "ct1" => "t1", "c2" => { "ct2" => "t2" }}
+ assert_equal(source, SOAPElement.from_obj(source).to_obj)
+ source = { "1" => nil }
+ assert_equal(source, SOAPElement.from_obj(source).to_obj)
+ source = {}
+ assert_equal(nil, SOAPElement.from_obj(source).to_obj) # not {}
+ source = nil
+ assert_equal(nil, SOAPElement.from_obj(source).to_obj)
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/test_streamhandler.rb b/ruby_1_8_6/test/soap/test_streamhandler.rb
new file mode 100644
index 0000000000..c31254513f
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_streamhandler.rb
@@ -0,0 +1,209 @@
+require 'test/unit'
+require 'soap/rpc/driver'
+require 'webrick'
+require 'webrick/httpproxy'
+require 'logger'
+
+
+module SOAP
+
+
+class TestStreamHandler < Test::Unit::TestCase
+ Port = 17171
+ ProxyPort = 17172
+
+ def setup
+ @logger = Logger.new(STDERR)
+ @logger.level = Logger::Severity::ERROR
+ @url = "http://localhost:#{Port}/"
+ @proxyurl = "http://localhost:#{ProxyPort}/"
+ @server = @proxyserver = @client = nil
+ @server_thread = @proxyserver_thread = nil
+ setup_server
+ setup_client
+ end
+
+ def teardown
+ teardown_client
+ teardown_proxyserver if @proxyserver
+ teardown_server
+ end
+
+ def setup_server
+ @server = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Logger => @logger,
+ :Port => Port,
+ :AccessLog => [],
+ :DocumentRoot => File.dirname(File.expand_path(__FILE__))
+ )
+ @server.mount(
+ '/',
+ WEBrick::HTTPServlet::ProcHandler.new(method(:do_server_proc).to_proc)
+ )
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_proxyserver
+ @proxyserver = WEBrick::HTTPProxyServer.new(
+ :BindAddress => "0.0.0.0",
+ :Logger => @logger,
+ :Port => ProxyPort,
+ :AccessLog => []
+ )
+ @proxyserver_thread = start_server_thread(@proxyserver)
+ end
+
+ def setup_client
+ @client = SOAP::RPC::Driver.new(@url, '')
+ @client.add_method("do_server_proc")
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_proxyserver
+ @proxyserver.shutdown
+ @proxyserver_thread.kill
+ @proxyserver_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def do_server_proc(req, res)
+ res['content-type'] = 'text/xml'
+ res.body = <<__EOX__
+<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:do_server_proc xmlns:n1="urn:foo" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+ <return xsi:nil="true"/>
+ </n1:do_server_proc>
+ </env:Body>
+</env:Envelope>
+__EOX__
+ end
+
+ def parse_req_header(str)
+ if ::SOAP::HTTPStreamHandler::Client.to_s == 'SOAP::NetHttpClient'
+ str = eval(str.split(/\r?\n/)[4][3..-1])
+ end
+ parse_req_header_http_access2(str)
+ end
+
+ def parse_req_header_http_access2(str)
+ headerp = false
+ headers = {}
+ req = nil
+ str.split(/(?:\r?\n)/).each do |line|
+ if headerp and /^$/ =~line
+ headerp = false
+ break
+ end
+ if headerp
+ k, v = line.scan(/^([^:]+):\s*(.*)$/)[0]
+ headers[k.downcase] = v
+ end
+ if /^POST/ =~ line
+ req = line
+ headerp = true
+ end
+ end
+ return req, headers
+ end
+
+ def test_normal
+ str = ""
+ @client.wiredump_dev = str
+ assert_nil(@client.do_server_proc)
+ r, h = parse_req_header(str)
+ assert_match(%r"POST / HTTP/1.", r)
+ assert(/^text\/xml;/ =~ h["content-type"])
+ end
+
+ def test_uri
+ # initialize client with URI object
+ @client = SOAP::RPC::Driver.new(URI.parse(@url), '')
+ @client.add_method("do_server_proc")
+ # same as test_normal
+ str = ""
+ @client.wiredump_dev = str
+ assert_nil(@client.do_server_proc)
+ r, h = parse_req_header(str)
+ assert_match(%r"POST / HTTP/1.", r)
+ assert(/^text\/xml;/ =~ h["content-type"])
+ end
+
+ def test_basic_auth
+ unless Object.const_defined?('HTTPAccess2')
+ # soap4r + net/http + basic_auth is not supported.
+ # use http-access2 instead.
+ assert(true)
+ return
+ end
+ str = ""
+ @client.wiredump_dev = str
+ @client.options["protocol.http.basic_auth"] << [@url, "foo", "bar"]
+ assert_nil(@client.do_server_proc)
+ r, h = parse_req_header(str)
+ assert_equal("Basic Zm9vOmJhcg==", h["authorization"])
+ end
+
+ def test_proxy
+ if Object.const_defined?('HTTPAccess2')
+ backup = HTTPAccess2::Client::NO_PROXY_HOSTS.dup
+ HTTPAccess2::Client::NO_PROXY_HOSTS.clear
+ else
+ backup = SOAP::NetHttpClient::NO_PROXY_HOSTS.dup
+ SOAP::NetHttpClient::NO_PROXY_HOSTS.clear
+ end
+ setup_proxyserver
+ str = ""
+ @client.wiredump_dev = str
+ @client.options["protocol.http.proxy"] = @proxyurl
+ assert_nil(@client.do_server_proc)
+ r, h = parse_req_header(str)
+ assert_match(%r"POST http://localhost:17171/ HTTP/1.", r)
+ # illegal proxy uri
+ assert_raise(ArgumentError) do
+ @client.options["protocol.http.proxy"] = 'ftp://foo:8080'
+ end
+ ensure
+ if Object.const_defined?('HTTPAccess2')
+ HTTPAccess2::Client::NO_PROXY_HOSTS.replace(backup)
+ else
+ SOAP::NetHttpClient::NO_PROXY_HOSTS.replace(backup)
+ end
+ end
+
+ def test_charset
+ str = ""
+ @client.wiredump_dev = str
+ @client.options["protocol.http.charset"] = "iso-8859-8"
+ assert_nil(@client.do_server_proc)
+ r, h = parse_req_header(str)
+ assert_equal("text/xml; charset=iso-8859-8", h["content-type"])
+ #
+ str.replace("")
+ @client.options["protocol.http.charset"] = "iso-8859-3"
+ assert_nil(@client.do_server_proc)
+ r, h = parse_req_header(str)
+ assert_equal("text/xml; charset=iso-8859-3", h["content-type"])
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/test_styleuse.rb b/ruby_1_8_6/test/soap/test_styleuse.rb
new file mode 100644
index 0000000000..4ea321848d
--- /dev/null
+++ b/ruby_1_8_6/test/soap/test_styleuse.rb
@@ -0,0 +1,333 @@
+require 'test/unit'
+require 'soap/rpc/httpserver'
+require 'soap/rpc/driver'
+
+
+module SOAP
+
+
+class TestStyleUse < Test::Unit::TestCase
+ # rpc driver: obj in(Hash allowed for literal), obj out
+ #
+ # style: not visible from user
+ # rpc: wrapped element
+ # document: unwrappted element
+ #
+ # use:
+ # encoding: a graph (SOAP Data Model)
+ # literal: not a graph (SOAPElement)
+ #
+ # rpc stub: obj in, obj out(Hash is allowed for literal)
+ #
+ # style: not visible from user
+ # rpc: wrapped element
+ # document: unwrappted element
+ #
+ # use:
+ # encoding: a graph (SOAP Data Model)
+ # literal: not a graph (SOAPElement)
+ #
+ # document driver: SOAPElement in, SOAPElement out? [not implemented]
+ #
+ # style: ditto
+ # use: ditto
+ #
+ #
+ # document stub: SOAPElement in, SOAPElement out? [not implemented]
+ #
+ # style: ditto
+ # use: ditto
+ #
+ class GenericServant
+ # method name style: requeststyle_requestuse_responsestyle_responseuse
+
+ # 2 params -> array
+ def rpc_enc_rpc_enc(obj1, obj2)
+ [obj1, [obj1, obj2]]
+ end
+
+ # 2 objs -> array
+ def rpc_lit_rpc_enc(obj1, obj2)
+ [obj2, obj1]
+ end
+
+ # 2 params -> 2 params
+ def rpc_enc_rpc_lit(obj1, obj2)
+ klass = [obj1.class.name, obj2.class.name]
+ [obj2, obj1]
+ end
+
+ # 2 objs -> 2 objs
+ def rpc_lit_rpc_lit(obj1, obj2)
+ [obj1, obj2]
+ end
+
+ # 2 params -> array
+ def doc_enc_doc_enc(obj1, obj2)
+ [obj1, [obj1, obj2]]
+ end
+
+ # 2 objs -> array
+ def doc_lit_doc_enc(obj1, obj2)
+ [obj2, obj1]
+ end
+
+ # 2 params -> 2 hashes
+ def doc_enc_doc_lit(obj1, obj2)
+ klass = [obj1.class.name, obj2.class.name]
+ return {'obj1' => {'klass' => klass}, 'misc' => 'hash does not have an order'},
+ {'obj2' => {'klass' => klass}}
+ end
+
+ # 2 objs -> 2 objs
+ def doc_lit_doc_lit(obj1, obj2)
+ return obj1, obj2
+ end
+ end
+
+ Namespace = "urn:styleuse"
+
+ module Op
+ def self.opt(request_style, request_use, response_style, response_use)
+ {
+ :request_style => request_style,
+ :request_use => request_use,
+ :response_style => response_style,
+ :response_use => response_use
+ }
+ end
+
+ Op_rpc_enc_rpc_enc = [
+ XSD::QName.new(Namespace, 'rpc_enc_rpc_enc'),
+ nil,
+ 'rpc_enc_rpc_enc', [
+ ['in', 'obj1', nil],
+ ['in', 'obj2', nil],
+ ['retval', 'return', nil]],
+ opt(:rpc, :encoded, :rpc, :encoded)
+ ]
+
+ Op_rpc_lit_rpc_enc = [
+ XSD::QName.new(Namespace, 'rpc_lit_rpc_enc'),
+ nil,
+ 'rpc_lit_rpc_enc', [
+ ['in', 'obj1', nil],
+ ['in', 'obj2', nil],
+ ['retval', 'return', nil]],
+ opt(:rpc, :literal, :rpc, :encoded)
+ ]
+
+ Op_rpc_enc_rpc_lit = [
+ XSD::QName.new(Namespace, 'rpc_enc_rpc_lit'),
+ nil,
+ 'rpc_enc_rpc_lit', [
+ ['in', 'obj1', nil],
+ ['in', 'obj2', nil],
+ ['retval', 'ret1', nil],
+ ['out', 'ret2', nil]],
+ opt(:rpc, :encoded, :rpc, :literal)
+ ]
+
+ Op_rpc_lit_rpc_lit = [
+ XSD::QName.new(Namespace, 'rpc_lit_rpc_lit'),
+ nil,
+ 'rpc_lit_rpc_lit', [
+ ['in', 'obj1', nil],
+ ['in', 'obj2', nil],
+ ['retval', 'ret1', nil],
+ ['out', 'ret2', nil]],
+ opt(:rpc, :literal, :rpc, :literal)
+ ]
+
+ Op_doc_enc_doc_enc = [
+ Namespace + 'doc_enc_doc_enc',
+ 'doc_enc_doc_enc', [
+ ['in', 'obj1', [nil, Namespace, 'obj1']],
+ ['in', 'obj2', [nil, Namespace, 'obj2']],
+ ['out', 'ret1', [nil, Namespace, 'ret1']],
+ ['out', 'ret2', [nil, Namespace, 'ret2']]],
+ opt(:document, :encoded, :document, :encoded)
+ ]
+
+ Op_doc_lit_doc_enc = [
+ Namespace + 'doc_lit_doc_enc',
+ 'doc_lit_doc_enc', [
+ ['in', 'obj1', [nil, Namespace, 'obj1']],
+ ['in', 'obj2', [nil, Namespace, 'obj2']],
+ ['out', 'ret1', [nil, Namespace, 'ret1']],
+ ['out', 'ret2', [nil, Namespace, 'ret2']]],
+ opt(:document, :literal, :document, :encoded)
+ ]
+
+ Op_doc_enc_doc_lit = [
+ Namespace + 'doc_enc_doc_lit',
+ 'doc_enc_doc_lit', [
+ ['in', 'obj1', [nil, Namespace, 'obj1']],
+ ['in', 'obj2', [nil, Namespace, 'obj2']],
+ ['out', 'ret1', [nil, Namespace, 'ret1']],
+ ['out', 'ret2', [nil, Namespace, 'ret2']]],
+ opt(:document, :encoded, :document, :literal)
+ ]
+
+ Op_doc_lit_doc_lit = [
+ Namespace + 'doc_lit_doc_lit',
+ 'doc_lit_doc_lit', [
+ ['in', 'obj1', [nil, Namespace, 'obj1']],
+ ['in', 'obj2', [nil, Namespace, 'obj2']],
+ ['out', 'ret1', [nil, Namespace, 'ret1']],
+ ['out', 'ret2', [nil, Namespace, 'ret2']]],
+ opt(:document, :literal, :document, :literal)
+ ]
+ end
+
+ include Op
+
+ class Server < ::SOAP::RPC::HTTPServer
+ include Op
+
+ def on_init
+ @servant = GenericServant.new
+ add_rpc_operation(@servant, *Op_rpc_enc_rpc_enc)
+ add_rpc_operation(@servant, *Op_rpc_lit_rpc_enc)
+ add_rpc_operation(@servant, *Op_rpc_enc_rpc_lit)
+ add_rpc_operation(@servant, *Op_rpc_lit_rpc_lit)
+ add_document_operation(@servant, *Op_doc_enc_doc_enc)
+ add_document_operation(@servant, *Op_doc_lit_doc_enc)
+ add_document_operation(@servant, *Op_doc_enc_doc_lit)
+ add_document_operation(@servant, *Op_doc_lit_doc_lit)
+ end
+ end
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new(
+ :BindAddress => "0.0.0.0",
+ :Port => Port,
+ :AccessLog => [],
+ :SOAPDefaultNamespace => Namespace
+ )
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/", Namespace)
+ @client.wiredump_dev = STDERR if $DEBUG
+ @client.add_rpc_operation(*Op_rpc_enc_rpc_enc)
+ @client.add_rpc_operation(*Op_rpc_lit_rpc_enc)
+ @client.add_rpc_operation(*Op_rpc_enc_rpc_lit)
+ @client.add_rpc_operation(*Op_rpc_lit_rpc_lit)
+ @client.add_document_operation(*Op_doc_enc_doc_enc)
+ @client.add_document_operation(*Op_doc_lit_doc_enc)
+ @client.add_document_operation(*Op_doc_enc_doc_lit)
+ @client.add_document_operation(*Op_doc_lit_doc_lit)
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_rpc_enc_rpc_enc
+ o = "hello"
+ obj1 = o
+ obj2 = [1]
+ ret = @client.rpc_enc_rpc_enc(obj1, obj2)
+ # server returns [obj1, [obj1, obj2]]
+ assert_equal([obj1, [obj1, obj2]], ret)
+ assert_same(ret[0], ret[1][0])
+ end
+
+ S1 = ::Struct.new(:a)
+ S2 = ::Struct.new(:c)
+ def test_rpc_lit_rpc_enc
+ ret1, ret2 = @client.rpc_lit_rpc_enc(S1.new('b'), S2.new('d'))
+ assert_equal('d', ret1.c)
+ assert_equal('b', ret2.a)
+ # Hash is allowed for literal
+ ret1, ret2 = @client.rpc_lit_rpc_enc({'a' => 'b'}, {'c' => 'd'})
+ assert_equal('d', ret1.c)
+ assert_equal('b', ret2.a)
+ # simple value
+ assert_equal(
+ ['1', 'a'],
+ @client.rpc_lit_rpc_enc('a', 1)
+ )
+ end
+
+ def test_rpc_enc_rpc_lit
+ assert_equal(
+ ['1', 'a'],
+ @client.rpc_enc_rpc_lit('a', '1')
+ )
+ end
+
+ def test_rpc_lit_rpc_lit
+ ret1, ret2 = @client.rpc_lit_rpc_lit({'a' => 'b'}, {'c' => 'd'})
+ assert_equal('b', ret1["a"])
+ assert_equal('d', ret2["c"])
+ end
+
+ def test_doc_enc_doc_enc
+ o = "hello"
+ obj1 = o
+ obj2 = [1]
+ ret = @client.rpc_enc_rpc_enc(obj1, obj2)
+ # server returns [obj1, [obj1, obj2]]
+ assert_equal([obj1, [obj1, obj2]], ret)
+ assert_same(ret[0], ret[1][0])
+ end
+
+ def test_doc_lit_doc_enc
+ ret1, ret2 = @client.doc_lit_doc_enc({'a' => 'b'}, {'c' => 'd'})
+ assert_equal('d', ret1.c)
+ assert_equal('b', ret2.a)
+ assert_equal(
+ ['a', '1'],
+ @client.doc_lit_doc_enc(1, 'a')
+ )
+ end
+
+ def test_doc_enc_doc_lit
+ ret1, ret2 = @client.doc_enc_doc_lit('a', 1)
+ # literal Array
+ assert_equal(['String', 'Fixnum'], ret1['obj1']['klass'])
+ # same value
+ assert_equal(ret1['obj1']['klass'], ret2['obj2']['klass'])
+ # not the same object (not encoded)
+ assert_not_same(ret1['obj1']['klass'], ret2['obj2']['klass'])
+ end
+
+ def test_doc_lit_doc_lit
+ ret1, ret2 = @client.doc_lit_doc_lit({'a' => 'b'}, {'c' => 'd'})
+ assert_equal('b', ret1["a"])
+ assert_equal('d', ret2["c"])
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/README.txt b/ruby_1_8_6/test/soap/wsdlDriver/README.txt
new file mode 100644
index 0000000000..b4d45a0486
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/README.txt
@@ -0,0 +1,2 @@
+echo_version.rb is generated by wsdl2ruby.rb;
+% wsdl2ruby.rb --wsdl simpletype.wsdl --classdef --force
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/calc.wsdl b/ruby_1_8_6/test/soap/wsdlDriver/calc.wsdl
new file mode 100644
index 0000000000..694a01e87e
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/calc.wsdl
@@ -0,0 +1,126 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!--generated by GLUE Standard 4.0.1 on Wed Mar 09 10:20:07 GMT-08:00
+2005-->
+<wsdl:definitions name='Calculator'
+targetNamespace='http://www.themindelectric.com/wsdl/Calculator/'
+ xmlns:tns='http://www.themindelectric.com/wsdl/Calculator/'
+ xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/'
+ xmlns:http='http://schemas.xmlsoap.org/wsdl/http/'
+ xmlns:mime='http://schemas.xmlsoap.org/wsdl/mime/'
+ xmlns:xsd='http://www.w3.org/2001/XMLSchema'
+ xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'
+ xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'
+ xmlns:tme='http://www.themindelectric.com/'>
+ <wsdl:message name='add0In'>
+ <wsdl:part name='x' type='xsd:float'/>
+ <wsdl:part name='y' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='add0Out'>
+ <wsdl:part name='Result' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='divide1In'>
+ <wsdl:part name='numerator' type='xsd:float'/>
+ <wsdl:part name='denominator' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='divide1Out'>
+ <wsdl:part name='Result' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='multiply2In'>
+ <wsdl:part name='x' type='xsd:float'/>
+ <wsdl:part name='y' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='multiply2Out'>
+ <wsdl:part name='Result' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='subtract3In'>
+ <wsdl:part name='x' type='xsd:float'/>
+ <wsdl:part name='y' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:message name='subtract3Out'>
+ <wsdl:part name='Result' type='xsd:float'/>
+ </wsdl:message>
+ <wsdl:portType name='ICalculator'>
+ <wsdl:operation name='add' parameterOrder='x y'>
+ <wsdl:input name='add0In' message='tns:add0In'/>
+ <wsdl:output name='add0Out' message='tns:add0Out'/>
+ </wsdl:operation>
+ <wsdl:operation name='divide' parameterOrder='numerator
+denominator'>
+ <wsdl:input name='divide1In' message='tns:divide1In'/>
+ <wsdl:output name='divide1Out' message='tns:divide1Out'/>
+ </wsdl:operation>
+ <wsdl:operation name='multiply' parameterOrder='x y'>
+ <wsdl:input name='multiply2In' message='tns:multiply2In'/>
+ <wsdl:output name='multiply2Out'
+message='tns:multiply2Out'/>
+ </wsdl:operation>
+ <wsdl:operation name='subtract' parameterOrder='x y'>
+ <wsdl:input name='subtract3In' message='tns:subtract3In'/>
+ <wsdl:output name='subtract3Out'
+message='tns:subtract3Out'/>
+ </wsdl:operation>
+ </wsdl:portType>
+ <wsdl:binding name='ICalculator' type='tns:ICalculator'>
+ <soap:binding style='rpc'
+transport='http://schemas.xmlsoap.org/soap/http'/>
+ <wsdl:operation name='add'>
+ <soap:operation soapAction='add' style='rpc'/>
+ <wsdl:input name='add0In'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:input>
+ <wsdl:output name='add0Out'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:output>
+ </wsdl:operation>
+ <wsdl:operation name='divide'>
+ <soap:operation soapAction='divide' style='rpc'/>
+ <wsdl:input name='divide1In'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:input>
+ <wsdl:output name='divide1Out'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:output>
+ </wsdl:operation>
+ <wsdl:operation name='multiply'>
+ <soap:operation soapAction='multiply' style='rpc'/>
+ <wsdl:input name='multiply2In'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:input>
+ <wsdl:output name='multiply2Out'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:output>
+ </wsdl:operation>
+ <wsdl:operation name='subtract'>
+ <soap:operation soapAction='subtract' style='rpc'/>
+ <wsdl:input name='subtract3In'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:input>
+ <wsdl:output name='subtract3Out'>
+ <soap:body use='encoded'
+namespace='http://www.fred.com'
+encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
+ </wsdl:output>
+ </wsdl:operation>
+ </wsdl:binding>
+ <wsdl:service name='Calculator'>
+ <wsdl:documentation>calculator service</wsdl:documentation>
+ <wsdl:port name='ICalculator' binding='tns:ICalculator'>
+ <soap:address
+location='http://ukulele:8080/calcapp/services/calculator'/>
+ </wsdl:port>
+ </wsdl:service>
+</wsdl:definitions>
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/document.wsdl b/ruby_1_8_6/test/soap/wsdlDriver/document.wsdl
new file mode 100644
index 0000000000..5e9e74b9df
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/document.wsdl
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name="submit_service"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="urn:example.com:document"
+ targetNamespace="urn:example.com:document"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema targetNamespace="urn:example.com:document">
+ <xsd:element name="ruby">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element minOccurs="1" maxOccurs="1" name="myversion" type="tns:myversion"/>
+ <xsd:element minOccurs="0" maxOccurs="1" name="date" type="xsd:dateTime"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+ <xsd:simpleType name="myversion">
+ <xsd:restriction base="xsd:string">
+ <xsd:enumeration value="1.6"/>
+ <xsd:enumeration value="1.8"/>
+ <xsd:enumeration value="1.9"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:schema>
+ </types>
+
+ <message name="submit_msg">
+ <part name="parameters" element="tns:ruby"/>
+ </message>
+
+ <portType name="submit_port_type">
+ <operation name="submit">
+ <input message="tns:submit_msg"/>
+ <output message="tns:submit_msg"/>
+ </operation>
+ </portType>
+
+ <binding name="submit_binding" type="tns:submit_port_type">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
+ <operation name="submit">
+ <soap:operation soapAction="urn:example.com:document#submit" style="document"/>
+ <input><soap:body use="literal"/></input>
+ <output><soap:body use="literal"/></output>
+ </operation>
+ </binding>
+
+ <service name="submit_service">
+ <port name="submit_port" binding="tns:submit_binding">
+ <soap:address location="http://localhost:10080"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/echo_version.rb b/ruby_1_8_6/test/soap/wsdlDriver/echo_version.rb
new file mode 100644
index 0000000000..7d76fb7587
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/echo_version.rb
@@ -0,0 +1,20 @@
+# urn:example.com:simpletype-rpc-type
+class Version_struct
+ @@schema_type = "version_struct"
+ @@schema_ns = "urn:example.com:simpletype-rpc-type"
+
+ attr_accessor :version
+ attr_accessor :msg
+
+ def initialize(version = nil, msg = nil)
+ @version = version
+ @msg = msg
+ end
+end
+
+# urn:example.com:simpletype-rpc-type
+module Versions
+ C_16 = "1.6"
+ C_18 = "1.8"
+ C_19 = "1.9"
+end
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/simpletype.wsdl b/ruby_1_8_6/test/soap/wsdlDriver/simpletype.wsdl
new file mode 100644
index 0000000000..6781dda552
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/simpletype.wsdl
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name="echo_version"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="urn:example.com:simpletype-rpc"
+ xmlns:txd="urn:example.com:simpletype-rpc-type"
+ targetNamespace="urn:example.com:simpletype-rpc"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema targetNamespace="urn:example.com:simpletype-rpc-type">
+ <xsd:complexType name="version_struct">
+ <xsd:all>
+ <xsd:element name="myversion" type="txd:myversions" />
+ <xsd:element name="msg" type="xsd:string" />
+ </xsd:all>
+ </xsd:complexType>
+
+ <xsd:simpleType name="myversions">
+ <xsd:restriction base="xsd:string">
+ <xsd:enumeration value="1.6"/>
+ <xsd:enumeration value="1.8"/>
+ <xsd:enumeration value="1.9"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:schema>
+ </types>
+
+ <message name="msg_version">
+ <part name="myversion" type="txd:myversions"/>
+ </message>
+
+ <message name="msg_version_struct">
+ <part name="return" type="txd:version_struct"/>
+ </message>
+
+ <portType name="echo_version_port_type">
+ <operation name="echo_version">
+ <input message="tns:msg_version"/>
+ <output message="tns:msg_version_struct"/>
+ </operation>
+ </portType>
+
+ <binding name="echo_version_binding" type="tns:echo_version_port_type">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
+ <operation name="echo_version">
+ <soap:operation soapAction="urn:example.com:simpletype-rpc"/>
+ <input>
+ <soap:body use="encoded" namespace="urn:example.com:simpletype-rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:example.com:simpletype-rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="echo_version_service">
+ <port name="echo_version_port" binding="tns:echo_version_binding">
+ <soap:address location="http://localhost:10080"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/test_calc.rb b/ruby_1_8_6/test/soap/wsdlDriver/test_calc.rb
new file mode 100644
index 0000000000..d031f663a3
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/test_calc.rb
@@ -0,0 +1,100 @@
+require 'test/unit'
+require 'soap/rpc/httpserver'
+require 'soap/wsdlDriver'
+
+
+module SOAP
+
+
+class TestCalc < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::HTTPServer
+ def on_init
+ add_method(self, 'add', 'x', 'y')
+ end
+
+ def add(x, y)
+ x.to_f + y.to_f
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new(
+ :BindAddress => "0.0.0.0",
+ :Port => Port,
+ :AccessLog => [],
+ :SOAPDefaultNamespace => 'http://www.fred.com'
+ )
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ @wsdl = File.join(DIR, 'calc.wsdl')
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream if @client
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_rpc_driver
+ @client = ::SOAP::WSDLDriverFactory.new(@wsdl).create_rpc_driver
+ @client.wiredump_dev = STDOUT if $DEBUG
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.generate_explicit_type = true
+ assert_equal(0.3, @client.add(0.1, 0.2))
+ @client.generate_explicit_type = false
+ assert_equal(0.3, @client.add(0.1, 0.2))
+ end
+
+ def test_old_driver
+ silent do
+ @client = ::SOAP::WSDLDriverFactory.new(@wsdl).create_driver
+ end
+ @client.wiredump_dev = STDOUT if $DEBUG
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.generate_explicit_type = true
+ assert_equal(0.3, @client.add(0.1, 0.2))
+ @client.generate_explicit_type = false
+ assert_equal(0.3, @client.add(0.1, 0.2))
+ end
+
+ def silent
+ back = $VERBOSE
+ $VERBOSE = nil
+ begin
+ yield
+ ensure
+ $VERBOSE = back
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/test_document.rb b/ruby_1_8_6/test/soap/wsdlDriver/test_document.rb
new file mode 100644
index 0000000000..634b827aae
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/test_document.rb
@@ -0,0 +1,78 @@
+require 'test/unit'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+
+module SOAP
+
+
+class TestDocument < Test::Unit::TestCase
+ Namespace = 'urn:example.com:document'
+
+ class Server < ::SOAP::RPC::StandaloneServer
+ def on_init
+ add_document_method(self, 'urn:example.com:document#submit', 'submit', XSD::QName.new(Namespace, 'ruby'), XSD::QName.new(Namespace, 'ruby'))
+ end
+
+ def submit(ruby)
+ ruby
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new('Test', Namespace, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'document.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDOUT if $DEBUG
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_document
+ msg = {'myversion' => "1.9", 'date' => "2004-01-01T00:00:00Z"}
+ reply_msg = @client.submit(msg)
+ assert_equal('1.9', reply_msg.myversion)
+ assert_equal('1.9', reply_msg['myversion'])
+ assert_equal('2004-01-01T00:00:00Z', reply_msg.date)
+ assert_equal('2004-01-01T00:00:00Z', reply_msg['date'])
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/soap/wsdlDriver/test_simpletype.rb b/ruby_1_8_6/test/soap/wsdlDriver/test_simpletype.rb
new file mode 100644
index 0000000000..76b3a32df7
--- /dev/null
+++ b/ruby_1_8_6/test/soap/wsdlDriver/test_simpletype.rb
@@ -0,0 +1,87 @@
+require 'test/unit'
+require 'soap/rpc/httpserver'
+require 'soap/wsdlDriver'
+
+
+module SOAP
+
+
+class TestSimpleType < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::HTTPServer
+ def on_init
+ add_method(self, 'echo_version', 'version')
+ end
+
+ def echo_version(version)
+ # "2.0" is out of range.
+ Version_struct.new(version || "2.0", 'checked')
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+ require File.join(DIR, 'echo_version')
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new(
+ :BindAddress => "0.0.0.0",
+ :Port => Port,
+ :AccessLog => [],
+ :SOAPDefaultNamespace => "urn:example.com:simpletype-rpc"
+ )
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'simpletype.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.wiredump_dev = STDOUT if $DEBUG
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.generate_explicit_type = false
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_ping
+ result = @client.echo_version("1.9")
+ assert_equal("1.9", result.version)
+ assert_equal("checked", result.msg)
+ assert_raise(XSD::ValueSpaceError) do
+ @client.echo_version("2.0")
+ end
+ assert_raise(XSD::ValueSpaceError) do
+ @client.echo_version(nil) # nil => "2.0" => out of range
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/socket/test_nonblock.rb b/ruby_1_8_6/test/socket/test_nonblock.rb
new file mode 100644
index 0000000000..ed6487b49f
--- /dev/null
+++ b/ruby_1_8_6/test/socket/test_nonblock.rb
@@ -0,0 +1,179 @@
+begin
+ require "socket"
+rescue LoadError
+end
+
+require "test/unit"
+require "tempfile"
+require "timeout"
+
+class TestNonblockSocket < Test::Unit::TestCase
+ def test_accept_nonblock
+ serv = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { serv.accept_nonblock }
+ c = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ c.connect(serv.getsockname)
+ s, sockaddr = serv.accept_nonblock
+ assert_equal(Socket.unpack_sockaddr_in(c.getsockname), Socket.unpack_sockaddr_in(sockaddr))
+ ensure
+ serv.close if serv
+ c.close if c
+ s.close if s
+ end
+
+ def test_connect_nonblock
+ serv = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ c = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ servaddr = serv.getsockname
+ begin
+ c.connect_nonblock(servaddr)
+ rescue Errno::EINPROGRESS
+ IO.select nil, [c]
+ assert_nothing_raised {
+ begin
+ c.connect_nonblock(servaddr)
+ rescue Errno::EISCONN
+ end
+ }
+ end
+ s, sockaddr = serv.accept
+ assert_equal(Socket.unpack_sockaddr_in(c.getsockname), Socket.unpack_sockaddr_in(sockaddr))
+ ensure
+ serv.close if serv
+ c.close if c
+ s.close if s
+ end
+
+ def test_udp_recvfrom_nonblock
+ u1 = UDPSocket.new
+ u2 = UDPSocket.new
+ u1.bind("127.0.0.1", 0)
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recvfrom_nonblock(100) }
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL) { u2.recvfrom_nonblock(100) }
+ u2.send("aaa", 0, u1.getsockname)
+ IO.select [u1]
+ mesg, inet_addr = u1.recvfrom_nonblock(100)
+ assert_equal(4, inet_addr.length)
+ assert_equal("aaa", mesg)
+ af, port, host, addr = inet_addr
+ u2_port, u2_addr = Socket.unpack_sockaddr_in(u2.getsockname)
+ assert_equal(u2_port, port)
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recvfrom_nonblock(100) }
+ u2.send("", 0, u1.getsockname)
+ assert_nothing_raised("cygwin 1.5.19 has a problem to send an empty UDP packet. [ruby-dev:28915]") {
+ timeout(1) { IO.select [u1] }
+ }
+ mesg, inet_addr = u1.recvfrom_nonblock(100)
+ assert_equal("", mesg)
+ ensure
+ u1.close if u1
+ u2.close if u2
+ end
+
+ def test_udp_recv_nonblock
+ u1 = UDPSocket.new
+ u2 = UDPSocket.new
+ u1.bind("127.0.0.1", 0)
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recv_nonblock(100) }
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL) { u2.recv_nonblock(100) }
+ u2.send("aaa", 0, u1.getsockname)
+ IO.select [u1]
+ mesg = u1.recv_nonblock(100)
+ assert_equal("aaa", mesg)
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recv_nonblock(100) }
+ u2.send("", 0, u1.getsockname)
+ assert_nothing_raised("cygwin 1.5.19 has a problem to send an empty UDP packet. [ruby-dev:28915]") {
+ timeout(1) { IO.select [u1] }
+ }
+ mesg = u1.recv_nonblock(100)
+ assert_equal("", mesg)
+ ensure
+ u1.close if u1
+ u2.close if u2
+ end
+
+ def test_socket_recvfrom_nonblock
+ s1 = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s2 = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM, 0)
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s1.recvfrom_nonblock(100) }
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL) { s2.recvfrom_nonblock(100) }
+ s2.send("aaa", 0, s1.getsockname)
+ IO.select [s1]
+ mesg, sockaddr = s1.recvfrom_nonblock(100)
+ assert_equal("aaa", mesg)
+ port, addr = Socket.unpack_sockaddr_in(sockaddr)
+ s2_port, s2_addr = Socket.unpack_sockaddr_in(s2.getsockname)
+ assert_equal(s2_port, port)
+ ensure
+ s1.close if s1
+ s2.close if s2
+ end
+
+ def tcp_pair
+ serv = TCPServer.new("127.0.0.1", 0)
+ af, port, host, addr = serv.addr
+ c = TCPSocket.new(addr, port)
+ s = serv.accept
+ return c, s
+ ensure
+ serv.close if serv
+ end
+
+ def test_tcp_recv_nonblock
+ c, s = tcp_pair
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { c.recv_nonblock(100) }
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.recv_nonblock(100) }
+ c.write("abc")
+ IO.select [s]
+ assert_equal("a", s.recv_nonblock(1))
+ assert_equal("bc", s.recv_nonblock(100))
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.recv_nonblock(100) }
+ ensure
+ c.close if c
+ s.close if s
+ end
+
+ def test_read_nonblock
+ c, s = tcp_pair
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { c.read_nonblock(100) }
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.read_nonblock(100) }
+ c.write("abc")
+ IO.select [s]
+ assert_equal("a", s.read_nonblock(1))
+ assert_equal("bc", s.read_nonblock(100))
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.read_nonblock(100) }
+ ensure
+ c.close if c
+ s.close if s
+ end
+
+=begin
+ def test_write_nonblock
+ c, s = tcp_pair
+ str = "a" * 10000
+ _, ws, _ = IO.select(nil, [c], nil)
+ assert_equal([c], ws)
+ ret = c.write_nonblock(str)
+ assert_operator(ret, :>, 0)
+ loop {
+ assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) {
+ loop {
+ ret = c.write_nonblock(str)
+ assert_operator(ret, :>, 0)
+ }
+ }
+ _, ws, _ = IO.select(nil, [c], nil, 0)
+ break if !ws
+ }
+ ensure
+ c.close if c
+ s.close if s
+ end
+=end
+
+end if defined?(Socket)
diff --git a/ruby_1_8_6/test/socket/test_socket.rb b/ruby_1_8_6/test/socket/test_socket.rb
new file mode 100644
index 0000000000..fc01467f16
--- /dev/null
+++ b/ruby_1_8_6/test/socket/test_socket.rb
@@ -0,0 +1,83 @@
+begin
+ require "socket"
+ require "test/unit"
+rescue LoadError
+end
+
+class TestBasicSocket < Test::Unit::TestCase
+ def inet_stream
+ sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ yield sock
+ ensure
+ assert_raise(IOError) {sock.close}
+ end
+
+ def test_getsockopt
+ inet_stream do |s|
+ n = s.getsockopt(Socket::SOL_SOCKET, Socket::SO_TYPE)
+ assert_equal([Socket::SOCK_STREAM].pack("i"), n)
+ n = s.getsockopt(Socket::SOL_SOCKET, Socket::SO_ERROR)
+ assert_equal([0].pack("i"), n)
+ val = Object.new
+ class << val; self end.__send__(:define_method, :to_int) {
+ s.close
+ Socket::SO_TYPE
+ }
+ assert_raise(IOError) {
+ n = s.getsockopt(Socket::SOL_SOCKET, val)
+ }
+ end
+ end
+
+ def test_setsockopt # [ruby-dev:25039]
+ s = nil
+ linger = [0, 0].pack("ii")
+
+ val = Object.new
+ class << val; self end.__send__(:define_method, :to_str) {
+ s.close
+ linger
+ }
+ inet_stream do |s|
+ assert_equal(0, s.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, linger))
+
+ assert_raise(IOError) {
+ s.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, val)
+ }
+ end
+
+ val = Object.new
+ class << val; self end.__send__(:define_method, :to_int) {
+ s.close
+ Socket::SO_LINGER
+ }
+ inet_stream do |s|
+ assert_raise(IOError) {
+ s.setsockopt(Socket::SOL_SOCKET, val, linger)
+ }
+ end
+ end
+
+ def test_listen
+ s = nil
+ log = Object.new
+ class << log; self end.__send__(:define_method, :to_int) {
+ s.close
+ 2
+ }
+ inet_stream do |s|
+ assert_raise(IOError) {
+ s.listen(log)
+ }
+ end
+ end
+end if defined?(Socket)
+
+class TestSocket < Test::Unit::TestCase
+ def test_unpack_sockaddr
+ sockaddr_in = Socket.sockaddr_in(80, "")
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_un(sockaddr_in) }
+ sockaddr_un = Socket.sockaddr_un("/tmp/s")
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_in(sockaddr_un) }
+ end
+end if defined?(Socket) && Socket.respond_to?(:sockaddr_un)
diff --git a/ruby_1_8_6/test/socket/test_unix.rb b/ruby_1_8_6/test/socket/test_unix.rb
new file mode 100644
index 0000000000..14ddd6a4b6
--- /dev/null
+++ b/ruby_1_8_6/test/socket/test_unix.rb
@@ -0,0 +1,141 @@
+begin
+ require "socket"
+rescue LoadError
+end
+
+require "test/unit"
+require "tempfile"
+
+class TestUNIXSocket < Test::Unit::TestCase
+ def test_fd_passing
+ r1, w = IO.pipe
+ s1, s2 = UNIXSocket.pair
+ begin
+ s1.send_io(nil)
+ rescue NotImplementedError
+ assert_raise(NotImplementedError) { s2.recv_io }
+ rescue TypeError
+ s1.send_io(r1)
+ r2 = s2.recv_io
+ assert_equal(r1.stat.ino, r2.stat.ino)
+ assert_not_equal(r1.fileno, r2.fileno)
+ w.syswrite "a"
+ assert_equal("a", r2.sysread(10))
+ ensure
+ s1.close
+ s2.close
+ w.close
+ r1.close
+ r2.close if r2 && !r2.closed?
+ end
+ end
+
+ def bound_unix_socket(klass)
+ tmpfile = Tempfile.new("testrubysock")
+ path = tmpfile.path
+ tmpfile.close(true)
+ yield klass.new(path), path
+ ensure
+ File.unlink path if path && File.socket?(path)
+ end
+
+ def test_addr
+ bound_unix_socket(UNIXServer) {|serv, path|
+ c = UNIXSocket.new(path)
+ s = serv.accept
+ assert_equal(["AF_UNIX", path], c.peeraddr)
+ assert_equal(["AF_UNIX", ""], c.addr)
+ assert_equal(["AF_UNIX", ""], s.peeraddr)
+ assert_equal(["AF_UNIX", path], s.addr)
+ assert_equal(path, s.path)
+ assert_equal("", c.path)
+ }
+ end
+
+ def test_noname_path
+ s1, s2 = UNIXSocket.pair
+ assert_equal("", s1.path)
+ assert_equal("", s2.path)
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_noname_addr
+ s1, s2 = UNIXSocket.pair
+ assert_equal(["AF_UNIX", ""], s1.addr)
+ assert_equal(["AF_UNIX", ""], s2.addr)
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_noname_peeraddr
+ s1, s2 = UNIXSocket.pair
+ assert_equal(["AF_UNIX", ""], s1.peeraddr)
+ assert_equal(["AF_UNIX", ""], s2.peeraddr)
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_noname_unpack_sockaddr_un
+ s1, s2 = UNIXSocket.pair
+ n = nil
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getsockname) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getsockname) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s2.getsockname) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getpeername) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s2.getpeername) != ""
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_noname_recvfrom
+ s1, s2 = UNIXSocket.pair
+ s2.write("a")
+ assert_equal(["a", ["AF_UNIX", ""]], s1.recvfrom(10))
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_noname_recv_nonblock
+ s1, s2 = UNIXSocket.pair
+ s2.write("a")
+ IO.select [s1]
+ assert_equal("a", s1.recv_nonblock(10))
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_too_long_path
+ assert_raise(ArgumentError) { Socket.sockaddr_un("a" * 300) }
+ assert_raise(ArgumentError) { UNIXServer.new("a" * 300) }
+ end
+
+ def test_nul
+ assert_raise(ArgumentError) { Socket.sockaddr_un("a\0b") }
+ assert_raise(ArgumentError) { UNIXServer.new("a\0b") }
+ end
+
+ def test_dgram_pair
+ s1, s2 = UNIXSocket.pair(Socket::SOCK_DGRAM)
+ assert_raise(Errno::EAGAIN) { s1.recv_nonblock(10) }
+ s2.send("", 0)
+ s2.send("haha", 0)
+ s2.send("", 0)
+ s2.send("", 0)
+ assert_equal("", s1.recv(10))
+ assert_equal("haha", s1.recv(10))
+ assert_equal("", s1.recv(10))
+ assert_equal("", s1.recv(10))
+ assert_raise(Errno::EAGAIN) { s1.recv_nonblock(10) }
+ ensure
+ s1.close if s1
+ s2.close if s2
+ end
+
+end if defined?(UNIXSocket) && /cygwin/ !~ RUBY_PLATFORM
diff --git a/ruby_1_8_6/test/stringio/test_stringio.rb b/ruby_1_8_6/test/stringio/test_stringio.rb
new file mode 100644
index 0000000000..de15ab5508
--- /dev/null
+++ b/ruby_1_8_6/test/stringio/test_stringio.rb
@@ -0,0 +1,43 @@
+require 'test/unit'
+require 'stringio'
+dir = File.expand_path(__FILE__)
+2.times {dir = File.dirname(dir)}
+$:.replace([File.join(dir, "ruby")] | $:)
+require 'ut_eof'
+
+class TestStringIO < Test::Unit::TestCase
+ include TestEOF
+ def open_file(content)
+ f = StringIO.new(content)
+ yield f
+ end
+ alias open_file_rw open_file
+
+ include TestEOF::Seek
+
+ def test_truncate # [ruby-dev:24190]
+ io = StringIO.new("")
+ io.puts "abc"
+ io.truncate(0)
+ io.puts "def"
+ assert_equal("\0\0\0\0def\n", io.string)
+ end
+
+ def test_seek_beyond_eof # [ruby-dev:24194]
+ io = StringIO.new
+ n = 100
+ io.seek(n)
+ io.print "last"
+ assert_equal("\0" * n + "last", io.string)
+ end
+
+ def test_overwrite # [ruby-core:03836]
+ stringio = StringIO.new
+ responses = ['', 'just another ruby', 'hacker']
+ responses.each do |resp|
+ stringio.puts(resp)
+ stringio.rewind
+ end
+ assert_equal("hacker\nother ruby\n", stringio.string)
+ end
+end
diff --git a/ruby_1_8_6/test/strscan/test_stringscanner.rb b/ruby_1_8_6/test/strscan/test_stringscanner.rb
new file mode 100644
index 0000000000..75e96c0293
--- /dev/null
+++ b/ruby_1_8_6/test/strscan/test_stringscanner.rb
@@ -0,0 +1,571 @@
+#
+# test/strscan/test_stringscanner.rb
+#
+
+require 'strscan'
+require 'test/unit'
+
+class TestStringScanner < Test::Unit::TestCase
+ def test_s_new
+ s = StringScanner.new('test string')
+ assert_instance_of StringScanner, s
+ assert_equal false, s.eos?
+ assert_equal false, s.tainted?
+
+ str = 'test string'
+ str.taint
+ s = StringScanner.new(str, false)
+ assert_instance_of StringScanner, s
+ assert_equal false, s.eos?
+ assert_same str, s.string
+ assert_equal true, s.string.tainted?
+
+ str = 'test string'
+ str.taint
+ s = StringScanner.new(str)
+ assert_equal true, s.string.tainted?
+ end
+
+ UNINIT_ERROR = ArgumentError
+
+ def test_s_allocate
+ s = StringScanner.allocate
+ assert_equal '#<StringScanner (uninitialized)>', s.inspect.sub(/StringScanner_C/, 'StringScanner')
+ assert_raises(UNINIT_ERROR) { s.eos? }
+ assert_raises(UNINIT_ERROR) { s.scan(/a/) }
+ s.string = 'test'
+ assert_equal '#<StringScanner 0/4 @ "test">', s.inspect.sub(/StringScanner_C/, 'StringScanner')
+ assert_nothing_raised(UNINIT_ERROR) { s.eos? }
+ assert_equal false, s.eos?
+ end
+
+ def test_s_mustc
+ assert_nothing_raised(NotImplementedError) {
+ StringScanner.must_C_version
+ }
+ end
+
+ def test_dup
+ s = StringScanner.new('test string')
+ d = s.dup
+ assert_equal s.inspect, d.inspect
+ assert_equal s.string, d.string
+ assert_equal s.pos, d.pos
+ assert_equal s.matched?, d.matched?
+ assert_equal s.eos?, d.eos?
+
+ s = StringScanner.new('test string')
+ s.scan(/test/)
+ d = s.dup
+ assert_equal s.inspect, d.inspect
+ assert_equal s.string, d.string
+ assert_equal s.pos, d.pos
+ assert_equal s.matched?, d.matched?
+ assert_equal s.eos?, d.eos?
+
+ s = StringScanner.new('test string')
+ s.scan(/test/)
+ s.scan(/NOT MATCH/)
+ d = s.dup
+ assert_equal s.inspect, d.inspect
+ assert_equal s.string, d.string
+ assert_equal s.pos, d.pos
+ assert_equal s.matched?, d.matched?
+ assert_equal s.eos?, d.eos?
+
+ s = StringScanner.new('test string')
+ s.terminate
+ d = s.dup
+ assert_equal s.inspect, d.inspect
+ assert_equal s.string, d.string
+ assert_equal s.pos, d.pos
+ assert_equal s.matched?, d.matched?
+ assert_equal s.eos?, d.eos?
+ end
+
+ def test_const_Version
+ assert_instance_of String, StringScanner::Version
+ assert_equal true, StringScanner::Version.frozen?
+ end
+
+ def test_const_Id
+ assert_instance_of String, StringScanner::Id
+ assert_equal true, StringScanner::Id.frozen?
+ end
+
+ def test_inspect
+ str = 'test string'
+ str.taint
+ s = StringScanner.new(str, false)
+ assert_instance_of String, s.inspect
+ assert_equal s.inspect, s.inspect
+ assert_equal '#<StringScanner 0/11 @ "test ...">', s.inspect.sub(/StringScanner_C/, 'StringScanner')
+ s.get_byte
+ assert_equal '#<StringScanner 1/11 "t" @ "est s...">', s.inspect.sub(/StringScanner_C/, 'StringScanner')
+ assert_equal true, s.inspect.tainted?
+
+ s = StringScanner.new("\n")
+ assert_equal '#<StringScanner 0/1 @ "\n">', s.inspect
+ end
+
+ def test_eos?
+ s = StringScanner.new('test string')
+ assert_equal false, s.eos?
+ assert_equal false, s.eos?
+ s.scan(/\w+/)
+ assert_equal false, s.eos?
+ assert_equal false, s.eos?
+ s.scan(/\s+/)
+ s.scan(/\w+/)
+ assert_equal true, s.eos?
+ assert_equal true, s.eos?
+ s.scan(/\w+/)
+ assert_equal true, s.eos?
+
+ s = StringScanner.new('test')
+ s.scan(/te/)
+ s.string.replace ''
+ assert_equal true, s.eos?
+ end
+
+ def test_bol?
+ s = StringScanner.new("a\nbbb\n\ncccc\nddd\r\neee")
+ assert_equal true, s.bol?
+ assert_equal true, s.bol?
+ s.scan(/a/)
+ assert_equal false, s.bol?
+ assert_equal false, s.bol?
+ s.scan(/\n/)
+ assert_equal true, s.bol?
+ s.scan(/b/)
+ assert_equal false, s.bol?
+ s.scan(/b/)
+ assert_equal false, s.bol?
+ s.scan(/b/)
+ assert_equal false, s.bol?
+ s.scan(/\n/)
+ assert_equal true, s.bol?
+ s.unscan
+ assert_equal false, s.bol?
+ s.scan(/\n/)
+ s.scan(/\n/)
+ assert_equal true, s.bol?
+ s.scan(/c+\n/)
+ assert_equal true, s.bol?
+ s.scan(/d+\r\n/)
+ assert_equal true, s.bol?
+ s.scan(/e+/)
+ assert_equal false, s.bol?
+ end
+
+ def test_string
+ s = StringScanner.new('test')
+ assert_equal 'test', s.string
+ s.string = 'a'
+ assert_equal 'a', s.string
+ s.scan(/a/)
+ s.string = 'b'
+ assert_equal 0, s.pos
+ end
+
+ def test_pos
+ s = StringScanner.new('test string')
+ assert_equal 0, s.pos
+ s.get_byte
+ assert_equal 1, s.pos
+ s.get_byte
+ assert_equal 2, s.pos
+ s.terminate
+ assert_equal 11, s.pos
+ end
+
+ def test_concat
+ s = StringScanner.new('a')
+ s.scan(/a/)
+ s.concat 'b'
+ assert_equal false, s.eos?
+ assert_equal 'b', s.scan(/b/)
+ assert_equal true, s.eos?
+ s.concat 'c'
+ assert_equal false, s.eos?
+ assert_equal 'c', s.scan(/c/)
+ assert_equal true, s.eos?
+ end
+
+ def test_scan
+ s = StringScanner.new('stra strb strc', true)
+ tmp = s.scan(/\w+/)
+ assert_equal 'stra', tmp
+ assert_equal false, tmp.tainted?
+
+ tmp = s.scan(/\s+/)
+ assert_equal ' ', tmp
+ assert_equal false, tmp.tainted?
+
+ assert_equal 'strb', s.scan(/\w+/)
+ assert_equal ' ', s.scan(/\s+/)
+
+ tmp = s.scan(/\w+/)
+ assert_equal 'strc', tmp
+ assert_equal false, tmp.tainted?
+
+ assert_nil s.scan(/\w+/)
+ assert_nil s.scan(/\w+/)
+
+
+ str = 'stra strb strc'
+ str.taint
+ s = StringScanner.new(str, false)
+ tmp = s.scan(/\w+/)
+ assert_equal 'stra', tmp
+ assert_equal true, tmp.tainted?
+
+ tmp = s.scan(/\s+/)
+ assert_equal ' ', tmp
+ assert_equal true, tmp.tainted?
+
+ assert_equal 'strb', s.scan(/\w+/)
+ assert_equal ' ', s.scan(/\s+/)
+
+ tmp = s.scan(/\w+/)
+ assert_equal 'strc', tmp
+ assert_equal true, tmp.tainted?
+
+ assert_nil s.scan(/\w+/)
+ assert_nil s.scan(/\w+/)
+
+ s = StringScanner.new('test')
+ s.scan(/te/)
+ # This assumes #string does not duplicate string,
+ # but it is implementation specific issue.
+ # DO NOT RELY ON THIS FEATURE.
+ s.string.replace ''
+ # unspecified: assert_equal 2, s.pos
+ assert_equal nil, s.scan(/test/)
+
+ # [ruby-bugs:4361]
+ s = StringScanner.new("")
+ assert_equal "", s.scan(//)
+ assert_equal "", s.scan(//)
+
+ # [ruby-dev:29914]
+ %w( NONE EUC SJIS UTF8 ).each do |kcode|
+ begin
+ $KCODE = kcode
+ assert_equal "a", StringScanner.new("a:b").scan(/[^\x01\:]+/n)
+ assert_equal "a", StringScanner.new("a:b").scan(/[^\x01\:]+/e)
+ assert_equal "a", StringScanner.new("a:b").scan(/[^\x01\:]+/s)
+ assert_equal "a", StringScanner.new("a:b").scan(/[^\x01\:]+/u)
+ ensure
+ $KCODE = 'NONE'
+ end
+ end
+ end
+
+ def test_skip
+ s = StringScanner.new('stra strb strc', true)
+ assert_equal 4, s.skip(/\w+/)
+ assert_equal 1, s.skip(/\s+/)
+ assert_equal 4, s.skip(/\w+/)
+ assert_equal 1, s.skip(/\s+/)
+ assert_equal 4, s.skip(/\w+/)
+ assert_nil s.skip(/\w+/)
+ assert_nil s.skip(/\s+/)
+ assert_equal true, s.eos?
+
+ s = StringScanner.new('test')
+ s.scan(/te/)
+ s.string.replace ''
+ assert_equal nil, s.skip(/./)
+
+ # [ruby-bugs:4361]
+ s = StringScanner.new("")
+ assert_equal 0, s.skip(//)
+ assert_equal 0, s.skip(//)
+ end
+
+ def test_getch
+ s = StringScanner.new('abcde')
+ assert_equal 'a', s.getch
+ assert_equal 'b', s.getch
+ assert_equal 'c', s.getch
+ assert_equal 'd', s.getch
+ assert_equal 'e', s.getch
+ assert_nil s.getch
+
+ str = 'abc'
+ str.taint
+ s = StringScanner.new(str)
+ assert_equal true, s.getch.tainted?
+ assert_equal true, s.getch.tainted?
+ assert_equal true, s.getch.tainted?
+ assert_nil s.getch
+
+ kc_backup = $KCODE
+ begin
+ $KCODE = 'EUC'
+ s = StringScanner.new("\244\242")
+ assert_equal "\244\242", s.getch
+ assert_nil s.getch
+ ensure
+ $KCODE = kc_backup
+ end
+
+ s = StringScanner.new('test')
+ s.scan(/te/)
+ s.string.replace ''
+ assert_equal nil, s.getch
+ end
+
+ def test_get_byte
+ s = StringScanner.new('abcde')
+ assert_equal 'a', s.get_byte
+ assert_equal 'b', s.get_byte
+ assert_equal 'c', s.get_byte
+ assert_equal 'd', s.get_byte
+ assert_equal 'e', s.get_byte
+ assert_nil s.get_byte
+ assert_nil s.get_byte
+
+ str = 'abc'
+ str.taint
+ s = StringScanner.new(str)
+ assert_equal true, s.get_byte.tainted?
+ assert_equal true, s.get_byte.tainted?
+ assert_equal true, s.get_byte.tainted?
+ assert_nil s.get_byte
+
+ kc_backup = $KCODE
+ begin
+ $KCODE = 'EUC'
+ s = StringScanner.new("\244\242")
+ assert_equal "\244", s.get_byte
+ assert_equal "\242", s.get_byte
+ assert_nil s.get_byte
+ ensure
+ $KCODE = kc_backup
+ end
+
+ s = StringScanner.new('test')
+ s.scan(/te/)
+ s.string.replace ''
+ assert_equal nil, s.get_byte
+ end
+
+ def test_matched
+ s = StringScanner.new('stra strb strc')
+ s.scan(/\w+/)
+ assert_equal 'stra', s.matched
+ assert_equal false, s.matched.tainted?
+ s.scan(/\s+/)
+ assert_equal ' ', s.matched
+ s.scan(/\w+/)
+ assert_equal 'strb', s.matched
+ s.scan(/\s+/)
+ assert_equal ' ', s.matched
+ s.scan(/\w+/)
+ assert_equal 'strc', s.matched
+ s.scan(/\w+/)
+ assert_nil s.matched
+ s.getch
+ assert_nil s.matched
+
+ s = StringScanner.new('stra strb strc')
+ s.getch
+ assert_equal 's', s.matched
+ assert_equal false, s.matched.tainted?
+ s.get_byte
+ assert_equal 't', s.matched
+ assert_equal 't', s.matched
+ assert_equal false, s.matched.tainted?
+
+ str = 'test'
+ str.taint
+ s = StringScanner.new(str)
+ s.scan(/\w+/)
+ assert_equal true, s.matched.tainted?
+ assert_equal true, s.matched.tainted?
+ end
+
+ def test_AREF
+ s = StringScanner.new('stra strb strc')
+
+ s.scan(/\w+/)
+ assert_nil s[-2]
+ assert_equal 'stra', s[-1]
+ assert_equal 'stra', s[0]
+ assert_nil s[1]
+
+ assert_equal false, s[-1].tainted?
+ assert_equal false, s[0].tainted?
+
+ s.skip(/\s+/)
+ assert_nil s[-2]
+ assert_equal ' ', s[-1]
+ assert_equal ' ', s[0]
+ assert_nil s[1]
+
+ s.scan(/(s)t(r)b/)
+ assert_nil s[-100]
+ assert_nil s[-4]
+ assert_equal 'strb', s[-3]
+ assert_equal 's', s[-2]
+ assert_equal 'r', s[-1]
+ assert_equal 'strb', s[0]
+ assert_equal 's', s[1]
+ assert_equal 'r', s[2]
+ assert_nil s[3]
+ assert_nil s[100]
+
+ s.scan(/\s+/)
+
+ s.getch
+ assert_nil s[-2]
+ assert_equal 's', s[-1]
+ assert_equal 's', s[0]
+ assert_nil s[1]
+
+ s.get_byte
+ assert_nil s[-2]
+ assert_equal 't', s[-1]
+ assert_equal 't', s[0]
+ assert_nil s[1]
+
+ s.scan(/.*/)
+ s.scan(/./)
+ assert_nil s[0]
+ assert_nil s[0]
+
+
+ kc_backup = $KCODE
+ begin
+ $KCODE = 'EUC'
+ s = StringScanner.new("\244\242")
+ s.getch
+ assert_equal "\244\242", s[0]
+ ensure
+ $KCODE = kc_backup
+ end
+
+
+ str = 'test'
+ str.taint
+ s = StringScanner.new(str)
+ s.scan(/(t)(e)(s)(t)/)
+ assert_equal true, s[0].tainted?
+ assert_equal true, s[1].tainted?
+ assert_equal true, s[2].tainted?
+ assert_equal true, s[3].tainted?
+ assert_equal true, s[4].tainted?
+ end
+
+ def test_pre_match
+ s = StringScanner.new('a b c d e')
+ s.scan(/\w/)
+ assert_equal '', s.pre_match
+ assert_equal false, s.pre_match.tainted?
+ s.skip(/\s/)
+ assert_equal 'a', s.pre_match
+ assert_equal false, s.pre_match.tainted?
+ s.scan(/\w/)
+ assert_equal 'a ', s.pre_match
+ s.scan_until(/c/)
+ assert_equal 'a b ', s.pre_match
+ s.getch
+ assert_equal 'a b c', s.pre_match
+ s.get_byte
+ assert_equal 'a b c ', s.pre_match
+ s.get_byte
+ assert_equal 'a b c d', s.pre_match
+ s.scan(/never match/)
+ assert_nil s.pre_match
+
+ str = 'test string'
+ str.taint
+ s = StringScanner.new(str)
+ s.scan(/\w+/)
+ assert_equal true, s.pre_match.tainted?
+ s.scan(/\s+/)
+ assert_equal true, s.pre_match.tainted?
+ s.scan(/\w+/)
+ assert_equal true, s.pre_match.tainted?
+ end
+
+ def test_post_match
+ s = StringScanner.new('a b c d e')
+ s.scan(/\w/)
+ assert_equal ' b c d e', s.post_match
+ s.skip(/\s/)
+ assert_equal 'b c d e', s.post_match
+ s.scan(/\w/)
+ assert_equal ' c d e', s.post_match
+ s.scan_until(/c/)
+ assert_equal ' d e', s.post_match
+ s.getch
+ assert_equal 'd e', s.post_match
+ s.get_byte
+ assert_equal ' e', s.post_match
+ s.get_byte
+ assert_equal 'e', s.post_match
+ s.scan(/never match/)
+ assert_nil s.post_match
+ s.scan(/./)
+ assert_equal '', s.post_match
+ s.scan(/./)
+ assert_nil s.post_match
+
+ str = 'test string'
+ str.taint
+ s = StringScanner.new(str)
+ s.scan(/\w+/)
+ assert_equal true, s.post_match.tainted?
+ s.scan(/\s+/)
+ assert_equal true, s.post_match.tainted?
+ s.scan(/\w+/)
+ assert_equal true, s.post_match.tainted?
+ end
+
+ def test_terminate
+ s = StringScanner.new('ssss')
+ s.getch
+ s.terminate
+ assert_equal true, s.eos?
+ s.terminate
+ assert_equal true, s.eos?
+ end
+
+ def test_reset
+ s = StringScanner.new('ssss')
+ s.getch
+ s.reset
+ assert_equal 0, s.pos
+ s.scan(/\w+/)
+ s.reset
+ assert_equal 0, s.pos
+ s.reset
+ assert_equal 0, s.pos
+ end
+
+ def test_matched_size
+ s = StringScanner.new('test string')
+ assert_nil s.matched_size
+ s.scan(/test/)
+ assert_equal 4, s.matched_size
+ assert_equal 4, s.matched_size
+ s.scan(//)
+ assert_equal 0, s.matched_size
+ s.scan(/x/)
+ assert_nil s.matched_size
+ assert_nil s.matched_size
+ s.terminate
+ assert_nil s.matched_size
+
+ # obsolete
+ s = StringScanner.new('test string')
+ assert_nil s.matchedsize
+ s.scan(/test/)
+ assert_equal 4, s.matched_size
+ s.terminate
+ assert_nil s.matched_size
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/collector/test_dir.rb b/ruby_1_8_6/test/testunit/collector/test_dir.rb
new file mode 100644
index 0000000000..2de802c5e3
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/collector/test_dir.rb
@@ -0,0 +1,406 @@
+require 'test/unit'
+require 'test/unit/collector/dir'
+require 'pp'
+
+module Test
+ module Unit
+ module Collector
+ class TestDir < TestCase
+ class FileSystem
+ class Directory
+ def initialize(name, fs, parent=self, &block)
+ @name = name
+ @fs = fs
+ @parent = parent
+ @contents = {'.' => self, '..' => parent}
+ instance_eval(&block) if(block)
+ end
+
+ def file(name, contents)
+ @contents[name] = contents
+ end
+
+ def dir(name, &block)
+ @contents[name] = self.class.new(name, @fs, self, &block)
+ end
+
+ def entries
+ @contents.keys
+ end
+
+ def directory?(name)
+ return true if(name.nil? || name.empty?)
+ return false unless(@contents.include?(name))
+ @contents[name].kind_of?(self.class)
+ end
+
+ def file?(name)
+ return false unless(@contents.include?(name))
+ !directory?(name)
+ end
+
+ def exist?(name)
+ @contents.include?(name)
+ end
+
+ def [](name)
+ raise Errno::ENOENT, name unless(@contents.include?(name))
+ @contents[name]
+ end
+
+ def path_to(name=nil)
+ if(!name)
+ @parent.path_to(@name)
+ elsif(@parent == self)
+ @fs.join('/', name)
+ else
+ @fs.join(@parent.path_to(@name), name)
+ end
+ end
+ end
+
+ class ObjectSpace
+ def initialize
+ @objects = []
+ end
+
+ def each_object(klass, &block)
+ @objects.find_all{|o| o.kind_of?(klass)}.each(&block)
+ end
+
+ def <<(object)
+ @objects << object
+ end
+ end
+
+ attr_reader :object_space
+
+ def initialize(&block)
+ @root = Directory.new('/', self, &block)
+ @pwd = @root
+ @object_space = ObjectSpace.new
+ @required = []
+ end
+
+ def entries(dir)
+ e = find(dir)
+ require_directory(dir)
+ e.entries
+ end
+
+ def directory?(name)
+ return true if (base = basename(name)) == '/'
+ e = find(dirname(name))
+ return false unless(e)
+ e.directory?(base)
+ end
+
+ def find(path)
+ if(/\A\// =~ path)
+ thing = @root
+ else
+ thing = @pwd
+ end
+ path.scan(/[^\/]+/) do |e|
+ break thing = false unless(thing.kind_of?(Directory))
+ thing = thing[e]
+ end
+ thing
+ end
+
+ def dirname(name)
+ if (name = name.tr_s('/', '/')) == '/'
+ name
+ else
+ name[%r"\A.+(?=/[^/]+/?\z)|\A/"] || "."
+ end
+ end
+
+ def basename(name)
+ name[%r"(\A/|[^/]+)/*\z", 1]
+ end
+
+ def split(name)
+ [dirname(name), basename(name)]
+ end
+
+ def join(*parts)
+ parts.join('/').gsub(%r{/+}, '/')
+ end
+
+ def file?(name)
+ e = find(dirname(name))
+ return false unless(e)
+ e.file?(basename(name))
+ end
+
+ def pwd
+ @pwd.path_to
+ end
+
+ def chdir(to)
+ e = find(to)
+ require_directory(to)
+ @pwd = e
+ end
+
+ def expand_path(path, base = nil)
+ until /\A\// =~ path
+ base ||= pwd
+ path = join(base, path)
+ base = nil
+ end
+ path.gsub!(%r"(?:/\.)+(?=/)", '')
+ nil while path.sub!(%r"/(?!\.\./)[^/]+/\.\.(?=/)", '')
+ path.sub!(%r"\A(?:/\.\.)+(?=/)", '')
+ path.sub!(%r"(?:\A(/)|/)\.\.?\z", '\1')
+ path
+ end
+
+ def require_directory(path)
+ raise Errno::ENOTDIR, path unless(directory?(path))
+ end
+
+ def require(file)
+ return false if(@required.include?(file))
+ begin
+ e = find(file)
+ rescue Errno::ENOENT => e
+ if(/\.rb\Z/ =~ file)
+ raise LoadError, file
+ end
+ e = find(file + '.rb')
+ end
+ @required << file
+ @object_space << e
+ true
+ rescue Errno::ENOENT
+ raise LoadError, file
+ end
+ end
+
+ def test_dir
+ inner_dir = nil
+ dirs = FileSystem::Directory.new('/', nil) do
+ file 'a', nil
+ inner_dir = dir 'b'
+ end
+ assert_equal(inner_dir, dirs['b'])
+ end
+
+ def test_fs
+ fs = FileSystem.new do
+ file 'a', nil
+ dir 'b'
+ end
+ assert_equal(['.', '..', 'a', 'b'].sort, fs.entries('/').sort)
+ assert(fs.directory?('/'))
+ assert(!fs.directory?('/a'))
+ assert(!fs.directory?('/bogus'))
+ assert(fs.file?('/a'))
+ assert(!fs.file?('/'))
+ assert(!fs.file?('/bogus'))
+ assert(fs.directory?('/b'))
+ assert(fs.file?('a'))
+ assert(fs.directory?('b'))
+ end
+
+ def test_fs_sub
+ fs = FileSystem.new do
+ dir 'a' do
+ file 'b', nil
+ dir 'c' do
+ file 'd', nil
+ end
+ end
+ end
+ assert(fs.file?('/a/b'))
+ assert(!fs.file?('/a/b/c/d'))
+ assert(fs.file?('/a/c/d'))
+ end
+
+ def test_fs_pwd
+ fs = FileSystem.new do
+ file 'a', nil
+ dir 'b' do
+ file 'c', nil
+ dir 'd' do
+ file 'e', nil
+ end
+ end
+ end
+ assert_equal('/', fs.pwd)
+ assert_raises(Errno::ENOENT) do
+ fs.chdir('bogus')
+ end
+ assert_raises(Errno::ENOTDIR) do
+ fs.chdir('a')
+ end
+ fs.chdir('b')
+ assert_equal('/b', fs.pwd)
+ fs.chdir('d')
+ assert_equal('/b/d', fs.pwd)
+ fs.chdir('..')
+ assert_equal('/b', fs.pwd)
+ fs.chdir('..')
+ assert_equal('/', fs.pwd)
+ end
+
+ def test_fs_entries
+ fs = FileSystem.new do
+ file 'a', nil
+ dir 'b' do
+ file 'c', nil
+ file 'd', nil
+ end
+ file 'e', nil
+ dir 'f' do
+ file 'g', nil
+ dir 'h' do
+ file 'i', nil
+ end
+ end
+ end
+ assert_equal(['.', '..', 'a', 'b', 'e', 'f'], fs.entries('/').sort)
+ assert_equal(['.', '..', 'a', 'b', 'e', 'f'], fs.entries('.').sort)
+ assert_equal(['.', '..', 'a', 'b', 'e', 'f'], fs.entries('b/..').sort)
+ assert_equal(['.', '..', 'c', 'd'], fs.entries('b').sort)
+ assert_raises(Errno::ENOENT) do
+ fs.entries('z')
+ end
+ assert_raises(Errno::ENOTDIR) do
+ fs.entries('a')
+ end
+ fs.chdir('f')
+ assert_equal(['.', '..', 'i'], fs.entries('h').sort)
+ end
+
+ class TestClass1
+ end
+ class TestClass2
+ end
+ def test_fs_require
+ fs = FileSystem.new do
+ file 'test_class1.rb', TestClass1
+ dir 'dir' do
+ file 'test_class2.rb', TestClass2
+ end
+ end
+ c = []
+ fs.object_space.each_object(Class) do |o|
+ c << o
+ end
+ assert_equal([], c)
+
+ assert_raises(LoadError) do
+ fs.require('bogus')
+ end
+
+ assert(fs.require('test_class1.rb'))
+ assert(!fs.require('test_class1.rb'))
+ c = []
+ fs.object_space.each_object(Class) do |o|
+ c << o
+ end
+ assert_equal([TestClass1], c)
+
+ fs.require('dir/test_class2')
+ c = []
+ fs.object_space.each_object(Class) do |o|
+ c << o
+ end
+ assert_equal([TestClass1, TestClass2], c)
+
+ c = []
+ fs.object_space.each_object(Time) do |o|
+ c << o
+ end
+ assert_equal([], c)
+ end
+
+ def setup
+ @t1 = t1 = create_test(1)
+ @t2 = t2 = create_test(2)
+ @t3 = t3 = create_test(3)
+ @t4 = t4 = create_test(4)
+ @t5 = t5 = create_test(5)
+ @t6 = t6 = create_test(6)
+ fs = FileSystem.new do
+ file 'test_1.rb', t1
+ file 'test_2.rb', t2
+ dir 'd1' do
+ file 'test_3.rb', t3
+ end
+ file 't4.rb', t4
+ dir 'd2' do
+ file 'test_5', t5
+ file 'test_6.rb', Time
+ end
+ file 't6.rb', t6
+ end
+ fs.require('t6')
+ @c = Dir.new(fs, fs, fs.object_space, fs)
+ end
+
+ def create_test(name)
+ t = Class.new(TestCase)
+ t.class_eval <<-EOC
+ def self.name
+ "T\#{#{name}}"
+ end
+ def test_#{name}a
+ end
+ def test_#{name}b
+ end
+ EOC
+ t
+ end
+
+ def test_simple_collect
+ expected = TestSuite.new('d1')
+ expected << (@t3.suite)
+ assert_equal(expected, @c.collect('d1'))
+ end
+
+ def test_multilevel_collect
+ expected = TestSuite.new('.')
+ expected << @t1.suite << @t2.suite
+ expected << (TestSuite.new('d1') << @t3.suite)
+ assert_equal(expected, @c.collect)
+ end
+
+ def test_collect_file
+ expected = TestSuite.new('test_1.rb')
+ expected << @t1.suite
+ assert_equal(expected, @c.collect('test_1.rb'))
+
+ expected = TestSuite.new('t4.rb')
+ expected << @t4.suite
+ assert_equal(expected, @c.collect('t4.rb'))
+ end
+
+ def test_nil_pattern
+ expected = TestSuite.new('d2')
+ expected << @t5.suite
+ @c.pattern.clear
+ assert_equal(expected, @c.collect('d2'))
+ end
+
+ def test_filtering
+ expected = TestSuite.new('.')
+ expected << @t1.suite
+ @c.filter = proc{|t| t.method_name == 'test_1a' || t.method_name == 'test_1b'}
+ assert_equal(expected, @c.collect)
+ end
+
+ def test_collect_multi
+ expected = TestSuite.new('[d1, d2]')
+ expected << (TestSuite.new('d1') << @t3.suite)
+ expected << (TestSuite.new('d2') << @t5.suite)
+ @c.pattern.replace([/\btest_/])
+ assert_equal(expected, @c.collect('d1', 'd2'))
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/collector/test_objectspace.rb b/ruby_1_8_6/test/testunit/collector/test_objectspace.rb
new file mode 100644
index 0000000000..a1532ff3e6
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/collector/test_objectspace.rb
@@ -0,0 +1,98 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+require 'test/unit/collector/objectspace'
+
+module Test
+ module Unit
+ module Collector
+ class TC_ObjectSpace < TestCase
+ def setup
+ @tc1 = Class.new(TestCase) do
+ def self.name
+ "tc_1"
+ end
+ def test_1
+ end
+ def test_2
+ end
+ end
+
+ @tc2 = Class.new(TestCase) do
+ def self.name
+ "tc_2"
+ end
+ def test_0
+ end
+ end
+
+ @no_tc = Class.new do
+ def test_4
+ end
+ end
+
+ @object_space = {Class => [@tc1, @tc2, @no_tc], String => ['']}
+ def @object_space.each_object(type)
+ self[type].each{|item| yield(item) }
+ end
+
+ @c = ObjectSpace.new(@object_space)
+ end
+
+ def full_suite(name=ObjectSpace::NAME)
+ expected = TestSuite.new(name)
+ expected << (TestSuite.new(@tc1.name) << @tc1.new('test_1') << @tc1.new('test_2'))
+ expected << (TestSuite.new(@tc2.name) << @tc2.new('test_0'))
+ end
+
+ def empty_suite
+ TestSuite.new(ObjectSpace::NAME)
+ end
+
+ def test_basic_collection
+ assert_equal(full_suite("name"), @c.collect("name"))
+
+ @c.filter = []
+ assert_equal(full_suite("name"), @c.collect("name"))
+ end
+
+ def test_filtered_collection
+ @c.filter = proc{false}
+ assert_equal(empty_suite, @c.collect)
+
+ @c.filter = proc{true}
+ assert_equal(full_suite, @c.collect)
+
+ @c.filter = proc{nil}
+ assert_equal(full_suite, @c.collect)
+
+ @c.filter = [proc{false}, proc{true}]
+ assert_equal(empty_suite, @c.collect)
+
+ @c.filter = [proc{true}, proc{false}]
+ assert_equal(full_suite, @c.collect)
+
+ @c.filter = [proc{nil}, proc{false}]
+ assert_equal(empty_suite, @c.collect)
+
+ @c.filter = [proc{nil}, proc{true}]
+ assert_equal(full_suite, @c.collect)
+
+ expected = TestSuite.new(ObjectSpace::NAME)
+ expected << (TestSuite.new(@tc1.name) << @tc1.new('test_1'))
+ expected << (TestSuite.new(@tc2.name) << @tc2.new('test_0'))
+ @c.filter = proc{|test| ['test_1', 'test_0'].include?(test.method_name)}
+ assert_equal(expected, @c.collect)
+
+ expected = TestSuite.new(ObjectSpace::NAME)
+ expected << (TestSuite.new(@tc1.name) << @tc1.new('test_1'))
+ expected << (TestSuite.new(@tc2.name) << @tc2.new('test_0'))
+ @c.filter = [proc{|t| t.method_name == 'test_1' ? true : nil}, proc{|t| t.method_name == 'test_0' ? true : nil}, proc{false}]
+ assert_equal(expected, @c.collect)
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/runit/test_assert.rb b/ruby_1_8_6/test/testunit/runit/test_assert.rb
new file mode 100644
index 0000000000..a3e62b2b2d
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/runit/test_assert.rb
@@ -0,0 +1,402 @@
+# Author:: Masaki Suketa.
+# Adapted by:: Nathaniel Talbott.
+# Copyright:: Copyright (c) Masaki Suketa. All rights reserved.
+# Copyright:: Copyright (c) 2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'rubyunit'
+
+module RUNIT
+ class TargetAssert
+ include RUNIT::Assert
+ end
+
+ class TestAssert < RUNIT::TestCase
+ def setup
+ @assert = TargetAssert.new
+ @e = nil
+ end
+
+ def test_assert
+ sub_test_assert_pass(true)
+ sub_test_assert_pass(TRUE)
+ sub_test_assert_failure(false)
+ sub_test_assert_failure(FALSE)
+ sub_test_assert_failure(nil)
+ sub_test_assert_pass("")
+ sub_test_assert_pass("ok")
+ sub_test_assert_pass(0)
+ sub_test_assert_pass(1)
+ end
+
+ def test_assert_with_2_argument
+ assert_no_exception {
+ assert(true, "3")
+ }
+ assert_no_exception {
+ assert(true)
+ }
+ end
+
+ def test_assert_equal_float_0_1
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(1.4, 1.35, 0.1)
+ }
+ sub_assert_pass(assert_proc)
+ end
+
+ def test_assert_equal_float_0_5
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(1.4, 1.34, 0.5)
+ }
+ sub_assert_pass(assert_proc)
+ end
+
+ def test_assert_equal_float_0
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(1.4, 1.4, 0)
+ }
+ sub_assert_pass(assert_proc)
+ end
+
+ def test_assert_equal_float_0_raise
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(1.4, 1.34, 0)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_equal_float_0_01
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(1.4, 1.35, 0.01)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_equal_float_0_001
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(Math.sqrt(2), 1.414, 0.001)
+ }
+ sub_assert_pass(assert_proc)
+ end
+
+ def test_assert_equal_float_minus_1_0
+ assert_proc = Proc.new {
+ @assert.assert_equal_float(1.4, 1.35, -1.0)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_fail
+ except = nil
+ begin
+ @assert.assert_fail("failure")
+ rescue Exception
+ except = $!
+ end
+ assert_not_nil(except)
+ end
+
+ def sub_test_assert_pass(obj)
+ assert_proc = Proc.new {
+ @assert.assert(obj)
+ }
+ sub_assert_pass(assert_proc)
+ end
+
+ def sub_test_assert_failure(obj)
+ assert_proc = Proc.new {
+ @assert.assert(obj)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_equal
+ assert_proc = Proc.new {
+ @assert.assert_equal(2, 2)
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_equal(2, 3)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_nil
+ obj = nil
+ assert_proc = Proc.new {
+ @assert.assert_nil(obj)
+ }
+ sub_assert_pass(assert_proc)
+ obj = 'string'
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_not_nil
+ obj = 'string'
+ assert_proc = Proc.new {
+ @assert.assert_not_nil(obj)
+ }
+ sub_assert_pass(assert_proc)
+
+ obj = nil
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_operator
+ assert_proc = Proc.new {
+ @assert.assert_operator(2, :<, 3)
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_operator(2, :>, 3)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_respond_to
+ sub_test_assert_respond_to('string', 'sub', 'foo')
+ sub_test_assert_respond_to('string', :sub, :foo)
+ end
+
+ def sub_test_assert_respond_to(obj, msg, dummy_msg)
+ assert_proc = Proc.new {
+ @assert.assert_respond_to(msg, obj)
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_respond_to(dummy_msg, obj)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_send
+ assert_proc = Proc.new {
+ ary = []
+ @assert.assert_send ary, :empty?
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ ary = [2,3]
+ @assert.assert_send ary, :empty?
+ }
+ sub_assert_raise_fail(assert_proc)
+ assert_proc = Proc.new {
+ str = "abc"
+ @assert.assert_send str, :sub!, "z", "y"
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_kind_of
+ assert_proc = Proc.new {
+ @assert.assert_kind_of(String, "string")
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_kind_of(Regexp, "string")
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_instance_of
+ assert_proc = Proc.new {
+ @assert.assert_instance_of(String, "string")
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_instance_of(Object, "string")
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_match
+ assert_proc = Proc.new{
+ @assert.assert_match('foostring', /foo/)
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_match('barstring', /foo/)
+ }
+ sub_assert_raise_fail(assert_proc)
+ match = @assert.assert_match('foostring', /foo/)
+ assert_instance_of(MatchData, match)
+ assert_equal('foo', match[0])
+ end
+
+ def test_assert_matches
+ assert_proc = Proc.new{
+ @assert.assert_matches('foostring', /foo/)
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_matches('barstring', /foo/)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_not_match
+ assert_proc = Proc.new{
+ @assert.assert_not_match('barstring', /foo/)
+ }
+ sub_assert_pass(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_not_match('foostring', /foo/)
+ }
+ sub_assert_raise_fail(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_not_match('foobarbaz', /ba.+/)
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_same
+ flag = false
+ e = "foo"
+ a = e
+ assert_proc = Proc.new {@assert.assert_same(e, a)}
+ sub_assert_pass(assert_proc)
+
+ a = "foo"
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def test_assert_exception
+ assert_proc = Proc.new{
+ @assert.assert_exception(IOError) {
+ raise IOError
+ }
+ }
+ sub_assert_pass(assert_proc)
+
+ assert_proc = Proc.new{
+ @assert.assert_exception(StandardError) {
+ raise IOError
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+
+ assert_proc = Proc.new{
+ @assert.assert_exception(IOError, "Exception") {
+ raise StandardError
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+
+ assert_proc = Proc.new {
+ @assert.assert_exception(StandardError) {
+ "No Exception raised in this block"
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+
+ assert_proc = Proc.new {
+ @assert.assert_exception(StandardError) {
+ exit(33)
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+
+ t = @assert.assert_exception(IOError) {
+ raise IOError
+ }
+ assert_instance_of(IOError, t)
+ t = @assert.assert_exception(NameError) {
+ non_existent_method
+ }
+ assert_instance_of(NameError, t)
+ t = @assert.assert_exception(SystemExit) {
+ exit(33)
+ }
+ assert_instance_of(SystemExit, t)
+ end
+
+ def test_assert_no_exception
+ assert_proc = Proc.new{
+ @assert.assert_no_exception(IOError, ArgumentError) {
+ "No Exception raised in this block"
+ }
+ }
+ sub_assert_pass(assert_proc)
+
+ assert_proc = Proc.new{
+ @assert.assert_no_exception(IOError, ArgumentError) {
+ raise StandardError, "Standard Error raised"
+ }
+ }
+ sub_assert_raise_error(assert_proc)
+
+ assert_proc = Proc.new{
+ @assert.assert_no_exception(IOError, ArgumentError) {
+ raise ArgumentError, "Bad Argument"
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+
+ assert_proc = Proc.new{
+ @assert.assert_no_exception {
+ raise ArgumentError, "Bad Argument"
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+
+ assert_proc = Proc.new{
+ @assert.assert_no_exception {
+ raise NameError, "Bad Name"
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+ assert_proc = Proc.new {
+ @assert.assert_no_exception {
+ raise NoMemoryError
+ }
+ }
+ sub_assert_raise_fail(assert_proc)
+ end
+
+ def sub_assert_pass(p)
+ flag = false
+ err = nil
+ begin
+ p.call
+ flag = true
+ rescue
+ err = $!
+ flag = false
+ end
+ assert(flag, err.to_s)
+ end
+
+ def sub_assert_raise_fail(p)
+ flag = false
+ err = nil
+ begin
+ p.call
+ flag = false
+ rescue RUNIT::AssertionFailedError
+ flag = true
+ err = $!
+ rescue Exception
+ flag = false
+ err = $!
+ end
+ assert(flag, err.to_s)
+ end
+
+ def sub_assert_raise_error(p)
+ flag = false
+ err = nil
+ begin
+ p.call
+ flag = false
+ rescue RUNIT::AssertionFailedError
+ flag = false
+ err = $!
+ rescue Exception
+ flag = true
+ err = $!
+ end
+ assert(flag, err.to_s)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/runit/test_testcase.rb b/ruby_1_8_6/test/testunit/runit/test_testcase.rb
new file mode 100644
index 0000000000..f57e0386e3
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/runit/test_testcase.rb
@@ -0,0 +1,91 @@
+# Author:: Masaki Suketa.
+# Adapted by:: Nathaniel Talbott.
+# Copyright:: Copyright (c) Masaki Suketa. All rights reserved.
+# Copyright:: Copyright (c) 2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'rubyunit'
+
+module RUNIT
+ class DummyError < StandardError
+ end
+
+ class TestTestCase < RUNIT::TestCase
+ def setup
+ @dummy_testcase = Class.new(RUNIT::TestCase) do
+ def self.name
+ "DummyTestCase"
+ end
+
+ attr_reader :status, :dummy_called, :dummy2_called
+
+ def initialize(*arg)
+ super(*arg)
+ @status = 0
+ @dummy_called = false
+ @dummy2_called = false
+ end
+
+ def setup
+ @status = 1 if @status == 0
+ end
+
+ def test_dummy
+ @status = 2 if @status == 1
+ @dummy_called = true
+ end
+
+ def test_dummy2
+ @status = 2 if @status == 1
+ @dummy2_called = true
+ raise DummyError
+ end
+
+ def teardown
+ @status = 3 if @status == 2
+ end
+ end
+
+ @test1 = @dummy_testcase.new('test_dummy')
+ @test2 = @dummy_testcase.new('test_dummy2', 'TestCase')
+ end
+
+ def test_name
+ assert_equal('DummyTestCase#test_dummy', @test1.name) # The second parameter to #initialize is ignored in emulation
+ assert_equal('DummyTestCase#test_dummy2', @test2.name)
+ end
+
+ def test_run
+ result = RUNIT::TestResult.new
+ @test1.run(result)
+ assert_equal(1, result.run_count)
+ end
+
+ def test_s_suite
+ suite = @dummy_testcase.suite
+ assert_instance_of(RUNIT::TestSuite, suite)
+ assert_equal(2, suite.count_test_cases)
+ end
+
+ def test_teardown_err
+ suite = Class.new(RUNIT::TestCase) do
+ def test_foo
+ assert(false)
+ end
+
+ def test_bar
+ assert(true)
+ end
+
+ def teardown
+ raise StandardError
+ end
+ end.suite
+
+ result = RUNIT::TestResult.new
+ suite.run(result)
+ assert_equal(2, result.error_size)
+ assert_equal(1, result.failure_size)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/runit/test_testresult.rb b/ruby_1_8_6/test/testunit/runit/test_testresult.rb
new file mode 100644
index 0000000000..702b88d0c0
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/runit/test_testresult.rb
@@ -0,0 +1,144 @@
+# Author:: Masaki Suketa.
+# Adapted by:: Nathaniel Talbott.
+# Copyright:: Copyright (c) Masaki Suketa. All rights reserved.
+# Copyright:: Copyright (c) 2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'rubyunit'
+
+module RUNIT
+ class TestTestResult < RUNIT::TestCase
+ def setup
+ @result = RUNIT::TestResult.new
+
+ @normal_suite = Class::new(RUNIT::TestCase) do
+ def test_1
+ assert(true)
+ assert(true)
+ end
+ end.suite
+
+ @failure_suite = Class::new(RUNIT::TestCase) do
+ def test_1
+ assert(true)
+ assert(false)
+ end
+ end.suite
+
+ @error_suite = Class::new(RUNIT::TestCase) do
+ def setup
+ raise ScriptError
+ end
+ def test_1
+ assert(true)
+ end
+ end.suite
+
+ @multi_failure_suite = Class::new(RUNIT::TestCase) do
+ def test1
+ assert(false)
+ end
+ def test2
+ assert(false)
+ end
+ def test3
+ assert(false)
+ end
+ end.suite
+
+ @with_error_suite = Class::new(RUNIT::TestCase) do
+ def test1
+ raise StandardError
+ end
+ end.suite
+
+ @multi_error_suite = Class::new(RUNIT::TestCase) do
+ def test1
+ raise StandardError
+ end
+ def test2
+ raise StandardError
+ end
+ def test3
+ raise StandardError
+ end
+ end.suite
+
+ @multi_suite = Class::new(RUNIT::TestCase) do
+ def test_1
+ assert(true)
+ assert(true)
+ end
+ def test_2
+ assert(true)
+ end
+ def test_3
+ assert(true)
+ assert(false)
+ assert(true)
+ end
+ end.suite
+ end
+
+ def test_error_size
+ @normal_suite.run(@result)
+ assert_equal(0, @result.error_size)
+ @with_error_suite.run(@result)
+ assert_equal(1, @result.error_size)
+ @multi_error_suite.run(@result)
+ assert_equal(4, @result.error_size)
+ end
+
+ def test_errors
+ @normal_suite.run(@result)
+ assert_equal(0, @result.errors.size)
+ end
+
+ def test_failure_size
+ @normal_suite.run(@result)
+ assert_equal(0, @result.failure_size)
+ @failure_suite.run(@result)
+ assert_equal(1, @result.failure_size)
+ @multi_failure_suite.run(@result)
+ assert_equal(4, @result.failure_size)
+ end
+
+ def test_failures
+ @normal_suite.run(@result)
+ assert_equal(0, @result.failures.size)
+ @failure_suite.run(@result)
+ assert_equal(1, @result.failures.size)
+ @multi_failure_suite.run(@result)
+ assert_equal(4, @result.failures.size)
+ end
+
+ def test_run_no_exception
+ assert_no_exception {
+ @error_suite.run(@result)
+ }
+ end
+
+ def test_run_asserts
+ @normal_suite.run(@result)
+ assert_equal(2, @result.run_asserts)
+ end
+
+ def test_run_asserts2
+ @failure_suite.run(@result)
+ assert_equal(2, @result.run_asserts)
+ end
+
+ def test_run_tests
+ assert_equal(0, @result.run_tests)
+ @normal_suite.run(@result)
+ assert_equal(1, @result.run_tests)
+ @multi_suite.run(@result)
+ assert_equal(4, @result.run_tests)
+ end
+
+ def test_succeed?
+ @normal_suite.run(@result)
+ assert(@result.succeed?)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/runit/test_testsuite.rb b/ruby_1_8_6/test/testunit/runit/test_testsuite.rb
new file mode 100644
index 0000000000..58702d3efe
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/runit/test_testsuite.rb
@@ -0,0 +1,49 @@
+# Author:: Masaki Suketa.
+# Adapted by:: Nathaniel Talbott.
+# Copyright:: Copyright (c) Masaki Suketa. All rights reserved.
+# Copyright:: Copyright (c) 2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'rubyunit'
+
+module RUNIT
+ class TestTestSuite < RUNIT::TestCase
+ def setup
+ @testsuite = RUNIT::TestSuite.new
+ @dummy_test = Class.new(RUNIT::TestCase) do
+ def test_foo
+ end
+ def test_bar
+ end
+ end
+ @dummy_empty_test = Class.new(RUNIT::TestCase){}
+ end
+
+ def test_count_test_cases
+ assert_equal(0, @testsuite.count_test_cases)
+
+ @testsuite.add(@dummy_empty_test.suite)
+ assert_equal(0, @testsuite.count_test_cases)
+
+ @testsuite.add(@dummy_test.suite)
+ assert_equal(2, @testsuite.count_test_cases)
+
+ @testsuite.add(@dummy_test.suite)
+ assert_equal(4, @testsuite.count_test_cases)
+
+ dummytest_foo = @dummy_test.new('test_foo')
+ @testsuite.add(dummytest_foo)
+ assert_equal(5, @testsuite.count_test_cases)
+ end
+
+ def test_add
+ @testsuite.add(@dummy_empty_test.suite)
+ assert_equal(0, @testsuite.size)
+ assert_equal(0, @testsuite.count_test_cases)
+
+ @testsuite.add(@dummy_test.suite)
+ assert_equal(2, @testsuite.size)
+ assert_equal(2, @testsuite.count_test_cases)
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/test_assertions.rb b/ruby_1_8_6/test/testunit/test_assertions.rb
new file mode 100644
index 0000000000..8ccd2a81bd
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/test_assertions.rb
@@ -0,0 +1,528 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+
+module Test
+ module Unit
+ class TC_Assertions < TestCase
+ def check(value, message="")
+ add_assertion
+ if (!value)
+ raise AssertionFailedError.new(message)
+ end
+ end
+
+ def check_assertions(expect_fail, expected_message="", return_value_expected=false)
+ @actual_assertion_count = 0
+ failed = true
+ actual_message = nil
+ @catch_assertions = true
+ return_value = nil
+ begin
+ return_value = yield
+ failed = false
+ rescue AssertionFailedError => error
+ actual_message = error.message
+ end
+ @catch_assertions = false
+ check(expect_fail == failed, (expect_fail ? "Should have failed, but didn't" : "Should not have failed, but did with message\n<#{actual_message}>"))
+ check(1 == @actual_assertion_count, "Should have made one assertion but made <#{@actual_assertion_count}>")
+ if (expect_fail)
+ case expected_message
+ when String
+ check(actual_message == expected_message, "Should have the correct message.\n<#{expected_message.inspect}> expected but was\n<#{actual_message.inspect}>")
+ when Regexp
+ check(actual_message =~ expected_message, "The message should match correctly.\n</#{expected_message.source}/> expected to match\n<#{actual_message.inspect}>")
+ else
+ check(false, "Incorrect expected message type in assert_nothing_failed")
+ end
+ else
+ if (!return_value_expected)
+ check(return_value.nil?, "Should not return a value but returned <#{return_value}>")
+ else
+ check(!return_value.nil?, "Should return a value")
+ end
+ end
+ return return_value
+ end
+
+ def check_nothing_fails(return_value_expected=false, &proc)
+ check_assertions(false, "", return_value_expected, &proc)
+ end
+
+ def check_fails(expected_message="", &proc)
+ check_assertions(true, expected_message, &proc)
+ end
+
+ def test_assert_block
+ check_nothing_fails {
+ assert_block {true}
+ }
+ check_nothing_fails {
+ assert_block("successful assert_block") {true}
+ }
+ check_nothing_fails {
+ assert_block("successful assert_block") {true}
+ }
+ check_fails("assert_block failed.") {
+ assert_block {false}
+ }
+ check_fails("failed assert_block") {
+ assert_block("failed assert_block") {false}
+ }
+ end
+
+ def test_assert
+ check_nothing_fails{assert("a")}
+ check_nothing_fails{assert(true)}
+ check_nothing_fails{assert(true, "successful assert")}
+ check_fails("<nil> is not true."){assert(nil)}
+ check_fails("<false> is not true."){assert(false)}
+ check_fails("failed assert.\n<false> is not true."){assert(false, "failed assert")}
+ end
+
+ def test_assert_equal
+ check_nothing_fails {
+ assert_equal("string1", "string1")
+ }
+ check_nothing_fails {
+ assert_equal( "string1", "string1", "successful assert_equal")
+ }
+ check_nothing_fails {
+ assert_equal("string1", "string1", "successful assert_equal")
+ }
+ check_fails(%Q{<"string1"> expected but was\n<"string2">.}) {
+ assert_equal("string1", "string2")
+ }
+ check_fails(%Q{failed assert_equal.\n<"string1"> expected but was\n<"string2">.}) {
+ assert_equal("string1", "string2", "failed assert_equal")
+ }
+ check_fails(%Q{<"1"> expected but was\n<1>.}) do
+ assert_equal("1", 1)
+ end
+ end
+
+ def test_assert_raise
+ return_value = nil
+ check_nothing_fails(true) {
+ return_value = assert_raise(RuntimeError) {
+ raise "Error"
+ }
+ }
+ check(return_value.kind_of?(Exception), "Should have returned the exception from a successful assert_raise")
+ check(return_value.message == "Error", "Should have returned the correct exception from a successful assert_raise")
+ check_nothing_fails(true) {
+ assert_raise(ArgumentError, "successful assert_raise") {
+ raise ArgumentError.new("Error")
+ }
+ }
+ check_nothing_fails(true) {
+ assert_raise(RuntimeError) {
+ raise "Error"
+ }
+ }
+ check_nothing_fails(true) {
+ assert_raise(RuntimeError, "successful assert_raise") {
+ raise "Error"
+ }
+ }
+ check_fails("<RuntimeError> exception expected but none was thrown.") {
+ assert_raise(RuntimeError) {
+ 1 + 1
+ }
+ }
+ check_fails(%r{\Afailed assert_raise.\n<ArgumentError> exception expected but was\nClass: <RuntimeError>\nMessage: <"Error">\n---Backtrace---\n.+\n---------------\Z}m) {
+ assert_raise(ArgumentError, "failed assert_raise") {
+ raise "Error"
+ }
+ }
+ check_fails("Should expect a class of exception, Object.\n<false> is not true.") {
+ assert_nothing_raised(Object) {
+ 1 + 1
+ }
+ }
+
+ exceptions = [ArgumentError, TypeError]
+ modules = [Math, Comparable]
+ rescues = exceptions + modules
+ exceptions.each do |exc|
+ check_nothing_fails(true) {
+ return_value = assert_raise(*rescues) {
+ raise exc, "Error"
+ }
+ }
+ check(return_value.instance_of?(exc), "Should have returned #{exc} but was #{return_value.class}")
+ check(return_value.message == "Error", "Should have returned the correct exception from a successful assert_raise")
+ end
+ modules.each do |mod|
+ check_nothing_fails(true) {
+ return_value = assert_raise(*rescues) {
+ raise Exception.new("Error").extend(mod)
+ }
+ }
+ check(mod === return_value, "Should have returned #{mod}")
+ check(return_value.message == "Error", "Should have returned the correct exception from a successful assert_raise")
+ end
+ check_fails("<[ArgumentError, TypeError, Math, Comparable]> exception expected but none was thrown.") {
+ assert_raise(*rescues) {
+ 1 + 1
+ }
+ }
+ check_fails(%r{\Afailed assert_raise.
+<\[ArgumentError, TypeError\]> exception expected but was
+Class: <RuntimeError>
+Message: <"Error">
+---Backtrace---
+.+
+---------------\Z}m) {
+ assert_raise(ArgumentError, TypeError, "failed assert_raise") {
+ raise "Error"
+ }
+ }
+ end
+
+ def test_assert_instance_of
+ check_nothing_fails {
+ assert_instance_of(String, "string")
+ }
+ check_nothing_fails {
+ assert_instance_of(String, "string", "successful assert_instance_of")
+ }
+ check_nothing_fails {
+ assert_instance_of(String, "string", "successful assert_instance_of")
+ }
+ check_fails(%Q{<"string"> expected to be an instance of\n<Hash> but was\n<String>.}) {
+ assert_instance_of(Hash, "string")
+ }
+ check_fails(%Q{failed assert_instance_of.\n<"string"> expected to be an instance of\n<Hash> but was\n<String>.}) {
+ assert_instance_of(Hash, "string", "failed assert_instance_of")
+ }
+ end
+
+ def test_assert_nil
+ check_nothing_fails {
+ assert_nil(nil)
+ }
+ check_nothing_fails {
+ assert_nil(nil, "successful assert_nil")
+ }
+ check_nothing_fails {
+ assert_nil(nil, "successful assert_nil")
+ }
+ check_fails(%Q{<nil> expected but was\n<"string">.}) {
+ assert_nil("string")
+ }
+ check_fails(%Q{failed assert_nil.\n<nil> expected but was\n<"string">.}) {
+ assert_nil("string", "failed assert_nil")
+ }
+ end
+
+ def test_assert_not_nil
+ check_nothing_fails{assert_not_nil(false)}
+ check_nothing_fails{assert_not_nil(false, "message")}
+ check_fails("<nil> expected to not be nil."){assert_not_nil(nil)}
+ check_fails("message.\n<nil> expected to not be nil.") {assert_not_nil(nil, "message")}
+ end
+
+ def test_assert_kind_of
+ check_nothing_fails {
+ assert_kind_of(Module, Array)
+ }
+ check_nothing_fails {
+ assert_kind_of(Object, "string", "successful assert_kind_of")
+ }
+ check_nothing_fails {
+ assert_kind_of(Object, "string", "successful assert_kind_of")
+ }
+ check_nothing_fails {
+ assert_kind_of(Comparable, 1)
+ }
+ check_fails(%Q{<"string">\nexpected to be kind_of?\n<Class> but was\n<String>.}) {
+ assert_kind_of(Class, "string")
+ }
+ check_fails(%Q{failed assert_kind_of.\n<"string">\nexpected to be kind_of?\n<Class> but was\n<String>.}) {
+ assert_kind_of(Class, "string", "failed assert_kind_of")
+ }
+ end
+
+ def test_assert_match
+ check_nothing_fails {
+ assert_match(/strin./, "string")
+ }
+ check_nothing_fails {
+ assert_match("strin", "string")
+ }
+ check_nothing_fails {
+ assert_match(/strin./, "string", "successful assert_match")
+ }
+ check_nothing_fails {
+ assert_match(/strin./, "string", "successful assert_match")
+ }
+ check_fails(%Q{<"string"> expected to be =~\n</slin./>.}) {
+ assert_match(/slin./, "string")
+ }
+ check_fails(%Q{<"string"> expected to be =~\n</strin\\./>.}) {
+ assert_match("strin.", "string")
+ }
+ check_fails(%Q{failed assert_match.\n<"string"> expected to be =~\n</slin./>.}) {
+ assert_match(/slin./, "string", "failed assert_match")
+ }
+ end
+
+ def test_assert_same
+ thing = "thing"
+ check_nothing_fails {
+ assert_same(thing, thing)
+ }
+ check_nothing_fails {
+ assert_same(thing, thing, "successful assert_same")
+ }
+ check_nothing_fails {
+ assert_same(thing, thing, "successful assert_same")
+ }
+ thing2 = "thing"
+ check_fails(%Q{<"thing">\nwith id <#{thing.__id__}> expected to be equal? to\n<"thing">\nwith id <#{thing2.__id__}>.}) {
+ assert_same(thing, thing2)
+ }
+ check_fails(%Q{failed assert_same.\n<"thing">\nwith id <#{thing.__id__}> expected to be equal? to\n<"thing">\nwith id <#{thing2.__id__}>.}) {
+ assert_same(thing, thing2, "failed assert_same")
+ }
+ end
+
+ def test_assert_nothing_raised
+ check_nothing_fails {
+ assert_nothing_raised {
+ 1 + 1
+ }
+ }
+ check_nothing_fails {
+ assert_nothing_raised("successful assert_nothing_raised") {
+ 1 + 1
+ }
+ }
+ check_nothing_fails {
+ assert_nothing_raised("successful assert_nothing_raised") {
+ 1 + 1
+ }
+ }
+ check_nothing_fails {
+ begin
+ assert_nothing_raised(RuntimeError, StandardError, Comparable, "successful assert_nothing_raised") {
+ raise ZeroDivisionError.new("ArgumentError")
+ }
+ rescue ZeroDivisionError
+ end
+ }
+ check_fails("Should expect a class of exception, Object.\n<false> is not true.") {
+ assert_nothing_raised(Object) {
+ 1 + 1
+ }
+ }
+ check_fails(%r{\AException raised:\nClass: <RuntimeError>\nMessage: <"Error">\n---Backtrace---\n.+\n---------------\Z}m) {
+ assert_nothing_raised {
+ raise "Error"
+ }
+ }
+ check_fails(%r{\Afailed assert_nothing_raised\.\nException raised:\nClass: <RuntimeError>\nMessage: <"Error">\n---Backtrace---\n.+\n---------------\Z}m) {
+ assert_nothing_raised("failed assert_nothing_raised") {
+ raise "Error"
+ }
+ }
+ check_fails(%r{\AException raised:\nClass: <RuntimeError>\nMessage: <"Error">\n---Backtrace---\n.+\n---------------\Z}m) {
+ assert_nothing_raised(StandardError, RuntimeError) {
+ raise "Error"
+ }
+ }
+ check_fails("Failure.") do
+ assert_nothing_raised do
+ flunk("Failure")
+ end
+ end
+ end
+
+ def test_flunk
+ check_fails("Flunked.") {
+ flunk
+ }
+ check_fails("flunk message.") {
+ flunk("flunk message")
+ }
+ end
+
+ def test_assert_not_same
+ thing = "thing"
+ thing2 = "thing"
+ check_nothing_fails {
+ assert_not_same(thing, thing2)
+ }
+ check_nothing_fails {
+ assert_not_same(thing, thing2, "message")
+ }
+ check_fails(%Q{<"thing">\nwith id <#{thing.__id__}> expected to not be equal? to\n<"thing">\nwith id <#{thing.__id__}>.}) {
+ assert_not_same(thing, thing)
+ }
+ check_fails(%Q{message.\n<"thing">\nwith id <#{thing.__id__}> expected to not be equal? to\n<"thing">\nwith id <#{thing.__id__}>.}) {
+ assert_not_same(thing, thing, "message")
+ }
+ end
+
+ def test_assert_not_equal
+ check_nothing_fails {
+ assert_not_equal("string1", "string2")
+ }
+ check_nothing_fails {
+ assert_not_equal("string1", "string2", "message")
+ }
+ check_fails(%Q{<"string"> expected to be != to\n<"string">.}) {
+ assert_not_equal("string", "string")
+ }
+ check_fails(%Q{message.\n<"string"> expected to be != to\n<"string">.}) {
+ assert_not_equal("string", "string", "message")
+ }
+ end
+
+ def test_assert_no_match
+ check_nothing_fails{assert_no_match(/sling/, "string")}
+ check_nothing_fails{assert_no_match(/sling/, "string", "message")}
+ check_fails(%Q{The first argument to assert_no_match should be a Regexp.\n<"asdf"> expected to be an instance of\n<Regexp> but was\n<String>.}) do
+ assert_no_match("asdf", "asdf")
+ end
+ check_fails(%Q{</string/> expected to not match\n<"string">.}) do
+ assert_no_match(/string/, "string")
+ end
+ check_fails(%Q{message.\n</string/> expected to not match\n<"string">.}) do
+ assert_no_match(/string/, "string", "message")
+ end
+ end
+
+ def test_assert_throws
+ check_nothing_fails {
+ assert_throws(:thing, "message") {
+ throw :thing
+ }
+ }
+ check_fails("message.\n<:thing> expected to be thrown but\n<:thing2> was thrown.") {
+ assert_throws(:thing, "message") {
+ throw :thing2
+ }
+ }
+ check_fails("message.\n<:thing> should have been thrown.") {
+ assert_throws(:thing, "message") {
+ 1 + 1
+ }
+ }
+ end
+
+ def test_assert_nothing_thrown
+ check_nothing_fails {
+ assert_nothing_thrown("message") {
+ 1 + 1
+ }
+ }
+ check_fails("message.\n<:thing> was thrown when nothing was expected.") {
+ assert_nothing_thrown("message") {
+ throw :thing
+ }
+ }
+ end
+
+ def test_assert_operator
+ check_nothing_fails {
+ assert_operator("thing", :==, "thing", "message")
+ }
+ check_fails(%Q{<0.15>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to?(:to_str).}) do
+ assert_operator("thing", 0.15, "thing")
+ end
+ check_fails(%Q{message.\n<"thing1"> expected to be\n==\n<"thing2">.}) {
+ assert_operator("thing1", :==, "thing2", "message")
+ }
+ end
+
+ def test_assert_respond_to
+ check_nothing_fails {
+ assert_respond_to("thing", :to_s, "message")
+ }
+ check_nothing_fails {
+ assert_respond_to("thing", "to_s", "message")
+ }
+ check_fails("<0.15>\ngiven as the method name argument to #assert_respond_to must be a Symbol or #respond_to?(:to_str).") {
+ assert_respond_to("thing", 0.15)
+ }
+ check_fails("message.\n<:symbol>\nof type <Symbol>\nexpected to respond_to?<:non_existent>.") {
+ assert_respond_to(:symbol, :non_existent, "message")
+ }
+ end
+
+ def test_assert_in_delta
+ check_nothing_fails {
+ assert_in_delta(1.4, 1.4, 0)
+ }
+ check_nothing_fails {
+ assert_in_delta(0.5, 0.4, 0.1, "message")
+ }
+ check_nothing_fails {
+ float_thing = Object.new
+ def float_thing.to_f
+ 0.2
+ end
+ assert_in_delta(0.1, float_thing, 0.1)
+ }
+ check_fails("message.\n<0.5> and\n<0.4> expected to be within\n<0.05> of each other.") {
+ assert_in_delta(0.5, 0.4, 0.05, "message")
+ }
+ check_fails(%r{The arguments must respond to to_f; the first float did not\.\n<.+>\nof type <Object>\nexpected to respond_to\?<:to_f>.}) {
+ assert_in_delta(Object.new, 0.4, 0.1)
+ }
+ check_fails("The delta should not be negative.\n<-0.1> expected to be\n>=\n<0.0>.") {
+ assert_in_delta(0.5, 0.4, -0.1, "message")
+ }
+ end
+
+ def test_assert_send
+ object = Object.new
+ class << object
+ private
+ def return_argument(argument, bogus)
+ return argument
+ end
+ end
+ check_nothing_fails {
+ assert_send([object, :return_argument, true, "bogus"], "message")
+ }
+ check_fails(%r{\Amessage\.\n<.+> expected to respond to\n<return_argument\(\[false, "bogus"\]\)> with a true value.\Z}) {
+ assert_send([object, :return_argument, false, "bogus"], "message")
+ }
+ end
+
+ def test_condition_invariant
+ object = Object.new
+ def object.inspect
+ @changed = true
+ end
+ def object.==(other)
+ @changed ||= false
+ return (!@changed)
+ end
+ check_nothing_fails {
+ assert_equal(object, object, "message")
+ }
+ end
+
+ def add_failure(message, location=caller)
+ if (!@catch_assertions)
+ super
+ end
+ end
+
+ def add_assertion
+ if (!@catch_assertions)
+ super
+ else
+ @actual_assertion_count += 1
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/test_error.rb b/ruby_1_8_6/test/testunit/test_error.rb
new file mode 100644
index 0000000000..56b275b362
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/test_error.rb
@@ -0,0 +1,26 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+
+module Test
+ module Unit
+ class TC_Error < TestCase
+ TF_Exception = Struct.new('TF_Exception', :message, :backtrace)
+ def test_display
+ ex = TF_Exception.new("message1\nmessage2", ['line1', 'line2'])
+ e = Error.new("name", ex)
+ assert_equal("name: #{TF_Exception.name}: message1", e.short_display)
+ assert_equal(<<EOM.strip, e.long_display)
+Error:
+name:
+Struct::TF_Exception: message1
+message2
+ line1
+ line2
+EOM
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/test_failure.rb b/ruby_1_8_6/test/testunit/test_failure.rb
new file mode 100644
index 0000000000..164f942476
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/test_failure.rb
@@ -0,0 +1,33 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2003 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+require 'test/unit/failure'
+
+module Test::Unit
+ class TestFailure < TestCase
+ def test_display
+ f = Failure.new("name", [%q{location:1 in 'l'}], "message1\nmessage2")
+ assert_equal("name: message1", f.short_display)
+ assert_equal(<<EOM.strip, f.long_display)
+Failure:
+name [location:1]:
+message1
+message2
+EOM
+
+ f = Failure.new("name", [%q{location1:2 in 'l1'}, 'location2:1', %q{location3:3 in 'l3'}], "message1\nmessage2")
+ assert_equal("name: message1", f.short_display)
+ assert_equal(<<EOM.strip, f.long_display)
+Failure:
+name
+ [location1:2 in 'l1'
+ location2:1
+ location3:3 in 'l3']:
+message1
+message2
+EOM
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/test_testcase.rb b/ruby_1_8_6/test/testunit/test_testcase.rb
new file mode 100644
index 0000000000..2934a92fef
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/test_testcase.rb
@@ -0,0 +1,275 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+
+module Test
+ module Unit
+ class TC_TestCase < TestCase
+ def test_creation
+ tc = Class.new(TestCase) do
+ def test_with_arguments(arg1, arg2)
+ end
+ end
+
+ caught = true
+ catch(:invalid_test) do
+ tc.new(:test_with_arguments)
+ caught = false
+ end
+ check("Should have caught an invalid test when there are arguments", caught)
+
+ caught = true
+ catch(:invalid_test) do
+ tc.new(:non_existent_test)
+ caught = false
+ end
+ check("Should have caught an invalid test when the method does not exist", caught)
+ end
+
+ def setup
+ @tc_failure_error = Class.new(TestCase) do
+ def test_failure
+ assert_block("failure") { false }
+ end
+ def test_error
+ 1 / 0
+ end
+ def test_nested_failure
+ nested
+ end
+ def nested
+ assert_block("nested"){false}
+ end
+ def return_passed?
+ return passed?
+ end
+ end
+
+ def @tc_failure_error.name
+ "TC_FailureError"
+ end
+ end
+
+ def test_add_failed_assertion
+ test_case = @tc_failure_error.new(:test_failure)
+ check("passed? should start out true", test_case.return_passed?)
+ result = TestResult.new
+ called = false
+ result.add_listener(TestResult::FAULT) {
+ | fault |
+ check("Should have a Failure", fault.instance_of?(Failure))
+ check("The Failure should have the correct message", "failure" == fault.message)
+ check("The Failure should have the correct test_name (was <#{fault.test_name}>)", fault.test_name == "test_failure(TC_FailureError)")
+ r = /\A.*#{Regexp.escape(File.basename(__FILE__))}:\d+:in `test_failure'\Z/
+
+ location = fault.location
+ check("The location should be an array", location.kind_of?(Array))
+ check("The location should have two lines (was: <#{location.inspect}>)", location.size == 2)
+ check("The Failure should have the correct location (was <#{location[0].inspect}>, expected <#{r.inspect}>)", r =~ location[0])
+ called = true
+ }
+ progress = []
+ test_case.run(result) { |*arguments| progress << arguments }
+ check("The failure should have triggered the listener", called)
+ check("The failure should have set passed?", !test_case.return_passed?)
+ check("The progress block should have been updated correctly", [[TestCase::STARTED, test_case.name], [TestCase::FINISHED, test_case.name]] == progress)
+ end
+
+ def test_add_failure_nested
+ test_case = @tc_failure_error.new(:test_nested_failure)
+ check("passed? should start out true", test_case.return_passed?)
+
+ result = TestResult.new
+ called = false
+ result.add_listener(TestResult::FAULT) {
+ | fault |
+ check("Should have a Failure", fault.instance_of?(Failure))
+ check("The Failure should have the correct message", "nested" == fault.message)
+ check("The Failure should have the correct test_name (was <#{fault.test_name}>)", fault.test_name == "test_nested_failure(TC_FailureError)")
+ r =
+
+ location = fault.location
+ check("The location should be an array", location.kind_of?(Array))
+ check("The location should have the correct number of lines (was: <#{location.inspect}>)", location.size == 3)
+ check("The Failure should have the correct location (was <#{location[0].inspect}>)", /\A.*#{Regexp.escape(File.basename(__FILE__))}:\d+:in `nested'\Z/ =~ location[0])
+ check("The Failure should have the correct location (was <#{location[1].inspect}>)", /\A.*#{Regexp.escape(File.basename(__FILE__))}:\d+:in `test_nested_failure'\Z/ =~ location[1])
+ called = true
+ }
+ test_case.run(result){}
+ check("The failure should have triggered the listener", called)
+ end
+
+ def test_add_error
+ test_case = @tc_failure_error.new(:test_error)
+ check("passed? should start out true", test_case.return_passed?)
+ result = TestResult.new
+ called = false
+ result.add_listener(TestResult::FAULT) {
+ | fault |
+ check("Should have a TestError", fault.instance_of?(Error))
+ check("The Error should have the correct message", "ZeroDivisionError: divided by 0" == fault.message)
+ check("The Error should have the correct test_name", "test_error(TC_FailureError)" == fault.test_name)
+ check("The Error should have the correct exception", fault.exception.instance_of?(ZeroDivisionError))
+ called = true
+ }
+ test_case.run(result) {}
+ check("The error should have triggered the listener", called)
+ check("The error should have set passed?", !test_case.return_passed?)
+ end
+
+ def test_no_tests
+ suite = TestCase.suite
+ check("Should have a test suite", suite.instance_of?(TestSuite))
+ check("Should have one test", suite.size == 1)
+ check("Should have the default test", suite.tests.first.name == "default_test(Test::Unit::TestCase)")
+
+ result = TestResult.new
+ suite.run(result) {}
+ check("Should have had one test run", result.run_count == 1)
+ check("Should have had one test failure", result.failure_count == 1)
+ check("Should have had no errors", result.error_count == 0)
+ end
+
+ def test_suite
+ tc = Class.new(TestCase) do
+ def test_succeed
+ assert_block {true}
+ end
+ def test_fail
+ assert_block {false}
+ end
+ def test_error
+ 1/0
+ end
+ def dont_run
+ assert_block {true}
+ end
+ def test_dont_run(argument)
+ assert_block {true}
+ end
+ def test
+ assert_block {true}
+ end
+ end
+
+ suite = tc.suite
+ check("Should have a test suite", suite.instance_of?(TestSuite))
+ check("Should have three tests", suite.size == 3)
+
+ result = TestResult.new
+ suite.run(result) {}
+ check("Should have had three test runs", result.run_count == 3)
+ check("Should have had one test failure", result.failure_count == 1)
+ check("Should have had one test error", result.error_count == 1)
+ end
+
+
+ def test_setup_teardown
+ tc = Class.new(TestCase) do
+ attr_reader(:setup_called, :teardown_called)
+ def initialize(test)
+ super(test)
+ @setup_called = false
+ @teardown_called = false
+ end
+ def setup
+ @setup_called = true
+ end
+ def teardown
+ @teardown_called = true
+ end
+ def test_succeed
+ assert_block {true}
+ end
+ def test_fail
+ assert_block {false}
+ end
+ def test_error
+ raise "Error!"
+ end
+ end
+ result = TestResult.new
+
+ test = tc.new(:test_succeed)
+ test.run(result) {}
+ check("Should have called setup the correct number of times", test.setup_called)
+ check("Should have called teardown the correct number of times", test.teardown_called)
+
+ test = tc.new(:test_fail)
+ test.run(result) {}
+ check("Should have called setup the correct number of times", test.setup_called)
+ check("Should have called teardown the correct number of times", test.teardown_called)
+
+ test = tc.new(:test_error)
+ test.run(result) {}
+ check("Should have called setup the correct number of times", test.setup_called)
+ check("Should have called teardown the correct number of times", test.teardown_called)
+
+ check("Should have had two test runs", result.run_count == 3)
+ check("Should have had a test failure", result.failure_count == 1)
+ check("Should have had a test error", result.error_count == 1)
+ end
+
+ def test_assertion_failed_not_called
+ tc = Class.new(TestCase) do
+ def test_thing
+ raise AssertionFailedError.new
+ end
+ end
+
+ suite = tc.suite
+ check("Should have one test", suite.size == 1)
+ result = TestResult.new
+ suite.run(result) {}
+ check("Should have had one test run", result.run_count == 1)
+ check("Should have had one assertion failure", result.failure_count == 1)
+ check("Should not have any assertion errors but had #{result.error_count}", result.error_count == 0)
+ end
+
+ def test_equality
+ tc1 = Class.new(TestCase) do
+ def test_1
+ end
+ def test_2
+ end
+ end
+
+ tc2 = Class.new(TestCase) do
+ def test_1
+ end
+ end
+
+ test1 = tc1.new('test_1')
+ test2 = tc1.new('test_1')
+ check("Should be equal", test1 == test2)
+ check("Should be equal", test2 == test1)
+
+ test1 = tc1.new('test_2')
+ check("Should not be equal", test1 != test2)
+ check("Should not be equal", test2 != test1)
+
+ test2 = tc1.new('test_2')
+ check("Should be equal", test1 == test2)
+ check("Should be equal", test2 == test1)
+
+ test1 = tc1.new('test_1')
+ test2 = tc2.new('test_1')
+ check("Should not be equal", test1 != test2)
+ check("Should not be equal", test2 != test1)
+
+
+ check("Should not be equal", test1 != Object.new)
+ check("Should not be equal", Object.new != test1)
+ end
+
+ def check(message, passed)
+ @_result.add_assertion
+ if ! passed
+ raise AssertionFailedError.new(message)
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/test_testresult.rb b/ruby_1_8_6/test/testunit/test_testresult.rb
new file mode 100644
index 0000000000..95d631a082
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/test_testresult.rb
@@ -0,0 +1,104 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit/testcase'
+require 'test/unit/testresult'
+
+module Test
+ module Unit
+ class TC_TestResult < TestCase
+ def setup
+ @my_result = TestResult.new
+ @my_result.add_assertion()
+ @my_result.add_failure("")
+ @my_result.add_error("")
+ end
+ def test_result_changed_notification
+ called1 = false
+ @my_result.add_listener( TestResult::CHANGED) {
+ |result|
+ assert_block("The result should be correct") { result == @my_result }
+ called1 = true
+ }
+ @my_result.add_assertion
+ assert_block("Should have been notified when the assertion happened") { called1 }
+
+ called1, called2 = false, false
+ @my_result.add_listener( TestResult::CHANGED) {
+ |result|
+ assert_block("The result should be correct") { result == @my_result }
+ called2 = true
+ }
+ @my_result.add_assertion
+ assert_block("Both listeners should have been notified for a success") { called1 && called2 }
+
+ called1, called2 = false, false
+ @my_result.add_failure("")
+ assert_block("Both listeners should have been notified for a failure") { called1 && called2 }
+
+ called1, called2 = false, false
+ @my_result.add_error("")
+ assert_block("Both listeners should have been notified for an error") { called1 && called2 }
+
+ called1, called2 = false, false
+ @my_result.add_run
+ assert_block("Both listeners should have been notified for a run") { called1 && called2 }
+ end
+ def test_fault_notification
+ called1 = false
+ fault = "fault"
+ @my_result.add_listener(TestResult::FAULT) {
+ | passed_fault |
+ assert_block("The fault should be correct") { passed_fault == fault }
+ called1 = true
+ }
+
+ @my_result.add_assertion
+ assert_block("Should not have been notified when the assertion happened") { !called1 }
+
+ @my_result.add_failure(fault)
+ assert_block("Should have been notified when the failure happened") { called1 }
+
+ called1, called2 = false, false
+ @my_result.add_listener(TestResult::FAULT) {
+ | passed_fault |
+ assert_block("The fault should be correct") { passed_fault == fault }
+ called2 = true
+ }
+
+ @my_result.add_assertion
+ assert_block("Neither listener should have been notified for a success") { !(called1 || called2) }
+
+ called1, called2 = false, false
+ @my_result.add_failure(fault)
+ assert_block("Both listeners should have been notified for a failure") { called1 && called2 }
+
+ called1, called2 = false, false
+ @my_result.add_error(fault)
+ assert_block("Both listeners should have been notified for an error") { called1 && called2 }
+
+ called1, called2 = false, false
+ @my_result.add_run
+ assert_block("Neither listener should have been notified for a run") { !(called1 || called2) }
+ end
+ def test_passed?
+ result = TestResult.new
+ assert(result.passed?, "An empty result should have passed")
+
+ result.add_assertion
+ assert(result.passed?, "Adding an assertion should not cause the result to not pass")
+
+ result.add_run
+ assert(result.passed?, "Adding a run should not cause the result to not pass")
+
+ result.add_failure("")
+ assert(!result.passed?, "Adding a failed assertion should cause the result to not pass")
+
+ result = TestResult.new
+ result.add_error("")
+ assert(!result.passed?, "Adding an error should cause the result to not pass")
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/test_testsuite.rb b/ruby_1_8_6/test/testunit/test_testsuite.rb
new file mode 100644
index 0000000000..5f6631d3eb
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/test_testsuite.rb
@@ -0,0 +1,129 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+
+module Test
+ module Unit
+ class TC_TestSuite < TestCase
+ def setup
+ @testcase1 = Class.new(TestCase) do
+ def test_succeed1
+ assert_block { true }
+ end
+ def test_fail
+ assert_block { false }
+ end
+ end
+
+ @testcase2 = Class.new(TestCase) do
+ def test_succeed2
+ assert_block { true }
+ end
+ def test_error
+ raise
+ end
+ end
+ end
+
+ def test_add
+ s = TestSuite.new
+ assert_equal(s, s << self.class.new("test_add"))
+ end
+
+ def test_delete
+ s = TestSuite.new
+ t1 = self.class.new("test_delete")
+ s << t1
+ t2 = self.class.new("test_add")
+ s << t2
+ assert_equal(t1, s.delete(t1))
+ assert_nil(s.delete(t1))
+ assert_equal(TestSuite.new << t2, s)
+ end
+
+ def test_size
+ suite = TestSuite.new
+ suite2 = TestSuite.new
+ suite2 << self.class.new("test_size")
+ suite << suite2
+ suite << self.class.new("test_size")
+ assert_equal(2, suite.size, "The count should be correct")
+ end
+
+ def test_run
+ progress = []
+ suite = @testcase1.suite
+ result = TestResult.new
+ suite.run(result) { |*values| progress << values }
+
+ assert_equal(2, result.run_count, "Should have had four test runs")
+ assert_equal(1, result.failure_count, "Should have had one test failure")
+ assert_equal(0, result.error_count, "Should have had one test error")
+ assert_equal([[TestSuite::STARTED, suite.name],
+ [TestCase::STARTED, "test_fail(#{suite.name})"],
+ [TestCase::FINISHED, "test_fail(#{suite.name})"],
+ [TestCase::STARTED, "test_succeed1(#{suite.name})"],
+ [TestCase::FINISHED, "test_succeed1(#{suite.name})"],
+ [TestSuite::FINISHED, suite.name]],
+ progress, "Should have had the correct progress")
+
+ suite = TestSuite.new
+ suite << @testcase1.suite
+ suite << @testcase2.suite
+ result = TestResult.new
+ progress = []
+ suite.run(result) { |*values| progress << values }
+
+ assert_equal(4, result.run_count, "Should have had four test runs")
+ assert_equal(1, result.failure_count, "Should have had one test failure")
+ assert_equal(1, result.error_count, "Should have had one test error")
+ assert_equal(14, progress.size, "Should have had the correct number of progress calls")
+ end
+
+ def test_empty?
+ assert(TestSuite.new.empty?, "A new test suite should be empty?")
+ assert(!@testcase2.suite.empty?, "A test suite with tests should not be empty")
+ end
+
+ def test_equality
+ suite1 = TestSuite.new
+ suite2 = TestSuite.new
+ assert_equal(suite1, suite2)
+ assert_equal(suite2, suite1)
+
+ suite1 = TestSuite.new('name')
+ assert_not_equal(suite1, suite2)
+ assert_not_equal(suite2, suite1)
+
+ suite2 = TestSuite.new('name')
+ assert_equal(suite1, suite2)
+ assert_equal(suite2, suite1)
+
+ suite1 << 'test'
+ assert_not_equal(suite1, suite2)
+ assert_not_equal(suite2, suite1)
+
+ suite2 << 'test'
+ assert_equal(suite1, suite2)
+ assert_equal(suite2, suite1)
+
+ suite2 = Object.new
+ class << suite2
+ def name
+ 'name'
+ end
+ def tests
+ ['test']
+ end
+ end
+ assert_not_equal(suite1, suite2)
+ assert_not_equal(suite2, suite1)
+
+ assert_not_equal(suite1, Object.new)
+ assert_not_equal(Object.new, suite1)
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/util/test_backtracefilter.rb b/ruby_1_8_6/test/testunit/util/test_backtracefilter.rb
new file mode 100644
index 0000000000..d4e40ea6ab
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/util/test_backtracefilter.rb
@@ -0,0 +1,41 @@
+require 'test/unit'
+
+require 'test/unit/util/backtracefilter'
+
+module Test::Unit::Util
+ class TestBacktraceFilter < Test::Unit::TestCase
+ include BacktraceFilter
+
+ def test_filter_backtrace
+ backtrace = [%q{C:\some\old\path/test/unit/assertions.rb:44:in 'assert'},
+ %q{tc_thing.rb:4:in 'a'},
+ %q{tc_thing.rb:4:in 'test_stuff'},
+ %q{C:\some\old\path/test/unit/testcase.rb:44:in 'send'},
+ %q{C:\some\old\path\test\unit\testcase.rb:44:in 'run'},
+ %q{C:\some\old\path\test\unit.rb:44:in 'run'},
+ %q{tc_thing.rb:3}]
+ assert_equal(backtrace[1..2], filter_backtrace(backtrace, %q{C:\some\old\path\test\unit}), "Should filter out all TestUnit-specific lines")
+
+backtrace = [%q{tc_thing.rb:4:in 'a'},
+ %q{tc_thing.rb:4:in 'test_stuff'},
+ %q{tc_thing.rb:3}]
+ assert_equal(backtrace, filter_backtrace(backtrace, %q{C:\some\old\path\test\unit}), "Shouldn't filter too much")
+
+ backtrace = [%q{C:\some\old\path/test/unit/assertions.rb:44:in 'assert'},
+ %q{tc_thing.rb:4:in 'a'},
+ %q{tc_thing.rb:4:in 'test_stuff'},
+ %q{tc_thing.rb:3}]
+ assert_equal(backtrace[1..3], filter_backtrace(backtrace, %q{C:\some\old\path\test\unit}), "Should filter out all TestUnit-specific lines")
+
+ backtrace = [%q{C:\some\old\path/test/unit/assertions.rb:44:in 'assert'},
+ %q{C:\some\old\path/test/unit/testcase.rb:44:in 'send'},
+ %q{C:\some\old\path\test\unit\testcase.rb:44:in 'run'},
+ %q{C:\some\old\path\test\unit.rb:44:in 'run'}]
+ assert_equal(backtrace, filter_backtrace(backtrace, %q{C:\some\old\path\test\unit}), "Should filter out all TestUnit-specific lines")
+ end
+
+ def test_nil_backtrace
+ assert_equal(["No backtrace"], filter_backtrace(nil))
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/util/test_observable.rb b/ruby_1_8_6/test/testunit/util/test_observable.rb
new file mode 100644
index 0000000000..6cd10184f1
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/util/test_observable.rb
@@ -0,0 +1,102 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit/util/observable'
+
+module Test
+ module Unit
+ module Util
+ class TC_Observable < TestCase
+
+ class TF_Observable
+ include Observable
+ end
+
+ def setup
+ @observable = TF_Observable.new
+ end
+
+ def test_simple_observation
+ assert_raises(ArgumentError, "add_listener should throw an exception if no callback is supplied") do
+ @observable.add_listener(:property, "a")
+ end
+
+ heard = false
+ callback = proc { heard = true }
+ assert_equal("a", @observable.add_listener(:property, "a", &callback), "add_listener should return the listener that was added")
+
+ count = 0
+ @observable.instance_eval do
+ count = notify_listeners(:property)
+ end
+ assert_equal(1, count, "notify_listeners should have returned the number of listeners that were notified")
+ assert(heard, "Should have heard the property changed")
+
+ heard = false
+ assert_equal(callback, @observable.remove_listener(:property, "a"), "remove_listener should return the callback")
+
+ count = 1
+ @observable.instance_eval do
+ count = notify_listeners(:property)
+ end
+ assert_equal(0, count, "notify_listeners should have returned the number of listeners that were notified")
+ assert(!heard, "Should not have heard the property change")
+ end
+
+ def test_value_observation
+ value = nil
+ @observable.add_listener(:property, "a") do |passed_value|
+ value = passed_value
+ end
+ count = 0
+ @observable.instance_eval do
+ count = notify_listeners(:property, "stuff")
+ end
+ assert_equal(1, count, "Should have update the correct number of listeners")
+ assert_equal("stuff", value, "Should have received the value as an argument to the listener")
+ end
+
+ def test_multiple_value_observation
+ values = []
+ @observable.add_listener(:property, "a") do |first_value, second_value|
+ values = [first_value, second_value]
+ end
+ count = 0
+ @observable.instance_eval do
+ count = notify_listeners(:property, "stuff", "more stuff")
+ end
+ assert_equal(1, count, "Should have update the correct number of listeners")
+ assert_equal(["stuff", "more stuff"], values, "Should have received the value as an argument to the listener")
+ end
+
+ def test_add_remove_with_default_listener
+ assert_raises(ArgumentError, "add_listener should throw an exception if no callback is supplied") do
+ @observable.add_listener(:property)
+ end
+
+ heard = false
+ callback = proc { heard = true }
+ assert_equal(callback, @observable.add_listener(:property, &callback), "add_listener should return the listener that was added")
+
+ count = 0
+ @observable.instance_eval do
+ count = notify_listeners(:property)
+ end
+ assert_equal(1, count, "notify_listeners should have returned the number of listeners that were notified")
+ assert(heard, "Should have heard the property changed")
+
+ heard = false
+ assert_equal(callback, @observable.remove_listener(:property, callback), "remove_listener should return the callback")
+
+ count = 1
+ @observable.instance_eval do
+ count = notify_listeners(:property)
+ end
+ assert_equal(0, count, "notify_listeners should have returned the number of listeners that were notified")
+ assert(!heard, "Should not have heard the property change")
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/testunit/util/test_procwrapper.rb b/ruby_1_8_6/test/testunit/util/test_procwrapper.rb
new file mode 100644
index 0000000000..3e552c7711
--- /dev/null
+++ b/ruby_1_8_6/test/testunit/util/test_procwrapper.rb
@@ -0,0 +1,36 @@
+# Author:: Nathaniel Talbott.
+# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
+# License:: Ruby license.
+
+require 'test/unit'
+require 'test/unit/util/procwrapper'
+
+module Test
+ module Unit
+ module Util
+ class TC_ProcWrapper < TestCase
+ def munge_proc(&a_proc)
+ return a_proc
+ end
+ def setup
+ @original = proc {}
+ @munged = munge_proc(&@original)
+ @wrapped_original = ProcWrapper.new(@original)
+ @wrapped_munged = ProcWrapper.new(@munged)
+ end
+ def test_wrapping
+ assert_same(@original, @wrapped_original.to_proc, "The wrapper should return what was wrapped")
+ end
+ def test_hashing
+
+ assert_equal(@wrapped_original.hash, @wrapped_munged.hash, "The original and munged should have the same hash when wrapped")
+ assert_equal(@wrapped_original, @wrapped_munged, "The wrappers should be equivalent")
+
+ a_hash = {@wrapped_original => @original}
+ assert(a_hash[@wrapped_original], "Should be able to access the wrapper in the hash")
+ assert_equal(a_hash[@wrapped_original], @original, "Should be able to access the wrapper in the hash")
+ end
+ end
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/thread/test_thread.rb b/ruby_1_8_6/test/thread/test_thread.rb
new file mode 100644
index 0000000000..abdcebffcf
--- /dev/null
+++ b/ruby_1_8_6/test/thread/test_thread.rb
@@ -0,0 +1,67 @@
+require 'thread'
+require 'test/unit'
+
+class TC_Thread < Test::Unit::TestCase
+ def setup
+ Thread.abort_on_exception = true
+ end
+ def teardown
+ Thread.abort_on_exception = false
+ end
+ def test_condvar
+ mutex = Mutex.new
+ condvar = ConditionVariable.new
+ result = []
+ mutex.synchronize do
+ t = Thread.new do
+ mutex.synchronize do
+ result << 1
+ condvar.signal
+ end
+ end
+
+ result << 0
+ condvar.wait(mutex)
+ result << 2
+ t.join
+ end
+ assert_equal([0, 1, 2], result)
+ end
+
+ def test_condvar_wait_not_owner
+ mutex = Mutex.new
+ condvar = ConditionVariable.new
+
+ assert_raises(ThreadError) { condvar.wait(mutex) }
+ end
+
+ def test_condvar_wait_exception_handling
+ # Calling wait in the only thread running should raise a ThreadError of
+ # 'stopping only thread'
+ mutex = Mutex.new
+ condvar = ConditionVariable.new
+
+ Thread.abort_on_exception = false
+
+ locked = false
+ thread = Thread.new do
+ mutex.synchronize do
+ begin
+ condvar.wait(mutex)
+ rescue Exception
+ locked = mutex.locked?
+ raise
+ end
+ end
+ end
+
+ while !thread.stop?
+ sleep(0.1)
+ end
+
+ thread.raise Interrupt, "interrupt a dead condition variable"
+ assert_raises(Interrupt) { thread.value }
+ assert(locked)
+ end
+end
+
diff --git a/ruby_1_8_6/test/uri/test_common.rb b/ruby_1_8_6/test/uri/test_common.rb
new file mode 100644
index 0000000000..a159901ea6
--- /dev/null
+++ b/ruby_1_8_6/test/uri/test_common.rb
@@ -0,0 +1,56 @@
+require 'test/unit'
+require 'uri'
+
+module URI
+
+
+class TestCommon < Test::Unit::TestCase
+ def setup
+ end
+
+ def teardown
+ end
+
+ def test_extract
+ # ruby-list:36086
+ assert_equal(['http://example.com'],
+ URI.extract('http://example.com'))
+ assert_equal(['http://example.com'],
+ URI.extract('(http://example.com)'))
+ assert_equal(['http://example.com/foo)'],
+ URI.extract('(http://example.com/foo)'))
+ assert_equal(['http://example.jphttp://example.jp'],
+ URI.extract('http://example.jphttp://example.jp'))
+ assert_equal(['http://example.jphttp://example.jp'],
+ URI.extract('http://example.jphttp://example.jp', ['http']))
+ assert_equal(['http://', 'mailto:'].sort,
+ URI.extract('ftp:// http:// mailto: https://', ['http', 'mailto']).sort)
+ # reported by Doug Kearns <djkea2@mugca.its.monash.edu.au>
+ assert_equal(['From:', 'mailto:xxx@xxx.xxx.xxx]'].sort,
+ URI.extract('From: XXX [mailto:xxx@xxx.xxx.xxx]').sort)
+ end
+
+ def test_regexp
+ assert_instance_of Regexp, URI.regexp
+ assert_instance_of Regexp, URI.regexp(['http'])
+ assert_equal URI.regexp, URI.regexp
+ assert_equal 'http://', 'x http:// x'.slice(URI.regexp)
+ assert_equal 'http://', 'x http:// x'.slice(URI.regexp(['http']))
+ assert_equal 'http://', 'x http:// x ftp://'.slice(URI.regexp(['http']))
+ assert_equal nil, 'http://'.slice(URI.regexp([]))
+ assert_equal nil, ''.slice(URI.regexp)
+ assert_equal nil, 'xxxx'.slice(URI.regexp)
+ assert_equal nil, ':'.slice(URI.regexp)
+ assert_equal 'From:', 'From:'.slice(URI.regexp)
+ end
+
+ def test_kernel_uri
+ expected = URI.parse("http://www.ruby-lang.org/")
+ assert_equal(expected, URI("http://www.ruby-lang.org/"))
+ assert_equal(expected, Kernel::URI("http://www.ruby-lang.org/"))
+ assert_raise(NoMethodError) { Object.new.URI("http://www.ruby-lang.org/") }
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/uri/test_ftp.rb b/ruby_1_8_6/test/uri/test_ftp.rb
new file mode 100644
index 0000000000..a7b59efebf
--- /dev/null
+++ b/ruby_1_8_6/test/uri/test_ftp.rb
@@ -0,0 +1,42 @@
+require 'test/unit'
+require 'uri/ftp'
+
+module URI
+
+
+class TestFTP < Test::Unit::TestCase
+ def setup
+ end
+
+ def test_parse
+ url = URI.parse('ftp://user:pass@host.com/abc/def')
+ assert_kind_of(URI::FTP, url)
+
+ exp = [
+ 'ftp',
+ 'user:pass', 'host.com', URI::FTP.default_port,
+ '/abc/def', nil,
+ ]
+ ary = [
+ url.scheme, url.userinfo, url.host, url.port,
+ url.path, url.opaque
+ ]
+ assert_equal(exp, ary)
+
+ assert_equal('user', url.user)
+ assert_equal('pass', url.password)
+ end
+
+ def test_select
+ assert_equal(['ftp', 'a.b.c', 21], URI.parse('ftp://a.b.c/').select(:scheme, :host, :port))
+ u = URI.parse('ftp://a.b.c/')
+ ary = u.component.collect {|c| u.send(c)}
+ assert_equal(ary, u.select(*u.component))
+ assert_raises(ArgumentError) do
+ u.select(:scheme, :host, :not_exist, :port)
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/uri/test_generic.rb b/ruby_1_8_6/test/uri/test_generic.rb
new file mode 100644
index 0000000000..8a7feb4982
--- /dev/null
+++ b/ruby_1_8_6/test/uri/test_generic.rb
@@ -0,0 +1,698 @@
+require 'test/unit'
+require 'uri'
+
+module URI
+
+
+class TestGeneric < Test::Unit::TestCase
+ def setup
+ @url = 'http://a/b/c/d;p?q'
+ @base_url = URI.parse(@url)
+ end
+
+ def teardown
+ end
+
+ def uri_to_ary(uri)
+ uri.class.component.collect {|c| uri.send(c)}
+ end
+
+ def test_parse
+ # 0
+ assert_kind_of(URI::HTTP, @base_url)
+
+ exp = [
+ 'http',
+ nil, 'a', URI::HTTP.default_port,
+ '/b/c/d;p',
+ 'q',
+ nil
+ ]
+ ary = uri_to_ary(@base_url)
+ assert_equal(exp, ary)
+
+ # 1
+ url = URI.parse('ftp://ftp.is.co.za/rfc/rfc1808.txt')
+ assert_kind_of(URI::FTP, url)
+
+ exp = [
+ 'ftp',
+ nil, 'ftp.is.co.za', URI::FTP.default_port,
+ '/rfc/rfc1808.txt', nil,
+ ]
+ ary = uri_to_ary(url)
+ assert_equal(exp, ary)
+
+ # 2
+ url = URI.parse('gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles')
+ assert_kind_of(URI::Generic, url)
+
+ exp = [
+ 'gopher',
+ nil, 'spinaltap.micro.umn.edu', nil, nil,
+ '/00/Weather/California/Los%20Angeles', nil,
+ nil,
+ nil
+ ]
+ ary = uri_to_ary(url)
+ assert_equal(exp, ary)
+
+ # 3
+ url = URI.parse('http://www.math.uio.no/faq/compression-faq/part1.html')
+ assert_kind_of(URI::HTTP, url)
+
+ exp = [
+ 'http',
+ nil, 'www.math.uio.no', URI::HTTP.default_port,
+ '/faq/compression-faq/part1.html',
+ nil,
+ nil
+ ]
+ ary = uri_to_ary(url)
+ assert_equal(exp, ary)
+
+ # 4
+ url = URI.parse('mailto:mduerst@ifi.unizh.ch')
+ assert_kind_of(URI::Generic, url)
+
+ exp = [
+ 'mailto',
+ 'mduerst@ifi.unizh.ch',
+ []
+ ]
+ ary = uri_to_ary(url)
+ assert_equal(exp, ary)
+
+ # 5
+ url = URI.parse('news:comp.infosystems.www.servers.unix')
+ assert_kind_of(URI::Generic, url)
+
+ exp = [
+ 'news',
+ nil, nil, nil, nil,
+ nil, 'comp.infosystems.www.servers.unix',
+ nil,
+ nil
+ ]
+ ary = uri_to_ary(url)
+ assert_equal(exp, ary)
+
+ # 6
+ url = URI.parse('telnet://melvyl.ucop.edu/')
+ assert_kind_of(URI::Generic, url)
+
+ exp = [
+ 'telnet',
+ nil, 'melvyl.ucop.edu', nil, nil,
+ '/', nil,
+ nil,
+ nil
+ ]
+ ary = uri_to_ary(url)
+ assert_equal(exp, ary)
+
+ # 7
+ # reported by Mr. Kubota <em6t-kbt@asahi-net.or.jp>
+ assert_raises(URI::InvalidURIError) { URI.parse('http://a_b:80/') }
+ assert_raises(URI::InvalidURIError) { URI.parse('http://a_b/') }
+
+ # 8
+ # reported by m_seki
+ uri = URI.parse('file:///foo/bar.txt')
+ assert_kind_of(URI::Generic, url)
+ uri = URI.parse('file:/foo/bar.txt')
+ assert_kind_of(URI::Generic, url)
+
+ # 9
+ # [ruby-dev:25667]
+ url = URI.parse('ftp://:pass@localhost/')
+ assert_equal('', url.user)
+ assert_equal('pass', url.password)
+ assert_equal(':pass', url.userinfo)
+ url = URI.parse('ftp://user@localhost/')
+ assert_equal('user', url.user)
+ assert_equal(nil, url.password)
+ assert_equal('user', url.userinfo)
+ url = URI.parse('ftp://localhost/')
+ assert_equal(nil, url.user)
+ assert_equal(nil, url.password)
+ assert_equal(nil, url.userinfo)
+ end
+
+ def test_merge
+ u1 = URI.parse('http://foo')
+ u2 = URI.parse('http://foo/')
+ u3 = URI.parse('http://foo/bar')
+ u4 = URI.parse('http://foo/bar/')
+
+ assert_equal(URI.parse('http://foo/baz'), u1 + 'baz')
+ assert_equal(URI.parse('http://foo/baz'), u2 + 'baz')
+ assert_equal(URI.parse('http://foo/baz'), u3 + 'baz')
+ assert_equal(URI.parse('http://foo/bar/baz'), u4 + 'baz')
+
+ assert_equal(URI.parse('http://foo/baz'), u1 + '/baz')
+ assert_equal(URI.parse('http://foo/baz'), u2 + '/baz')
+ assert_equal(URI.parse('http://foo/baz'), u3 + '/baz')
+ assert_equal(URI.parse('http://foo/baz'), u4 + '/baz')
+
+ # from [ruby-dev:11508] Re: uri
+ url = URI.parse('http://hoge/a.html') + 'b.html'
+ assert_equal('http://hoge/b.html', url.to_s)
+
+ # reported by Mr. Kubota <em6t-kbt@asahi-net.or.jp>
+ url = URI.parse('http://a/b') + 'http://x/y'
+ assert_equal('http://x/y', url.to_s)
+ assert_equal(url, URI.parse('') + 'http://x/y')
+ assert_equal(url, URI.parse('').normalize + 'http://x/y')
+ assert_equal(url, URI.parse('http://a/b').normalize + 'http://x/y')
+
+ u = URI.parse('http://foo/bar/baz')
+ assert_equal(nil, u.merge!(""))
+ assert_equal(nil, u.merge!(u))
+ assert(nil != u.merge!("."))
+ assert_equal('http://foo/bar/', u.to_s)
+ assert(nil != u.merge!("../baz"))
+ assert_equal('http://foo/baz', u.to_s)
+
+ # [ruby-dev:23628]
+ u0 = URI.parse('mailto:foo@example.com')
+ u1 = URI.parse('mailto:foo@example.com#bar')
+ assert_equal(uri_to_ary(u0 + '#bar'), uri_to_ary(u1))
+
+ # [ruby-list:39838]
+ u0 = URI.parse('http://www.example.com/')
+ u1 = URI.parse('http://www.example.com/foo/..') + './'
+ assert_equal(u0, u1)
+ u0 = URI.parse('http://www.example.com/foo/')
+ u1 = URI.parse('http://www.example.com/foo/bar/..') + './'
+ assert_equal(u0, u1)
+ u0 = URI.parse('http://www.example.com/foo/bar/')
+ u1 = URI.parse('http://www.example.com/foo/bar/baz/..') + './'
+ assert_equal(u0, u1)
+ u0 = URI.parse('http://www.example.com/')
+ u1 = URI.parse('http://www.example.com/foo/bar/../..') + './'
+ assert_equal(u0, u1)
+ u0 = URI.parse('http://www.example.com/foo/')
+ u1 = URI.parse('http://www.example.com/foo/bar/baz/../..') + './'
+ assert_equal(u0, u1)
+
+ # [ruby-list:39844]
+ u = URI.parse('http://www.example.com/')
+ u0 = u + './foo/'
+ u1 = u + './foo/bar/..'
+ assert_equal(u0, u1)
+ u = URI.parse('http://www.example.com/')
+ u0 = u + './'
+ u1 = u + './foo/bar/../..'
+ assert_equal(u0, u1)
+ end
+
+ def test_route
+ url = URI.parse('http://hoge/a.html').route_to('http://hoge/b.html')
+ assert_equal('b.html', url.to_s)
+
+ url = URI.parse('http://hoge/a/').route_to('http://hoge/b/')
+ assert_equal('../b/', url.to_s)
+ url = URI.parse('http://hoge/a/b').route_to('http://hoge/b/')
+ assert_equal('../b/', url.to_s)
+
+ url = URI.parse('http://hoge/a/b/').route_to('http://hoge/b/')
+ assert_equal('../../b/', url.to_s)
+
+ url = URI.parse('http://hoge/a/b/').route_to('http://HOGE/b/')
+ assert_equal('../../b/', url.to_s)
+
+ url = URI.parse('http://hoge/a/b/').route_to('http://MOGE/b/')
+ assert_equal('//MOGE/b/', url.to_s)
+
+ url = URI.parse('file:///a/b/').route_to('file:///a/b/')
+ assert_equal('', url.to_s)
+
+ url = URI.parse('mailto:foo@example.com').route_to('mailto:foo@example.com#bar')
+ assert_equal('#bar', url.to_s)
+
+ url = URI.parse('mailto:foo@example.com#bar').route_to('mailto:foo@example.com')
+ assert_equal('', url.to_s)
+
+ url = URI.parse('mailto:foo@example.com').route_to('mailto:foo@example.com')
+ assert_equal('', url.to_s)
+ end
+
+ def test_rfc2396_examples
+# http://a/b/c/d;p?q
+# g:h = g:h
+ url = @base_url.merge('g:h')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g:h', url.to_s)
+ url = @base_url.route_to('g:h')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g:h', url.to_s)
+
+# http://a/b/c/d;p?q
+# g = http://a/b/c/g
+ url = @base_url.merge('g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g', url.to_s)
+
+# http://a/b/c/d;p?q
+# ./g = http://a/b/c/g
+ url = @base_url.merge('./g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g')
+ assert_kind_of(URI::Generic, url)
+ assert('./g' != url.to_s) # ok
+ assert_equal('g', url.to_s)
+
+# http://a/b/c/d;p?q
+# g/ = http://a/b/c/g/
+ url = @base_url.merge('g/')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g/', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g/')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g/', url.to_s)
+
+# http://a/b/c/d;p?q
+# /g = http://a/g
+ url = @base_url.merge('/g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/g', url.to_s)
+ url = @base_url.route_to('http://a/g')
+ assert_kind_of(URI::Generic, url)
+ assert('/g' != url.to_s) # ok
+ assert_equal('../../g', url.to_s)
+
+# http://a/b/c/d;p?q
+# //g = http://g
+ url = @base_url.merge('//g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://g', url.to_s)
+ url = @base_url.route_to('http://g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('//g', url.to_s)
+
+# http://a/b/c/d;p?q
+# ?y = http://a/b/c/?y
+ url = @base_url.merge('?y')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/?y', url.to_s)
+ url = @base_url.route_to('http://a/b/c/?y')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('?y', url.to_s)
+
+# http://a/b/c/d;p?q
+# g?y = http://a/b/c/g?y
+ url = @base_url.merge('g?y')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g?y', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g?y')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g?y', url.to_s)
+
+# http://a/b/c/d;p?q
+# #s = (current document)#s
+ url = @base_url.merge('#s')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal(@base_url.to_s + '#s', url.to_s)
+ url = @base_url.route_to(@base_url.to_s + '#s')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('#s', url.to_s)
+
+# http://a/b/c/d;p?q
+# g#s = http://a/b/c/g#s
+ url = @base_url.merge('g#s')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g#s', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g#s')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g#s', url.to_s)
+
+# http://a/b/c/d;p?q
+# g?y#s = http://a/b/c/g?y#s
+ url = @base_url.merge('g?y#s')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g?y#s', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g?y#s')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g?y#s', url.to_s)
+
+# http://a/b/c/d;p?q
+# ;x = http://a/b/c/;x
+ url = @base_url.merge(';x')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/;x', url.to_s)
+ url = @base_url.route_to('http://a/b/c/;x')
+ assert_kind_of(URI::Generic, url)
+ assert_equal(';x', url.to_s)
+
+# http://a/b/c/d;p?q
+# g;x = http://a/b/c/g;x
+ url = @base_url.merge('g;x')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g;x', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g;x')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g;x', url.to_s)
+
+# http://a/b/c/d;p?q
+# g;x?y#s = http://a/b/c/g;x?y#s
+ url = @base_url.merge('g;x?y#s')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g;x?y#s', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g;x?y#s')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g;x?y#s', url.to_s)
+
+# http://a/b/c/d;p?q
+# . = http://a/b/c/
+ url = @base_url.merge('.')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/', url.to_s)
+ url = @base_url.route_to('http://a/b/c/')
+ assert_kind_of(URI::Generic, url)
+ assert('.' != url.to_s) # ok
+ assert_equal('./', url.to_s)
+
+# http://a/b/c/d;p?q
+# ./ = http://a/b/c/
+ url = @base_url.merge('./')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/', url.to_s)
+ url = @base_url.route_to('http://a/b/c/')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('./', url.to_s)
+
+# http://a/b/c/d;p?q
+# .. = http://a/b/
+ url = @base_url.merge('..')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/', url.to_s)
+ url = @base_url.route_to('http://a/b/')
+ assert_kind_of(URI::Generic, url)
+ assert('..' != url.to_s) # ok
+ assert_equal('../', url.to_s)
+
+# http://a/b/c/d;p?q
+# ../ = http://a/b/
+ url = @base_url.merge('../')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/', url.to_s)
+ url = @base_url.route_to('http://a/b/')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('../', url.to_s)
+
+# http://a/b/c/d;p?q
+# ../g = http://a/b/g
+ url = @base_url.merge('../g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/g', url.to_s)
+ url = @base_url.route_to('http://a/b/g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('../g', url.to_s)
+
+# http://a/b/c/d;p?q
+# ../.. = http://a/
+ url = @base_url.merge('../..')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/', url.to_s)
+ url = @base_url.route_to('http://a/')
+ assert_kind_of(URI::Generic, url)
+ assert('../..' != url.to_s) # ok
+ assert_equal('../../', url.to_s)
+
+# http://a/b/c/d;p?q
+# ../../ = http://a/
+ url = @base_url.merge('../../')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/', url.to_s)
+ url = @base_url.route_to('http://a/')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('../../', url.to_s)
+
+# http://a/b/c/d;p?q
+# ../../g = http://a/g
+ url = @base_url.merge('../../g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/g', url.to_s)
+ url = @base_url.route_to('http://a/g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('../../g', url.to_s)
+
+# http://a/b/c/d;p?q
+# <> = (current document)
+ url = @base_url.merge('')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/d;p?q', url.to_s)
+ url = @base_url.route_to('http://a/b/c/d;p?q')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('', url.to_s)
+
+# http://a/b/c/d;p?q
+# /./g = http://a/./g
+ url = @base_url.merge('/./g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/./g', url.to_s)
+ url = @base_url.route_to('http://a/./g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('/./g', url.to_s)
+
+# http://a/b/c/d;p?q
+# /../g = http://a/../g
+ url = @base_url.merge('/../g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/../g', url.to_s)
+ url = @base_url.route_to('http://a/../g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('/../g', url.to_s)
+
+# http://a/b/c/d;p?q
+# g. = http://a/b/c/g.
+ url = @base_url.merge('g.')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g.', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g.')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g.', url.to_s)
+
+# http://a/b/c/d;p?q
+# .g = http://a/b/c/.g
+ url = @base_url.merge('.g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/.g', url.to_s)
+ url = @base_url.route_to('http://a/b/c/.g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('.g', url.to_s)
+
+# http://a/b/c/d;p?q
+# g.. = http://a/b/c/g..
+ url = @base_url.merge('g..')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g..', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g..')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g..', url.to_s)
+
+# http://a/b/c/d;p?q
+# ..g = http://a/b/c/..g
+ url = @base_url.merge('..g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/..g', url.to_s)
+ url = @base_url.route_to('http://a/b/c/..g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('..g', url.to_s)
+
+# http://a/b/c/d;p?q
+# ../../../g = http://a/../g
+ url = @base_url.merge('../../../g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/../g', url.to_s)
+ url = @base_url.route_to('http://a/../g')
+ assert_kind_of(URI::Generic, url)
+ assert('../../../g' != url.to_s) # ok? yes, it confuses you
+ assert_equal('/../g', url.to_s) # and it is clearly
+
+# http://a/b/c/d;p?q
+# ../../../../g = http://a/../../g
+ url = @base_url.merge('../../../../g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/../../g', url.to_s)
+ url = @base_url.route_to('http://a/../../g')
+ assert_kind_of(URI::Generic, url)
+ assert('../../../../g' != url.to_s) # ok? yes, it confuses you
+ assert_equal('/../../g', url.to_s) # and it is clearly
+
+# http://a/b/c/d;p?q
+# ./../g = http://a/b/g
+ url = @base_url.merge('./../g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/g', url.to_s)
+ url = @base_url.route_to('http://a/b/g')
+ assert_kind_of(URI::Generic, url)
+ assert('./../g' != url.to_s) # ok
+ assert_equal('../g', url.to_s)
+
+# http://a/b/c/d;p?q
+# ./g/. = http://a/b/c/g/
+ url = @base_url.merge('./g/.')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g/', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g/')
+ assert_kind_of(URI::Generic, url)
+ assert('./g/.' != url.to_s) # ok
+ assert_equal('g/', url.to_s)
+
+# http://a/b/c/d;p?q
+# g/./h = http://a/b/c/g/h
+ url = @base_url.merge('g/./h')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g/h', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g/h')
+ assert_kind_of(URI::Generic, url)
+ assert('g/./h' != url.to_s) # ok
+ assert_equal('g/h', url.to_s)
+
+# http://a/b/c/d;p?q
+# g/../h = http://a/b/c/h
+ url = @base_url.merge('g/../h')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/h', url.to_s)
+ url = @base_url.route_to('http://a/b/c/h')
+ assert_kind_of(URI::Generic, url)
+ assert('g/../h' != url.to_s) # ok
+ assert_equal('h', url.to_s)
+
+# http://a/b/c/d;p?q
+# g;x=1/./y = http://a/b/c/g;x=1/y
+ url = @base_url.merge('g;x=1/./y')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g;x=1/y', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g;x=1/y')
+ assert_kind_of(URI::Generic, url)
+ assert('g;x=1/./y' != url.to_s) # ok
+ assert_equal('g;x=1/y', url.to_s)
+
+# http://a/b/c/d;p?q
+# g;x=1/../y = http://a/b/c/y
+ url = @base_url.merge('g;x=1/../y')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/y', url.to_s)
+ url = @base_url.route_to('http://a/b/c/y')
+ assert_kind_of(URI::Generic, url)
+ assert('g;x=1/../y' != url.to_s) # ok
+ assert_equal('y', url.to_s)
+
+# http://a/b/c/d;p?q
+# g?y/./x = http://a/b/c/g?y/./x
+ url = @base_url.merge('g?y/./x')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g?y/./x', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g?y/./x')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g?y/./x', url.to_s)
+
+# http://a/b/c/d;p?q
+# g?y/../x = http://a/b/c/g?y/../x
+ url = @base_url.merge('g?y/../x')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g?y/../x', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g?y/../x')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g?y/../x', url.to_s)
+
+# http://a/b/c/d;p?q
+# g#s/./x = http://a/b/c/g#s/./x
+ url = @base_url.merge('g#s/./x')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g#s/./x', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g#s/./x')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g#s/./x', url.to_s)
+
+# http://a/b/c/d;p?q
+# g#s/../x = http://a/b/c/g#s/../x
+ url = @base_url.merge('g#s/../x')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http://a/b/c/g#s/../x', url.to_s)
+ url = @base_url.route_to('http://a/b/c/g#s/../x')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('g#s/../x', url.to_s)
+
+# http://a/b/c/d;p?q
+# http:g = http:g ; for validating parsers
+# | http://a/b/c/g ; for backwards compatibility
+ url = @base_url.merge('http:g')
+ assert_kind_of(URI::HTTP, url)
+ assert_equal('http:g', url.to_s)
+ url = @base_url.route_to('http:g')
+ assert_kind_of(URI::Generic, url)
+ assert_equal('http:g', url.to_s)
+ end
+
+ def test_join
+ assert_equal(URI.parse('http://foo/bar'), URI.join('http://foo/bar'))
+ assert_equal(URI.parse('http://foo/bar'), URI.join('http://foo', 'bar'))
+ assert_equal(URI.parse('http://foo/bar/'), URI.join('http://foo', 'bar/'))
+
+ assert_equal(URI.parse('http://foo/baz'), URI.join('http://foo', 'bar', 'baz'))
+ assert_equal(URI.parse('http://foo/baz'), URI.join('http://foo', 'bar', '/baz'))
+ assert_equal(URI.parse('http://foo/baz/'), URI.join('http://foo', 'bar', '/baz/'))
+ assert_equal(URI.parse('http://foo/bar/baz'), URI.join('http://foo', 'bar/', 'baz'))
+ assert_equal(URI.parse('http://foo/hoge'), URI.join('http://foo', 'bar', 'baz', 'hoge'))
+
+ assert_equal(URI.parse('http://foo/bar/baz'), URI.join('http://foo', 'bar/baz'))
+ assert_equal(URI.parse('http://foo/bar/hoge'), URI.join('http://foo', 'bar/baz', 'hoge'))
+ assert_equal(URI.parse('http://foo/bar/baz/hoge'), URI.join('http://foo', 'bar/baz/', 'hoge'))
+ assert_equal(URI.parse('http://foo/hoge'), URI.join('http://foo', 'bar/baz', '/hoge'))
+ assert_equal(URI.parse('http://foo/bar/hoge'), URI.join('http://foo', 'bar/baz', 'hoge'))
+ assert_equal(URI.parse('http://foo/bar/baz/hoge'), URI.join('http://foo', 'bar/baz/', 'hoge'))
+ assert_equal(URI.parse('http://foo/hoge'), URI.join('http://foo', 'bar/baz', '/hoge'))
+ end
+
+ # ruby-dev:16728
+ def test_set_component
+ uri = URI.parse('http://foo:bar@baz')
+ assert_equal('oof', uri.user = 'oof')
+ assert_equal('http://oof:bar@baz', uri.to_s)
+ assert_equal('rab', uri.password = 'rab')
+ assert_equal('http://oof:rab@baz', uri.to_s)
+ assert_equal('foo', uri.userinfo = 'foo')
+ assert_equal('http://foo:rab@baz', uri.to_s)
+ assert_equal(['foo', 'bar'], uri.userinfo = ['foo', 'bar'])
+ assert_equal('http://foo:bar@baz', uri.to_s)
+ assert_equal(['foo'], uri.userinfo = ['foo'])
+ assert_equal('http://foo:bar@baz', uri.to_s)
+ assert_equal('zab', uri.host = 'zab')
+ assert_equal('http://foo:bar@zab', uri.to_s)
+ assert_equal(8080, uri.port = 8080)
+ assert_equal('http://foo:bar@zab:8080', uri.to_s)
+ assert_equal('/', uri.path = '/')
+ assert_equal('http://foo:bar@zab:8080/', uri.to_s)
+ assert_equal('a=1', uri.query = 'a=1')
+ assert_equal('http://foo:bar@zab:8080/?a=1', uri.to_s)
+ assert_equal('b123', uri.fragment = 'b123')
+ assert_equal('http://foo:bar@zab:8080/?a=1#b123', uri.to_s)
+
+ uri = URI.parse('http://example.com')
+ assert_raises(URI::InvalidURIError) { uri.password = 'bar' }
+ uri.userinfo = 'foo:bar'
+ assert_equal('http://foo:bar@example.com', uri.to_s)
+ assert_raises(URI::InvalidURIError) { uri.registry = 'bar' }
+ assert_raises(URI::InvalidURIError) { uri.opaque = 'bar' }
+
+ uri = URI.parse('mailto:foo@example.com')
+ assert_raises(URI::InvalidURIError) { uri.user = 'bar' }
+ assert_raises(URI::InvalidURIError) { uri.password = 'bar' }
+ assert_raises(URI::InvalidURIError) { uri.userinfo = ['bar', 'baz'] }
+ assert_raises(URI::InvalidURIError) { uri.host = 'bar' }
+ assert_raises(URI::InvalidURIError) { uri.port = 'bar' }
+ assert_raises(URI::InvalidURIError) { uri.path = 'bar' }
+ assert_raises(URI::InvalidURIError) { uri.query = 'bar' }
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/uri/test_http.rb b/ruby_1_8_6/test/uri/test_http.rb
new file mode 100644
index 0000000000..a6846141df
--- /dev/null
+++ b/ruby_1_8_6/test/uri/test_http.rb
@@ -0,0 +1,63 @@
+require 'test/unit'
+require 'uri/http'
+
+module URI
+
+
+class TestHTTP < Test::Unit::TestCase
+ def setup
+ end
+
+ def teardown
+ end
+
+ def uri_to_ary(uri)
+ uri.class.component.collect {|c| uri.send(c)}
+ end
+
+ def test_parse
+ u = URI.parse('http://a')
+ assert_kind_of(URI::HTTP, u)
+ assert_equal(['http',
+ nil, 'a', URI::HTTP.default_port,
+ '', nil, nil], uri_to_ary(u))
+ end
+
+ def test_normalize
+ host = 'aBcD'
+ u1 = URI.parse('http://' + host + '/eFg?HiJ')
+ u2 = URI.parse('http://' + host.downcase + '/eFg?HiJ')
+ assert(u1.normalize.host == 'abcd')
+ assert(u1.normalize.path == u1.path)
+ assert(u1.normalize == u2.normalize)
+ assert(!u1.normalize.host.equal?(u1.host))
+ assert( u2.normalize.host.equal?(u2.host))
+
+ assert_equal('http://abc/', URI.parse('http://abc').normalize.to_s)
+ end
+
+ def test_equal
+ assert(URI.parse('http://abc') == URI.parse('http://ABC'))
+ assert(URI.parse('http://abc/def') == URI.parse('http://ABC/def'))
+ assert(URI.parse('http://abc/def') != URI.parse('http://ABC/DEF'))
+ end
+
+ def test_request_uri
+ assert_equal('/', URI.parse('http://a.b.c/').request_uri)
+ assert_equal('/?abc=def', URI.parse('http://a.b.c/?abc=def').request_uri)
+ assert_equal('/', URI.parse('http://a.b.c').request_uri)
+ assert_equal('/?abc=def', URI.parse('http://a.b.c?abc=def').request_uri)
+ end
+
+ def test_select
+ assert_equal(['http', 'a.b.c', 80], URI.parse('http://a.b.c/').select(:scheme, :host, :port))
+ u = URI.parse('http://a.b.c/')
+ assert_equal(uri_to_ary(u), u.select(*u.component))
+ assert_raises(ArgumentError) do
+ u.select(:scheme, :host, :not_exist, :port)
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/uri/test_ldap.rb b/ruby_1_8_6/test/uri/test_ldap.rb
new file mode 100644
index 0000000000..866b7d8066
--- /dev/null
+++ b/ruby_1_8_6/test/uri/test_ldap.rb
@@ -0,0 +1,100 @@
+require 'test/unit'
+require 'uri/ldap'
+
+module URI
+
+
+class TestLDAP < Test::Unit::TestCase
+ def setup
+ end
+
+ def teardown
+ end
+
+ def uri_to_ary(uri)
+ uri.class.component.collect {|c| uri.send(c)}
+ end
+
+ def test_parse
+ url = 'ldap://ldap.jaist.ac.jp/o=JAIST,c=JP?sn?base?(sn=ttate*)'
+ u = URI.parse(url)
+ assert_kind_of(URI::LDAP, u)
+ assert_equal(url, u.to_s)
+ assert_equal('o=JAIST,c=JP', u.dn)
+ assert_equal('sn', u.attributes)
+ assert_equal('base', u.scope)
+ assert_equal('(sn=ttate*)', u.filter)
+ assert_equal(nil, u.extensions)
+
+ u.scope = URI::LDAP::SCOPE_SUB
+ u.attributes = 'sn,cn,mail'
+ assert_equal('ldap://ldap.jaist.ac.jp/o=JAIST,c=JP?sn,cn,mail?sub?(sn=ttate*)', u.to_s)
+ assert_equal('o=JAIST,c=JP', u.dn)
+ assert_equal('sn,cn,mail', u.attributes)
+ assert_equal('sub', u.scope)
+ assert_equal('(sn=ttate*)', u.filter)
+ assert_equal(nil, u.extensions)
+
+ # from RFC2255, section 6.
+ urls = {
+ 'ldap:///o=University%20of%20Michigan,c=US' =>
+ ['ldap', nil, URI::LDAP::DEFAULT_PORT,
+ 'o=University%20of%20Michigan,c=US',
+ nil, nil, nil, nil],
+
+ 'ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US' =>
+ ['ldap', 'ldap.itd.umich.edu', URI::LDAP::DEFAULT_PORT,
+ 'o=University%20of%20Michigan,c=US',
+ nil, nil, nil, nil],
+
+ 'ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress' =>
+ ['ldap', 'ldap.itd.umich.edu', URI::LDAP::DEFAULT_PORT,
+ 'o=University%20of%20Michigan,c=US',
+ 'postalAddress', nil, nil, nil],
+
+ 'ldap://host.com:6666/o=University%20of%20Michigan,c=US??sub?(cn=Babs%20Jensen)' =>
+ ['ldap', 'host.com', 6666,
+ 'o=University%20of%20Michigan,c=US',
+ nil, 'sub', '(cn=Babs%20Jensen)', nil],
+
+ 'ldap://ldap.itd.umich.edu/c=GB?objectClass?one' =>
+ ['ldap', 'ldap.itd.umich.edu', URI::LDAP::DEFAULT_PORT,
+ 'c=GB',
+ 'objectClass', 'one', nil, nil],
+
+ 'ldap://ldap.question.com/o=Question%3f,c=US?mail' =>
+ ['ldap', 'ldap.question.com', URI::LDAP::DEFAULT_PORT,
+ 'o=Question%3f,c=US',
+ 'mail', nil, nil, nil],
+
+ 'ldap://ldap.netscape.com/o=Babsco,c=US??(int=%5c00%5c00%5c00%5c04)' =>
+ ['ldap', 'ldap.netscape.com', URI::LDAP::DEFAULT_PORT,
+ 'o=Babsco,c=US',
+ nil, '(int=%5c00%5c00%5c00%5c04)', nil, nil],
+
+ 'ldap:///??sub??bindname=cn=Manager%2co=Foo' =>
+ ['ldap', nil, URI::LDAP::DEFAULT_PORT,
+ '',
+ nil, 'sub', nil, 'bindname=cn=Manager%2co=Foo'],
+
+ 'ldap:///??sub??!bindname=cn=Manager%2co=Foo' =>
+ ['ldap', nil, URI::LDAP::DEFAULT_PORT,
+ '',
+ nil, 'sub', nil, '!bindname=cn=Manager%2co=Foo'],
+ }.each do |url, ary|
+ u = URI.parse(url)
+ assert_equal(ary, uri_to_ary(u))
+ end
+ end
+
+ def test_select
+ u = URI.parse('ldap:///??sub??!bindname=cn=Manager%2co=Foo')
+ assert_equal(uri_to_ary(u), u.select(*u.component))
+ assert_raises(ArgumentError) do
+ u.select(:scheme, :host, :not_exist, :port)
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/uri/test_mailto.rb b/ruby_1_8_6/test/uri/test_mailto.rb
new file mode 100644
index 0000000000..ba437904f8
--- /dev/null
+++ b/ruby_1_8_6/test/uri/test_mailto.rb
@@ -0,0 +1,122 @@
+require 'test/unit'
+require 'uri/mailto'
+
+module URI
+
+
+class TestMailTo < Test::Unit::TestCase
+ def setup
+ @u = URI::MailTo
+ end
+
+ def teardown
+ end
+
+ def uri_to_ary(uri)
+ uri.class.component.collect {|c| uri.send(c)}
+ end
+
+ def test_build
+ ok = []
+ bad = []
+
+ # RFC2368, 6. Examples
+ # mailto:chris@example.com
+ ok << ["mailto:chris@example.com"]
+ ok[-1] << ["chris@example.com", nil]
+ ok[-1] << {:to => "chris@example.com"}
+
+ # mailto:infobot@example.com?subject=current-issue
+ ok << ["mailto:infobot@example.com?subject=current-issue"]
+ ok[-1] << ["infobot@example.com", ["subject=current-issue"]]
+ ok[-1] << {:to => "infobot@example.com",
+ :headers => ["subject=current-issue"]}
+
+ # mailto:infobot@example.com?body=send%20current-issue
+ ok << ["mailto:infobot@example.com?body=send%20current-issue"]
+ ok[-1] << ["infobot@example.com", ["body=send%20current-issue"]]
+ ok[-1] << {:to => "infobot@example.com",
+ :headers => ["body=send%20current-issue"]}
+
+ # mailto:infobot@example.com?body=send%20current-issue%0D%0Asend%20index
+ ok << ["mailto:infobot@example.com?body=send%20current-issue%0D%0Asend%20index"]
+ ok[-1] << ["infobot@example.com",
+ ["body=send%20current-issue%0D%0Asend%20index"]]
+ ok[-1] << {:to => "infobot@example.com",
+ :headers => ["body=send%20current-issue%0D%0Asend%20index"]}
+
+ # mailto:foobar@example.com?In-Reply-To=%3c3469A91.D10AF4C@example.com
+ ok << ["mailto:foobar@example.com?In-Reply-To=%3c3469A91.D10AF4C@example.com"]
+ ok[-1] << ["foobar@example.com",
+ ["In-Reply-To=%3c3469A91.D10AF4C@example.com"]]
+ ok[-1] << {:to => "foobar@example.com",
+ :headers => ["In-Reply-To=%3c3469A91.D10AF4C@example.com"]}
+
+ # mailto:majordomo@example.com?body=subscribe%20bamboo-l
+ ok << ["mailto:majordomo@example.com?body=subscribe%20bamboo-l"]
+ ok[-1] << ["majordomo@example.com", ["body=subscribe%20bamboo-l"]]
+ ok[-1] << {:to => "majordomo@example.com",
+ :headers => ["body=subscribe%20bamboo-l"]}
+
+ # mailto:joe@example.com?cc=bob@example.com&body=hello
+ ok << ["mailto:joe@example.com?cc=bob@example.com&body=hello"]
+ ok[-1] << ["joe@example.com", ["cc=bob@example.com", "body=hello"]]
+ ok[-1] << {:to => "joe@example.com",
+ :headers => ["cc=bob@example.com", "body=hello"]}
+
+ # mailto:?to=joe@example.com&cc=bob@example.com&body=hello
+ ok << ["mailto:?to=joe@example.com&cc=bob@example.com&body=hello"]
+ ok[-1] << [nil,
+ ["to=joe@example.com", "cc=bob@example.com", "body=hello"]]
+ ok[-1] << {:headers => ["to=joe@example.com",
+ "cc=bob@example.com", "body=hello"]}
+
+ # mailto:gorby%25kremvax@example.com
+ ok << ["mailto:gorby%25kremvax@example.com"]
+ ok[-1] << ["gorby%25kremvax@example.com", nil]
+ ok[-1] << {:to => "gorby%25kremvax@example.com"}
+
+ # mailto:unlikely%3Faddress@example.com?blat=foop
+ ok << ["mailto:unlikely%3Faddress@example.com?blat=foop"]
+ ok[-1] << ["unlikely%3Faddress@example.com", ["blat=foop"]]
+ ok[-1] << {:to => "unlikely%3Faddress@example.com",
+ :headers => ["blat=foop"]}
+
+ ok_all = ok.flatten.join("\0")
+
+ # mailto:joe@example.com?cc=bob@example.com?body=hello ; WRONG!
+ bad << ["joe@example.com", ["cc=bob@example.com?body=hello"]]
+
+ # mailto:javascript:alert()
+ bad << ["javascript:alert()", []]
+
+ # '=' which is in hname or hvalue is wrong.
+ bad << ["foo@example.jp?subject=1+1=2", []]
+
+ ok.each do |x|
+ assert_equal(x[0],
+ @u.build(x[1]).to_s)
+ assert_equal(x[0],
+ @u.build(x[2]).to_s)
+ end
+
+ bad.each do |x|
+ assert_raises(URI::InvalidComponentError) {
+ @u.build(x)
+ }
+ end
+
+ assert_equal(ok_all, ok.flatten.join("\0"))
+ end
+
+ def test_select
+ u = URI.parse('mailto:joe@example.com?cc=bob@example.com&body=hello')
+ assert_equal(uri_to_ary(u), u.select(*u.component))
+ assert_raises(ArgumentError) do
+ u.select(:scheme, :host, :not_exist, :port)
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/webrick/test_cgi.rb b/ruby_1_8_6/test/webrick/test_cgi.rb
new file mode 100644
index 0000000000..7e3f4ee5f0
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_cgi.rb
@@ -0,0 +1,78 @@
+require "webrick"
+require File.join(File.dirname(__FILE__), "utils.rb")
+require "test/unit"
+begin
+ loadpath = $:.dup
+ $:.replace($: | [File.expand_path("../ruby", File.dirname(__FILE__))])
+ require 'envutil'
+ensure
+ $:.replace(loadpath)
+end
+
+class TestWEBrickCGI < Test::Unit::TestCase
+ def test_cgi
+ accepted = started = stopped = 0
+ requested0 = requested1 = 0
+ config = {
+ :CGIInterpreter => EnvUtil.rubybin,
+ :DocumentRoot => File.dirname(__FILE__),
+ :DirectoryIndex => ["webrick.cgi"],
+ }
+ if RUBY_PLATFORM =~ /mswin32|mingw|cygwin|bccwin32/
+ config[:CGIPathEnv] = ENV['PATH'] # runtime dll may not be in system dir.
+ end
+ TestWEBrick.start_httpserver(config){|server, addr, port|
+ http = Net::HTTP.new(addr, port)
+ req = Net::HTTP::Get.new("/webrick.cgi")
+ http.request(req){|res| assert_equal("/webrick.cgi", res.body)}
+ req = Net::HTTP::Get.new("/webrick.cgi/path/info")
+ http.request(req){|res| assert_equal("/path/info", res.body)}
+ req = Net::HTTP::Get.new("/webrick.cgi/%3F%3F%3F?foo=bar")
+ http.request(req){|res| assert_equal("/???", res.body)}
+ req = Net::HTTP::Get.new("/webrick.cgi/%A4%DB%A4%B2/%A4%DB%A4%B2")
+ http.request(req){|res|
+ assert_equal("/\xA4\xDB\xA4\xB2/\xA4\xDB\xA4\xB2", res.body)}
+ req = Net::HTTP::Get.new("/webrick.cgi?a=1;a=2;b=x")
+ http.request(req){|res| assert_equal("a=1, a=2, b=x", res.body)}
+ req = Net::HTTP::Get.new("/webrick.cgi?a=1&a=2&b=x")
+ http.request(req){|res| assert_equal("a=1, a=2, b=x", res.body)}
+
+ req = Net::HTTP::Post.new("/webrick.cgi?a=x;a=y;b=1")
+ req["Content-Type"] = "application/x-www-form-urlencoded"
+ http.request(req, "a=1;a=2;b=x"){|res|
+ assert_equal("a=1, a=2, b=x", res.body)}
+ req = Net::HTTP::Post.new("/webrick.cgi?a=x&a=y&b=1")
+ req["Content-Type"] = "application/x-www-form-urlencoded"
+ http.request(req, "a=1&a=2&b=x"){|res|
+ assert_equal("a=1, a=2, b=x", res.body)}
+ req = Net::HTTP::Get.new("/")
+ http.request(req){|res|
+ ary = res.body.to_a
+ assert_match(%r{/$}, ary[0])
+ assert_match(%r{/webrick.cgi$}, ary[1])
+ }
+
+ req = Net::HTTP::Get.new("/webrick.cgi")
+ req["Cookie"] = "CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001"
+ http.request(req){|res|
+ assert_equal(
+ "CUSTOMER=WILE_E_COYOTE\nPART_NUMBER=ROCKET_LAUNCHER_0001\n",
+ res.body)
+ }
+
+ req = Net::HTTP::Get.new("/webrick.cgi")
+ cookie = %{$Version="1"; }
+ cookie << %{Customer="WILE_E_COYOTE"; $Path="/acme"; }
+ cookie << %{Part_Number="Rocket_Launcher_0001"; $Path="/acme"; }
+ cookie << %{Shipping="FedEx"; $Path="/acme"}
+ req["Cookie"] = cookie
+ http.request(req){|res|
+ assert_equal("Customer=WILE_E_COYOTE, Shipping=FedEx",
+ res["Set-Cookie"])
+ assert_equal("Customer=WILE_E_COYOTE\n" +
+ "Part_Number=Rocket_Launcher_0001\n" +
+ "Shipping=FedEx\n", res.body)
+ }
+ }
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_cookie.rb b/ruby_1_8_6/test/webrick/test_cookie.rb
new file mode 100644
index 0000000000..14771fd01c
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_cookie.rb
@@ -0,0 +1,104 @@
+require "test/unit"
+require "webrick/cookie"
+
+class TestWEBrickCookie < Test::Unit::TestCase
+ def test_new
+ cookie = WEBrick::Cookie.new("foo","bar")
+ assert_equal("foo", cookie.name)
+ assert_equal("bar", cookie.value)
+ assert_equal("foo=bar", cookie.to_s)
+ end
+
+ def test_time
+ cookie = WEBrick::Cookie.new("foo","bar")
+ t = 1000000000
+ cookie.max_age = t
+ assert_match(t.to_s, cookie.to_s)
+
+ cookie = WEBrick::Cookie.new("foo","bar")
+ t = Time.at(1000000000)
+ cookie.expires = t
+ assert_equal(Time, cookie.expires.class)
+ assert_equal(t, cookie.expires)
+ ts = t.httpdate
+ cookie.expires = ts
+ assert_equal(Time, cookie.expires.class)
+ assert_equal(t, cookie.expires)
+ assert_match(ts, cookie.to_s)
+ end
+
+ def test_parse
+ data = ""
+ data << '$Version="1"; '
+ data << 'Customer="WILE_E_COYOTE"; $Path="/acme"; '
+ data << 'Part_Number="Rocket_Launcher_0001"; $Path="/acme"; '
+ data << 'Shipping="FedEx"; $Path="/acme"'
+ cookies = WEBrick::Cookie.parse(data)
+ assert_equal(1, cookies[0].version)
+ assert_equal("Customer", cookies[0].name)
+ assert_equal("WILE_E_COYOTE", cookies[0].value)
+ assert_equal("/acme", cookies[0].path)
+ assert_equal(1, cookies[1].version)
+ assert_equal("Part_Number", cookies[1].name)
+ assert_equal("Rocket_Launcher_0001", cookies[1].value)
+ assert_equal(1, cookies[2].version)
+ assert_equal("Shipping", cookies[2].name)
+ assert_equal("FedEx", cookies[2].value)
+
+ data = "hoge=moge; __div__session=9865ecfd514be7f7"
+ cookies = WEBrick::Cookie.parse(data)
+ assert_equal(0, cookies[0].version)
+ assert_equal("hoge", cookies[0].name)
+ assert_equal("moge", cookies[0].value)
+ assert_equal("__div__session", cookies[1].name)
+ assert_equal("9865ecfd514be7f7", cookies[1].value)
+ end
+
+ def test_parse_set_cookie
+ data = %(Customer="WILE_E_COYOTE"; Version="1"; Path="/acme")
+ cookie = WEBrick::Cookie.parse_set_cookie(data)
+ assert_equal("Customer", cookie.name)
+ assert_equal("WILE_E_COYOTE", cookie.value)
+ assert_equal(1, cookie.version)
+ assert_equal("/acme", cookie.path)
+
+ data = %(Shipping="FedEx"; Version="1"; Path="/acme"; Secure)
+ cookie = WEBrick::Cookie.parse_set_cookie(data)
+ assert_equal("Shipping", cookie.name)
+ assert_equal("FedEx", cookie.value)
+ assert_equal(1, cookie.version)
+ assert_equal("/acme", cookie.path)
+ assert_equal(true, cookie.secure)
+ end
+
+ def test_parse_set_cookies
+ data = %(Shipping="FedEx"; Version="1"; Path="/acme"; Secure)
+ data << %(, CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT; path=/; Secure)
+ data << %(, name="Aaron"; Version="1"; path="/acme")
+ cookies = WEBrick::Cookie.parse_set_cookies(data)
+ assert_equal(3, cookies.length)
+
+ fed_ex = cookies.find { |c| c.name == 'Shipping' }
+ assert_not_nil(fed_ex)
+ assert_equal("Shipping", fed_ex.name)
+ assert_equal("FedEx", fed_ex.value)
+ assert_equal(1, fed_ex.version)
+ assert_equal("/acme", fed_ex.path)
+ assert_equal(true, fed_ex.secure)
+
+ name = cookies.find { |c| c.name == 'name' }
+ assert_not_nil(name)
+ assert_equal("name", name.name)
+ assert_equal("Aaron", name.value)
+ assert_equal(1, name.version)
+ assert_equal("/acme", name.path)
+
+ customer = cookies.find { |c| c.name == 'CUSTOMER' }
+ assert_not_nil(customer)
+ assert_equal("CUSTOMER", customer.name)
+ assert_equal("WILE_E_COYOTE", customer.value)
+ assert_equal(0, customer.version)
+ assert_equal("/", customer.path)
+ assert_equal(Time.utc(1999, 11, 9, 23, 12, 40), customer.expires)
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_filehandler.rb b/ruby_1_8_6/test/webrick/test_filehandler.rb
new file mode 100644
index 0000000000..703fde4d9a
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_filehandler.rb
@@ -0,0 +1,65 @@
+require "test/unit"
+require "webrick"
+require "stringio"
+
+class WEBrick::TestFileHandler < Test::Unit::TestCase
+ def default_file_handler(filename)
+ klass = WEBrick::HTTPServlet::DefaultFileHandler
+ klass.new(WEBrick::Config::HTTP, filename)
+ end
+
+ def get_res_body(res)
+ return res.body.read rescue res.body
+ end
+
+ def make_range_request(range_spec)
+ msg = <<-_end_of_request_
+ GET / HTTP/1.0
+ Range: #{range_spec}
+
+ _end_of_request_
+ return StringIO.new(msg.gsub(/^ {6}/, ""))
+ end
+
+ def make_range_response(file, range_spec)
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(make_range_request(range_spec))
+ res = WEBrick::HTTPResponse.new(WEBrick::Config::HTTP)
+ size = File.size(file)
+ handler = default_file_handler(file)
+ handler.make_partial_content(req, res, file, size)
+ return res
+ end
+
+ def test_make_partial_content
+ filename = __FILE__
+ filesize = File.size(filename)
+
+ res = make_range_response(filename, "bytes=#{filesize-100}-")
+ assert_match(%r{^text/plain}, res["content-type"])
+ assert_equal(get_res_body(res).size, 100)
+
+ res = make_range_response(filename, "bytes=-100")
+ assert_match(%r{^text/plain}, res["content-type"])
+ assert_equal(get_res_body(res).size, 100)
+
+ res = make_range_response(filename, "bytes=0-99")
+ assert_match(%r{^text/plain}, res["content-type"])
+ assert_equal(get_res_body(res).size, 100)
+
+ res = make_range_response(filename, "bytes=100-199")
+ assert_match(%r{^text/plain}, res["content-type"])
+ assert_equal(get_res_body(res).size, 100)
+
+ res = make_range_response(filename, "bytes=0-0")
+ assert_match(%r{^text/plain}, res["content-type"])
+ assert_equal(get_res_body(res).size, 1)
+
+ res = make_range_response(filename, "bytes=-1")
+ assert_match(%r{^text/plain}, res["content-type"])
+ assert_equal(get_res_body(res).size, 1)
+
+ res = make_range_response(filename, "bytes=0-0, -2")
+ assert_match(%r{^multipart/byteranges}, res["content-type"])
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_httpauth.rb b/ruby_1_8_6/test/webrick/test_httpauth.rb
new file mode 100644
index 0000000000..75926b1624
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_httpauth.rb
@@ -0,0 +1,82 @@
+require "test/unit"
+require "net/http"
+require "tempfile"
+require "webrick"
+require "webrick/httpauth/basicauth"
+require File.join(File.dirname(__FILE__), "utils.rb")
+
+class TestWEBrickHTTPAuth < Test::Unit::TestCase
+ def test_basic_auth
+ TestWEBrick.start_httpserver{|server, addr, port|
+ realm = "WEBrick's realm"
+ path = "/basic_auth"
+
+ server.mount_proc(path){|req, res|
+ WEBrick::HTTPAuth.basic_auth(req, res, realm){|user, pass|
+ user == "webrick" && pass == "supersecretpassword"
+ }
+ res.body = "hoge"
+ }
+ http = Net::HTTP.new(addr, port)
+ g = Net::HTTP::Get.new(path)
+ g.basic_auth("webrick", "supersecretpassword")
+ http.request(g){|res| assert_equal("hoge", res.body)}
+ g.basic_auth("webrick", "not super")
+ http.request(g){|res| assert_not_equal("hoge", res.body)}
+ }
+ end
+
+ def test_basic_auth2
+ TestWEBrick.start_httpserver{|server, addr, port|
+ realm = "WEBrick's realm"
+ path = "/basic_auth2"
+
+ tmpfile = Tempfile.new("test_webrick_auth")
+ tmpfile.close
+ tmp_pass = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
+ tmp_pass.set_passwd(realm, "webrick", "supersecretpassword")
+ tmp_pass.set_passwd(realm, "foo", "supersecretpassword")
+ tmp_pass.flush
+
+ htpasswd = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
+ users = []
+ htpasswd.each{|user, pass| users << user }
+ assert_equal(2, users.size)
+ assert(users.member?("webrick"))
+ assert(users.member?("foo"))
+
+ server.mount_proc(path){|req, res|
+ auth = WEBrick::HTTPAuth::BasicAuth.new(
+ :Realm => realm, :UserDB => htpasswd,
+ :Logger => server.logger
+ )
+ auth.authenticate(req, res)
+ res.body = "hoge"
+ }
+ http = Net::HTTP.new(addr, port)
+ g = Net::HTTP::Get.new(path)
+ g.basic_auth("webrick", "supersecretpassword")
+ http.request(g){|res| assert_equal("hoge", res.body)}
+ g.basic_auth("webrick", "not super")
+ http.request(g){|res| assert_not_equal("hoge", res.body)}
+ }
+ end
+
+ def test_basic_auth3
+ tmpfile = Tempfile.new("test_webrick_auth")
+ tmpfile.puts("webrick:{SHA}GJYFRpBbdchp595jlh3Bhfmgp8k=")
+ tmpfile.flush
+ assert_raises(NotImplementedError){
+ WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
+ }
+ tmpfile.close(true)
+
+ tmpfile = Tempfile.new("test_webrick_auth")
+ tmpfile.puts("webrick:$apr1$IOVMD/..$rmnOSPXr0.wwrLPZHBQZy0")
+ tmpfile.flush
+ assert_raises(NotImplementedError){
+ WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
+ }
+ tmpfile.close(true)
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_httprequest.rb b/ruby_1_8_6/test/webrick/test_httprequest.rb
new file mode 100644
index 0000000000..f0cd1a092a
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_httprequest.rb
@@ -0,0 +1,272 @@
+require "webrick"
+require "stringio"
+require "test/unit"
+
+class TestWEBrickHTTPRequest < Test::Unit::TestCase
+ def test_parse_09
+ msg = <<-_end_of_message_
+ GET /
+ foobar # HTTP/0.9 request don't have header nor entity body.
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal("GET", req.request_method)
+ assert_equal("/", req.unparsed_uri)
+ assert_equal(WEBrick::HTTPVersion.new("0.9"), req.http_version)
+ assert_equal(WEBrick::Config::HTTP[:ServerName], req.host)
+ assert_equal(80, req.port)
+ assert_equal(false, req.keep_alive?)
+ assert_equal(nil, req.body)
+ assert(req.query.empty?)
+ end
+
+ def test_parse_10
+ msg = <<-_end_of_message_
+ GET / HTTP/1.0
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal("GET", req.request_method)
+ assert_equal("/", req.unparsed_uri)
+ assert_equal(WEBrick::HTTPVersion.new("1.0"), req.http_version)
+ assert_equal(WEBrick::Config::HTTP[:ServerName], req.host)
+ assert_equal(80, req.port)
+ assert_equal(false, req.keep_alive?)
+ assert_equal(nil, req.body)
+ assert(req.query.empty?)
+ end
+
+ def test_parse_11
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal("GET", req.request_method)
+ assert_equal("/path", req.unparsed_uri)
+ assert_equal("", req.script_name)
+ assert_equal("/path", req.path_info)
+ assert_equal(WEBrick::HTTPVersion.new("1.1"), req.http_version)
+ assert_equal(WEBrick::Config::HTTP[:ServerName], req.host)
+ assert_equal(80, req.port)
+ assert_equal(true, req.keep_alive?)
+ assert_equal(nil, req.body)
+ assert(req.query.empty?)
+ end
+
+ def test_parse_headers
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+ Host: test.ruby-lang.org:8080
+ Connection: close
+ Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1,
+ text/html;level=2;q=0.4, */*;q=0.5
+ Accept-Encoding: compress;q=0.5
+ Accept-Encoding: gzip;q=1.0, identity; q=0.4, *;q=0
+ Accept-Language: en;q=0.5, *; q=0
+ Accept-Language: ja
+ Content-Type: text/plain
+ Content-Length: 7
+
+ foobar
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal(
+ URI.parse("http://test.ruby-lang.org:8080/path"), req.request_uri)
+ assert_equal("test.ruby-lang.org", req.host)
+ assert_equal(8080, req.port)
+ assert_equal(false, req.keep_alive?)
+ assert_equal(
+ %w(text/html;level=1 text/html */* text/html;level=2 text/*),
+ req.accept)
+ assert_equal(%w(gzip compress identity *), req.accept_encoding)
+ assert_equal(%w(ja en *), req.accept_language)
+ assert_equal(7, req.content_length)
+ assert_equal("text/plain", req.content_type)
+ assert_equal("foobar\n", req.body)
+ assert(req.query.empty?)
+ end
+
+ def test_parse_header2()
+ msg = <<-_end_of_message_
+ POST /foo/bar/../baz?q=a HTTP/1.0
+ Content-Length: 9
+ User-Agent:
+ FOO BAR
+ BAZ
+
+ hogehoge
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal("POST", req.request_method)
+ assert_equal("/foo/baz", req.path)
+ assert_equal("", req.script_name)
+ assert_equal("/foo/baz", req.path_info)
+ assert_equal("9", req['content-length'])
+ assert_equal("FOO BAR BAZ", req['user-agent'])
+ assert_equal("hogehoge\n", req.body)
+ end
+
+ def test_parse_headers3
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+ Host: test.ruby-lang.org
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal(URI.parse("http://test.ruby-lang.org/path"), req.request_uri)
+ assert_equal("test.ruby-lang.org", req.host)
+ assert_equal(80, req.port)
+
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+ Host: 192.168.1.1
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal(URI.parse("http://192.168.1.1/path"), req.request_uri)
+ assert_equal("192.168.1.1", req.host)
+ assert_equal(80, req.port)
+
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+ Host: [fe80::208:dff:feef:98c7]
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal(URI.parse("http://[fe80::208:dff:feef:98c7]/path"),
+ req.request_uri)
+ assert_equal("[fe80::208:dff:feef:98c7]", req.host)
+ assert_equal(80, req.port)
+
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+ Host: 192.168.1.1:8080
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal(URI.parse("http://192.168.1.1:8080/path"), req.request_uri)
+ assert_equal("192.168.1.1", req.host)
+ assert_equal(8080, req.port)
+
+ msg = <<-_end_of_message_
+ GET /path HTTP/1.1
+ Host: [fe80::208:dff:feef:98c7]:8080
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ assert_equal(URI.parse("http://[fe80::208:dff:feef:98c7]:8080/path"),
+ req.request_uri)
+ assert_equal("[fe80::208:dff:feef:98c7]", req.host)
+ assert_equal(8080, req.port)
+ end
+
+ def test_parse_get_params
+ param = "foo=1;foo=2;foo=3;bar=x"
+ msg = <<-_end_of_message_
+ GET /path?#{param} HTTP/1.1
+ Host: test.ruby-lang.org:8080
+
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ query = req.query
+ assert_equal("1", query["foo"])
+ assert_equal(["1", "2", "3"], query["foo"].to_ary)
+ assert_equal(["1", "2", "3"], query["foo"].list)
+ assert_equal("x", query["bar"])
+ assert_equal(["x"], query["bar"].list)
+ end
+
+ def test_parse_post_params
+ param = "foo=1;foo=2;foo=3;bar=x"
+ msg = <<-_end_of_message_
+ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
+ Host: test.ruby-lang.org:8080
+ Content-Length: #{param.size}
+ Content-Type: application/x-www-form-urlencoded
+
+ #{param}
+ _end_of_message_
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ query = req.query
+ assert_equal("1", query["foo"])
+ assert_equal(["1", "2", "3"], query["foo"].to_ary)
+ assert_equal(["1", "2", "3"], query["foo"].list)
+ assert_equal("x", query["bar"])
+ assert_equal(["x"], query["bar"].list)
+ end
+
+ def test_chunked
+ crlf = "\x0d\x0a"
+ msg = <<-_end_of_message_
+ POST /path HTTP/1.1
+ Host: test.ruby-lang.org:8080
+ Transfer-Encoding: chunked
+
+ _end_of_message_
+ msg.gsub!(/^ {6}/, "")
+ open(__FILE__){|io|
+ while chunk = io.read(100)
+ msg << chunk.size.to_s(16) << crlf
+ msg << chunk << crlf
+ end
+ }
+ msg << "0" << crlf
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg))
+ assert_equal(File.read(__FILE__), req.body)
+ end
+
+ def test_bad_messages
+ param = "foo=1;foo=2;foo=3;bar=x"
+ msg = <<-_end_of_message_
+ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
+ Host: test.ruby-lang.org:8080
+ Content-Type: application/x-www-form-urlencoded
+
+ #{param}
+ _end_of_message_
+ assert_raises(WEBrick::HTTPStatus::LengthRequired){
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ req.body
+ }
+
+ msg = <<-_end_of_message_
+ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
+ Host: test.ruby-lang.org:8080
+ Content-Length: 100000
+
+ body is too short.
+ _end_of_message_
+ assert_raises(WEBrick::HTTPStatus::BadRequest){
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ req.body
+ }
+
+ msg = <<-_end_of_message_
+ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
+ Host: test.ruby-lang.org:8080
+ Transfer-Encoding: foobar
+
+ body is too short.
+ _end_of_message_
+ assert_raises(WEBrick::HTTPStatus::NotImplemented){
+ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
+ req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
+ req.body
+ }
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_httpserver.rb b/ruby_1_8_6/test/webrick/test_httpserver.rb
new file mode 100644
index 0000000000..eb685f916d
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_httpserver.rb
@@ -0,0 +1,260 @@
+require "test/unit"
+require "net/http"
+require "webrick"
+require File.join(File.dirname(__FILE__), "utils.rb")
+
+class TestWEBrickHTTPServer < Test::Unit::TestCase
+ def test_mount
+ httpd = WEBrick::HTTPServer.new(
+ :Logger => WEBrick::Log.new(TestWEBrick::NullWriter),
+ :DoNotListen=>true
+ )
+ httpd.mount("/", :Root)
+ httpd.mount("/foo", :Foo)
+ httpd.mount("/foo/bar", :Bar, :bar1)
+ httpd.mount("/foo/bar/baz", :Baz, :baz1, :baz2)
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/")
+ assert_equal(:Root, serv)
+ assert_equal([], opts)
+ assert_equal(script_name, "")
+ assert_equal(path_info, "/")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/sub")
+ assert_equal(:Root, serv)
+ assert_equal([], opts)
+ assert_equal(script_name, "")
+ assert_equal(path_info, "/sub")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/sub/")
+ assert_equal(:Root, serv)
+ assert_equal([], opts)
+ assert_equal(script_name, "")
+ assert_equal(path_info, "/sub/")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/foo")
+ assert_equal(:Foo, serv)
+ assert_equal([], opts)
+ assert_equal(script_name, "/foo")
+ assert_equal(path_info, "")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/foo/")
+ assert_equal(:Foo, serv)
+ assert_equal([], opts)
+ assert_equal(script_name, "/foo")
+ assert_equal(path_info, "/")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/foo/sub")
+ assert_equal(:Foo, serv)
+ assert_equal([], opts)
+ assert_equal(script_name, "/foo")
+ assert_equal(path_info, "/sub")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/foo/bar")
+ assert_equal(:Bar, serv)
+ assert_equal([:bar1], opts)
+ assert_equal(script_name, "/foo/bar")
+ assert_equal(path_info, "")
+
+ serv, opts, script_name, path_info = httpd.search_servlet("/foo/bar/baz")
+ assert_equal(:Baz, serv)
+ assert_equal([:baz1, :baz2], opts)
+ assert_equal(script_name, "/foo/bar/baz")
+ assert_equal(path_info, "")
+ end
+
+ class Req
+ attr_reader :port, :host
+ def initialize(addr, port, host)
+ @addr, @port, @host = addr, port, host
+ end
+ def addr
+ [0,0,0,@addr]
+ end
+ end
+
+ def httpd(addr, port, host, ali)
+ config ={
+ :Logger => WEBrick::Log.new(TestWEBrick::NullWriter),
+ :DoNotListen => true,
+ :BindAddress => addr,
+ :Port => port,
+ :ServerName => host,
+ :ServerAlias => ali,
+ }
+ return WEBrick::HTTPServer.new(config)
+ end
+
+ def assert_eql?(v1, v2)
+ assert_equal(v1.object_id, v2.object_id)
+ end
+
+ def test_lookup_server
+ addr1 = "192.168.100.1"
+ addr2 = "192.168.100.2"
+ addrz = "192.168.100.254"
+ local = "127.0.0.1"
+ port1 = 80
+ port2 = 8080
+ port3 = 10080
+ portz = 32767
+ name1 = "www.example.com"
+ name2 = "www2.example.com"
+ name3 = "www3.example.com"
+ namea = "www.example.co.jp"
+ nameb = "www.example.jp"
+ namec = "www2.example.co.jp"
+ named = "www2.example.jp"
+ namez = "foobar.example.com"
+ alias1 = [namea, nameb]
+ alias2 = [namec, named]
+
+ host1 = httpd(nil, port1, name1, nil)
+ hosts = [
+ host2 = httpd(addr1, port1, name1, nil),
+ host3 = httpd(addr1, port1, name2, alias1),
+ host4 = httpd(addr1, port2, name1, nil),
+ host5 = httpd(addr1, port2, name2, alias1),
+ host6 = httpd(addr1, port2, name3, alias2),
+ host7 = httpd(addr2, nil, name1, nil),
+ host8 = httpd(addr2, nil, name2, alias1),
+ host9 = httpd(addr2, nil, name3, alias2),
+ host10 = httpd(local, nil, nil, nil),
+ host11 = httpd(nil, port3, nil, nil),
+ ].sort_by{ rand }
+ hosts.each{|h| host1.virtual_host(h) }
+
+ # connect to addr1
+ assert_eql?(host2, host1.lookup_server(Req.new(addr1, port1, name1)))
+ assert_eql?(host3, host1.lookup_server(Req.new(addr1, port1, name2)))
+ assert_eql?(host3, host1.lookup_server(Req.new(addr1, port1, namea)))
+ assert_eql?(host3, host1.lookup_server(Req.new(addr1, port1, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, port1, namez)))
+ assert_eql?(host4, host1.lookup_server(Req.new(addr1, port2, name1)))
+ assert_eql?(host5, host1.lookup_server(Req.new(addr1, port2, name2)))
+ assert_eql?(host5, host1.lookup_server(Req.new(addr1, port2, namea)))
+ assert_eql?(host5, host1.lookup_server(Req.new(addr1, port2, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, port2, namez)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, name1)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, name2)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, namea)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, nameb)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, namez)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, name1)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, name2)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, namea)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, namez)))
+
+ # connect to addr2
+ assert_eql?(host7, host1.lookup_server(Req.new(addr2, port1, name1)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port1, name2)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port1, namea)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port1, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr2, port1, namez)))
+ assert_eql?(host7, host1.lookup_server(Req.new(addr2, port2, name1)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port2, name2)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port2, namea)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port2, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr2, port2, namez)))
+ assert_eql?(host7, host1.lookup_server(Req.new(addr2, port3, name1)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port3, name2)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port3, namea)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, port3, nameb)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addr2, port3, namez)))
+ assert_eql?(host7, host1.lookup_server(Req.new(addr2, portz, name1)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, portz, name2)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, portz, namea)))
+ assert_eql?(host8, host1.lookup_server(Req.new(addr2, portz, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addr2, portz, namez)))
+
+ # connect to addrz
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, name1)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, name2)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, namea)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, namez)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, name1)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, name2)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, namea)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, namez)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, name1)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, name2)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, namea)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, nameb)))
+ assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, namez)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, name1)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, name2)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, namea)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, nameb)))
+ assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, namez)))
+
+ # connect to localhost
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port1, name1)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port1, name2)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port1, namea)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port1, nameb)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port1, namez)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port2, name1)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port2, name2)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port2, namea)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port2, nameb)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port2, namez)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port3, name1)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port3, name2)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port3, namea)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port3, nameb)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, port3, namez)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, portz, name1)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, portz, name2)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, portz, namea)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, portz, nameb)))
+ assert_eql?(host10, host1.lookup_server(Req.new(local, portz, namez)))
+ end
+
+ def test_callbacks
+ accepted = started = stopped = 0
+ requested0 = requested1 = 0
+ config = {
+ :ServerName => "localhost",
+ :AcceptCallback => Proc.new{ accepted += 1 },
+ :StartCallback => Proc.new{ started += 1 },
+ :StopCallback => Proc.new{ stopped += 1 },
+ :RequestCallback => Proc.new{|req, res| requested0 += 1 },
+ }
+ TestWEBrick.start_httpserver(config){|server, addr, port|
+ vhost_config = {
+ :ServerName => "myhostname",
+ :BindAddress => addr,
+ :Port => port,
+ :DoNotListen => true,
+ :Logger => WEBrick::Log.new(TestWEBrick::NullWriter),
+ :AccessLog => [],
+ :RequestCallback => Proc.new{|req, res| requested1 += 1 },
+ }
+ server.virtual_host(WEBrick::HTTPServer.new(vhost_config))
+
+ true while server.status != :Running
+ assert_equal(started, 1)
+ assert_equal(stopped, 0)
+ assert_equal(accepted, 0)
+
+ http = Net::HTTP.new(addr, port)
+ req = Net::HTTP::Get.new("/")
+ req["Host"] = "myhostname:#{port}"
+ http.request(req){|res| assert_equal("404", res.code)}
+ http.request(req){|res| assert_equal("404", res.code)}
+ http.request(req){|res| assert_equal("404", res.code)}
+ req["Host"] = "localhost:#{port}"
+ http.request(req){|res| assert_equal("404", res.code)}
+ http.request(req){|res| assert_equal("404", res.code)}
+ http.request(req){|res| assert_equal("404", res.code)}
+ assert_equal(6, accepted)
+ assert_equal(3, requested0)
+ assert_equal(3, requested1)
+ }
+ assert_equal(started, 1)
+ assert_equal(stopped, 1)
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_httputils.rb b/ruby_1_8_6/test/webrick/test_httputils.rb
new file mode 100644
index 0000000000..9d39ff53ab
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_httputils.rb
@@ -0,0 +1,96 @@
+require "test/unit"
+require "webrick/httputils"
+
+class TestWEBrickHTTPUtils < Test::Unit::TestCase
+ include WEBrick::HTTPUtils
+
+ def test_normilize_path
+ assert_equal("/foo", normalize_path("/foo"))
+ assert_equal("/foo/bar/", normalize_path("/foo/bar/"))
+
+ assert_equal("/", normalize_path("/foo/../"))
+ assert_equal("/", normalize_path("/foo/.."))
+ assert_equal("/", normalize_path("/foo/bar/../../"))
+ assert_equal("/", normalize_path("/foo/bar/../.."))
+ assert_equal("/", normalize_path("/foo/bar/../.."))
+ assert_equal("/baz", normalize_path("/foo/bar/../../baz"))
+ assert_equal("/baz", normalize_path("/foo/../bar/../baz"))
+ assert_equal("/baz/", normalize_path("/foo/../bar/../baz/"))
+ assert_equal("/...", normalize_path("/bar/../..."))
+ assert_equal("/.../", normalize_path("/bar/../.../"))
+
+ assert_equal("/foo/", normalize_path("/foo/./"))
+ assert_equal("/foo/", normalize_path("/foo/."))
+ assert_equal("/foo/", normalize_path("/foo/././"))
+ assert_equal("/foo/", normalize_path("/foo/./."))
+ assert_equal("/foo/bar", normalize_path("/foo/./bar"))
+ assert_equal("/foo/bar/", normalize_path("/foo/./bar/."))
+ assert_equal("/foo/bar/", normalize_path("/./././foo/./bar/."))
+
+ assert_equal("/foo/bar/", normalize_path("//foo///.//bar/.///.//"))
+ assert_equal("/", normalize_path("//foo///..///bar/.///..//.//"))
+
+ assert_raises(RuntimeError){ normalize_path("foo/bar") }
+ assert_raises(RuntimeError){ normalize_path("..") }
+ assert_raises(RuntimeError){ normalize_path("/..") }
+ assert_raises(RuntimeError){ normalize_path("/./..") }
+ assert_raises(RuntimeError){ normalize_path("/./../") }
+ assert_raises(RuntimeError){ normalize_path("/./../..") }
+ assert_raises(RuntimeError){ normalize_path("/./../../") }
+ assert_raises(RuntimeError){ normalize_path("/./../") }
+ assert_raises(RuntimeError){ normalize_path("/../..") }
+ assert_raises(RuntimeError){ normalize_path("/../../") }
+ assert_raises(RuntimeError){ normalize_path("/../../..") }
+ assert_raises(RuntimeError){ normalize_path("/../../../") }
+ assert_raises(RuntimeError){ normalize_path("/../foo/../") }
+ assert_raises(RuntimeError){ normalize_path("/../foo/../../") }
+ assert_raises(RuntimeError){ normalize_path("/foo/bar/../../../../") }
+ assert_raises(RuntimeError){ normalize_path("/foo/../bar/../../") }
+ assert_raises(RuntimeError){ normalize_path("/./../bar/") }
+ assert_raises(RuntimeError){ normalize_path("/./../") }
+ end
+
+ def test_split_header_value
+ assert_equal(['foo', 'bar'], split_header_value('foo, bar'))
+ assert_equal(['"foo"', 'bar'], split_header_value('"foo", bar'))
+ assert_equal(['foo', '"bar"'], split_header_value('foo, "bar"'))
+ assert_equal(['*'], split_header_value('*'))
+ assert_equal(['W/"xyzzy"', 'W/"r2d2xxxx"', 'W/"c3piozzzz"'],
+ split_header_value('W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz"'))
+ end
+
+ def test_escape
+ assert_equal("/foo/bar", escape("/foo/bar"))
+ assert_equal("/~foo/bar", escape("/~foo/bar"))
+ assert_equal("/~foo%20bar", escape("/~foo bar"))
+ assert_equal("/~foo%20bar", escape("/~foo bar"))
+ assert_equal("/~foo%09bar", escape("/~foo\tbar"))
+ assert_equal("/~foo+bar", escape("/~foo+bar"))
+ end
+
+ def test_escape_form
+ assert_equal("%2Ffoo%2Fbar", escape_form("/foo/bar"))
+ assert_equal("%2F~foo%2Fbar", escape_form("/~foo/bar"))
+ assert_equal("%2F~foo+bar", escape_form("/~foo bar"))
+ assert_equal("%2F~foo+%2B+bar", escape_form("/~foo + bar"))
+ end
+
+ def test_unescape
+ assert_equal("/foo/bar", unescape("%2ffoo%2fbar"))
+ assert_equal("/~foo/bar", unescape("/%7efoo/bar"))
+ assert_equal("/~foo/bar", unescape("%2f%7efoo%2fbar"))
+ assert_equal("/~foo+bar", unescape("/%7efoo+bar"))
+ end
+
+ def test_unescape_form
+ assert_equal("//foo/bar", unescape_form("/%2Ffoo/bar"))
+ assert_equal("//foo/bar baz", unescape_form("/%2Ffoo/bar+baz"))
+ assert_equal("/~foo/bar baz", unescape_form("/%7Efoo/bar+baz"))
+ end
+
+ def test_escape_path
+ assert_equal("/foo/bar", escape_path("/foo/bar"))
+ assert_equal("/foo/bar/", escape_path("/foo/bar/"))
+ assert_equal("/%25foo/bar/", escape_path("/%foo/bar/"))
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_httpversion.rb b/ruby_1_8_6/test/webrick/test_httpversion.rb
new file mode 100644
index 0000000000..81a871a226
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_httpversion.rb
@@ -0,0 +1,40 @@
+require "test/unit"
+require "webrick/httpversion"
+
+class TestWEBrickHTTPVersion < Test::Unit::TestCase
+ def setup
+ @v09 = WEBrick::HTTPVersion.new("0.9")
+ @v10 = WEBrick::HTTPVersion.new("1.0")
+ @v11 = WEBrick::HTTPVersion.new("1.001")
+ end
+
+ def test_to_s()
+ assert_equal("0.9", @v09.to_s)
+ assert_equal("1.0", @v10.to_s)
+ assert_equal("1.1", @v11.to_s)
+ end
+
+ def test_major()
+ assert_equal(0, @v09.major)
+ assert_equal(1, @v10.major)
+ assert_equal(1, @v11.major)
+ end
+
+ def test_minor()
+ assert_equal(9, @v09.minor)
+ assert_equal(0, @v10.minor)
+ assert_equal(1, @v11.minor)
+ end
+
+ def test_compar()
+ assert_equal(0, @v09 <=> "0.9")
+ assert_equal(0, @v09 <=> "0.09")
+
+ assert_equal(-1, @v09 <=> @v10)
+ assert_equal(-1, @v09 <=> "1.00")
+
+ assert_equal(1, @v11 <=> @v09)
+ assert_equal(1, @v11 <=> "1.0")
+ assert_equal(1, @v11 <=> "0.9")
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/test_server.rb b/ruby_1_8_6/test/webrick/test_server.rb
new file mode 100644
index 0000000000..ce5ee85c6c
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/test_server.rb
@@ -0,0 +1,64 @@
+require "test/unit"
+require "tempfile"
+require "webrick"
+require File.join(File.dirname(__FILE__), "utils.rb")
+
+class TestWEBrickServer < Test::Unit::TestCase
+ class Echo < WEBrick::GenericServer
+ def run(sock)
+ while line = sock.gets
+ sock << line
+ end
+ end
+ end
+
+ def test_server
+ TestWEBrick.start_server(Echo){|server, addr, port|
+ TCPSocket.open(addr, port){|sock|
+ sock.puts("foo"); assert_equal("foo\n", sock.gets)
+ sock.puts("bar"); assert_equal("bar\n", sock.gets)
+ sock.puts("baz"); assert_equal("baz\n", sock.gets)
+ sock.puts("qux"); assert_equal("qux\n", sock.gets)
+ }
+ }
+ end
+
+ def test_callbacks
+ accepted = started = stopped = 0
+ config = {
+ :AcceptCallback => Proc.new{ accepted += 1 },
+ :StartCallback => Proc.new{ started += 1 },
+ :StopCallback => Proc.new{ stopped += 1 },
+ }
+ TestWEBrick.start_server(Echo, config){|server, addr, port|
+ true while server.status != :Running
+ assert_equal(started, 1)
+ assert_equal(stopped, 0)
+ assert_equal(accepted, 0)
+ TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
+ TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
+ TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
+ assert_equal(accepted, 3)
+ }
+ assert_equal(started, 1)
+ assert_equal(stopped, 1)
+ end
+
+ def test_daemon
+ begin
+ r, w = IO.pipe
+ Process.fork{
+ r.close
+ WEBrick::Daemon.start
+ w.puts(Process.pid)
+ sleep
+ }
+ assert(Process.kill(:KILL, r.gets.to_i))
+ rescue NotImplementedError
+ # snip this test
+ ensure
+ r.close
+ w.close
+ end
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/utils.rb b/ruby_1_8_6/test/webrick/utils.rb
new file mode 100644
index 0000000000..f1e6e4b027
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/utils.rb
@@ -0,0 +1,40 @@
+require "webrick"
+begin
+ require "webrick/https"
+rescue LoadError
+end
+require "webrick/httpproxy"
+
+module TestWEBrick
+ NullWriter = Object.new
+ def NullWriter.<<(msg)
+ puts msg if $DEBUG
+ return self
+ end
+
+ module_function
+
+ def start_server(klass, config={}, &block)
+ server = klass.new({
+ :BindAddress => "127.0.0.1", :Port => 0,
+ :Logger => WEBrick::Log.new(NullWriter),
+ :AccessLog => [[NullWriter, ""]]
+ }.update(config))
+ begin
+ thread = Thread.start{ server.start }
+ addr = server.listeners[0].addr
+ block.call([server, addr[3], addr[1]])
+ ensure
+ server.stop
+ thread.join
+ end
+ end
+
+ def start_httpserver(config={}, &block)
+ start_server(WEBrick::HTTPServer, config, &block)
+ end
+
+ def start_httpproxy(config={}, &block)
+ start_server(WEBrick::HTTPProxyServer, config, &block)
+ end
+end
diff --git a/ruby_1_8_6/test/webrick/webrick.cgi b/ruby_1_8_6/test/webrick/webrick.cgi
new file mode 100644
index 0000000000..73ba729407
--- /dev/null
+++ b/ruby_1_8_6/test/webrick/webrick.cgi
@@ -0,0 +1,36 @@
+#!ruby -d
+require "webrick/cgi"
+
+class TestApp < WEBrick::CGI
+ def do_GET(req, res)
+ res["content-type"] = "text/plain"
+ if (p = req.path_info) && p.length > 0
+ res.body = p
+ elsif (q = req.query).size > 0
+ res.body = q.keys.sort.collect{|key|
+ q[key].list.sort.collect{|v|
+ "#{key}=#{v}"
+ }.join(", ")
+ }.join(", ")
+ elsif %r{/$} =~ req.request_uri.to_s
+ res.body = ""
+ res.body << req.request_uri.to_s << "\n"
+ res.body << req.script_name
+ elsif !req.cookies.empty?
+ res.body = req.cookies.inject(""){|result, cookie|
+ result << "%s=%s\n" % [cookie.name, cookie.value]
+ }
+ res.cookies << WEBrick::Cookie.new("Customer", "WILE_E_COYOTE")
+ res.cookies << WEBrick::Cookie.new("Shipping", "FedEx")
+ else
+ res.body = req.script_name
+ end
+ end
+
+ def do_POST(req, res)
+ do_GET(req, res)
+ end
+end
+
+cgi = TestApp.new
+cgi.start
diff --git a/ruby_1_8_6/test/wsdl/any/any.wsdl b/ruby_1_8_6/test/wsdl/any/any.wsdl
new file mode 100644
index 0000000000..4d1f73a8cd
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/any/any.wsdl
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name="echo"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="urn:example.com:echo"
+ xmlns:txd="urn:example.com:echo-type"
+ targetNamespace="urn:example.com:echo"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema targetNamespace="urn:example.com:echo-type">
+ <xsd:complexType name="foo.bar">
+ <xsd:sequence>
+ <xsd:any />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:schema>
+ </types>
+
+ <message name="msg_echoitem">
+ <part name="echoitem" type="txd:foo.bar"/>
+ </message>
+
+ <portType name="echo_port_type">
+ <operation name="echo">
+ <input message="tns:msg_echoitem"/>
+ <output message="tns:msg_echoitem"/>
+ </operation>
+ </portType>
+
+ <binding name="echo_binding" type="tns:echo_port_type">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
+ <operation name="echo">
+ <soap:operation soapAction="urn:example.com:echo"/>
+ <input>
+ <soap:body use="encoded" namespace="urn:example.com:echo"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:example.com:echo"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="echo_service">
+ <port name="echo_port" binding="tns:echo_binding">
+ <soap:address location="http://localhost:10080"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/any/expectedDriver.rb b/ruby_1_8_6/test/wsdl/any/expectedDriver.rb
new file mode 100644
index 0000000000..6d1827fb94
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/any/expectedDriver.rb
@@ -0,0 +1,54 @@
+require 'echo.rb'
+
+require 'soap/rpc/driver'
+
+class Echo_port_type < ::SOAP::RPC::Driver
+ DefaultEndpointUrl = "http://localhost:10080"
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ FooBar,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:example.com:echo-type", "foo.bar") }
+ )
+
+ Methods = [
+ [ XSD::QName.new("urn:example.com:echo", "echo"),
+ "urn:example.com:echo",
+ "echo",
+ [ ["in", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]],
+ ["retval", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]] ],
+ { :request_style => :rpc, :request_use => :encoded,
+ :response_style => :rpc, :response_use => :encoded }
+ ]
+ ]
+
+ def initialize(endpoint_url = nil)
+ endpoint_url ||= DefaultEndpointUrl
+ super(endpoint_url, nil)
+ self.mapping_registry = MappingRegistry
+ init_methods
+ end
+
+private
+
+ def init_methods
+ Methods.each do |definitions|
+ opt = definitions.last
+ if opt[:request_style] == :document
+ add_document_operation(*definitions)
+ else
+ add_rpc_operation(*definitions)
+ qname = definitions[0]
+ name = definitions[2]
+ if qname.name != name and qname.name.capitalize == name.capitalize
+ ::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg|
+ __send__(name, *arg)
+ end
+ end
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/wsdl/any/expectedEcho.rb b/ruby_1_8_6/test/wsdl/any/expectedEcho.rb
new file mode 100644
index 0000000000..456950dfef
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/any/expectedEcho.rb
@@ -0,0 +1,14 @@
+require 'xsd/qname'
+
+# {urn:example.com:echo-type}foo.bar
+class FooBar
+ @@schema_type = "foo.bar"
+ @@schema_ns = "urn:example.com:echo-type"
+ @@schema_element = [["any", [nil, XSD::QName.new(nil, "any")]]]
+
+ attr_accessor :any
+
+ def initialize(any = nil)
+ @any = any
+ end
+end
diff --git a/ruby_1_8_6/test/wsdl/any/expectedService.rb b/ruby_1_8_6/test/wsdl/any/expectedService.rb
new file mode 100644
index 0000000000..e3885e7c6c
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/any/expectedService.rb
@@ -0,0 +1,52 @@
+#!/usr/bin/env ruby
+require 'echoServant.rb'
+
+require 'soap/rpc/standaloneServer'
+require 'soap/mapping/registry'
+
+class Echo_port_type
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ FooBar,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:example.com:echo-type", "foo.bar") }
+ )
+
+ Methods = [
+ [ XSD::QName.new("urn:example.com:echo", "echo"),
+ "urn:example.com:echo",
+ "echo",
+ [ ["in", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]],
+ ["retval", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]] ],
+ { :request_style => :rpc, :request_use => :encoded,
+ :response_style => :rpc, :response_use => :encoded }
+ ]
+ ]
+end
+
+class Echo_port_typeApp < ::SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super(*arg)
+ servant = Echo_port_type.new
+ Echo_port_type::Methods.each do |definitions|
+ opt = definitions.last
+ if opt[:request_style] == :document
+ @router.add_document_operation(servant, *definitions)
+ else
+ @router.add_rpc_operation(servant, *definitions)
+ end
+ end
+ self.mapping_registry = Echo_port_type::MappingRegistry
+ end
+end
+
+if $0 == __FILE__
+ # Change listen port.
+ server = Echo_port_typeApp.new('app', nil, '0.0.0.0', 10080)
+ trap(:INT) do
+ server.shutdown
+ end
+ server.start
+end
diff --git a/ruby_1_8_6/test/wsdl/any/test_any.rb b/ruby_1_8_6/test/wsdl/any/test_any.rb
new file mode 100644
index 0000000000..aab5eb631f
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/any/test_any.rb
@@ -0,0 +1,58 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/wsdl2ruby'
+module WSDL; module Any
+
+
+class TestAny < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def test_any
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("any.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['driver'] = nil
+ gen.opt['client_skelton'] = nil
+ gen.opt['servant_skelton'] = nil
+ gen.opt['standalone_server_stub'] = nil
+ gen.opt['force'] = true
+ suppress_warning do
+ gen.run
+ end
+ compare("expectedDriver.rb", "echoDriver.rb")
+ compare("expectedEcho.rb", "echo.rb")
+ compare("expectedService.rb", "echo_service.rb")
+
+ File.unlink(pathname("echo_service.rb"))
+ File.unlink(pathname("echo.rb"))
+ File.unlink(pathname("echo_serviceClient.rb"))
+ File.unlink(pathname("echoDriver.rb"))
+ File.unlink(pathname("echoServant.rb"))
+ end
+
+ def compare(expected, actual)
+ assert_equal(loadfile(expected), loadfile(actual), actual)
+ end
+
+ def loadfile(file)
+ File.open(pathname(file)) { |f| f.read }
+ end
+
+ def suppress_warning
+ back = $VERBOSE
+ $VERBOSE = nil
+ begin
+ yield
+ ensure
+ $VERBOSE = back
+ end
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/wsdl/axisArray/axisArray.wsdl b/ruby_1_8_6/test/wsdl/axisArray/axisArray.wsdl
new file mode 100644
index 0000000000..3602edb748
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/axisArray/axisArray.wsdl
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<wsdl:definitions name = "itemList"
+ targetNamespace="urn:jp.gr.jin.rrr.example.itemList"
+ xmlns:tns="urn:jp.gr.jin.rrr.example.itemList"
+ xmlns:typens="urn:jp.gr.jin.rrr.example.itemListType"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+ <wsdl:types>
+ <schema targetNamespace="urn:jp.gr.jin.rrr.example.itemListType"
+ xmlns="http://www.w3.org/2001/XMLSchema">
+ <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+ <complexType name="Item">
+ <sequence>
+ <element name="name" type="xsd:string"/>
+ </sequence>
+ </complexType>
+ <complexType name="ItemList">
+ <sequence>
+ <element maxOccurs="unbounded" minOccurs="0" name="Item" type="typens:Item"/>
+ </sequence>
+ </complexType>
+ </schema>
+ </wsdl:types>
+
+ <wsdl:message name="listItemRequest"/>
+
+ <wsdl:message name="listItemResponse">
+ <wsdl:part name="list" type="typens:ItemList"/>
+ </wsdl:message>
+
+ <wsdl:portType name="ItemListPortType">
+ <wsdl:operation name="listItem">
+ <wsdl:input message="tns:listItemRequest" name="listItemRequest"/>
+ <wsdl:output message="tns:listItemResponse" name="listItemResponse"/>
+ </wsdl:operation>
+ </wsdl:portType>
+
+ <wsdl:binding name="ItemListBinding" type="tns:ItemListPortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <wsdl:operation name="listItem">
+ <soap:operation soapAction=""/>
+ <wsdl:input name="listItemRequest">
+ <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:jp.gr.jin.rrr.example.itemList" use="encoded"/>
+ </wsdl:input>
+ <wsdl:output name="listItemResponse">
+ <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:jp.gr.jin.rrr.example.itemList" use="encoded"/>
+ </wsdl:output>
+ </wsdl:operation>
+ </wsdl:binding>
+
+ <wsdl:service name="ItemListService">
+ <wsdl:port binding="tns:ItemListBinding" name="ItemListPort">
+ <soap:address location="http://localhost:10080/"/>
+ </wsdl:port>
+ </wsdl:service>
+</wsdl:definitions>
diff --git a/ruby_1_8_6/test/wsdl/axisArray/itemList.rb b/ruby_1_8_6/test/wsdl/axisArray/itemList.rb
new file mode 100644
index 0000000000..b81297ed37
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/axisArray/itemList.rb
@@ -0,0 +1,27 @@
+# Generated by wsdl2ruby.rb with axisArray.wsdl.
+
+# urn:jp.gr.jin.rrr.example.itemListType
+class Item
+ @@schema_type = "Item"
+ @@schema_ns = "urn:jp.gr.jin.rrr.example.itemListType"
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def initialize(name = nil)
+ @name = name
+ end
+end
+
+# urn:jp.gr.jin.rrr.example.itemListType
+class ItemList < Array
+ # Contents type should be dumped here...
+ @@schema_type = "ItemList"
+ @@schema_ns = "urn:jp.gr.jin.rrr.example.itemListType"
+end
+
diff --git a/ruby_1_8_6/test/wsdl/axisArray/test_axisarray.rb b/ruby_1_8_6/test/wsdl/axisArray/test_axisarray.rb
new file mode 100644
index 0000000000..9f220bb48a
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/axisArray/test_axisarray.rb
@@ -0,0 +1,69 @@
+require 'test/unit'
+require 'soap/processor'
+require 'soap/mapping'
+require 'soap/rpc/element'
+require 'wsdl/importer'
+require 'itemList.rb'
+
+
+module WSDL
+
+
+class TestAxisArray < Test::Unit::TestCase
+ def setup
+ @xml =<<__EOX__
+<?xml version="1.0" encoding="UTF-8"?>
+<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <soapenv:Body>
+ <ns1:listItemResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:jp.gr.jin.rrr.example.itemList">
+ <list href="#id0"/>
+ </ns1:listItemResponse>
+ <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns2:ItemList" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="urn:jp.gr.jin.rrr.example.itemListType">
+ <Item href="#id1"/>
+ <Item href="#id2"/>
+ <Item href="#id3"/>
+ </multiRef>
+ <multiRef id="id3" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns3:Item" xmlns:ns3="urn:jp.gr.jin.rrr.example.itemListType" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
+ <name xsi:type="xsd:string">name3</name>
+ </multiRef>
+ <multiRef id="id1" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns4:Item" xmlns:ns4="urn:jp.gr.jin.rrr.example.itemListType" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
+ <name xsi:type="xsd:string">name1</name>
+ </multiRef>
+ <multiRef id="id2" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns5:Item" xmlns:ns5="urn:jp.gr.jin.rrr.example.itemListType" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
+ <name xsi:type="xsd:string">name2</name>
+ </multiRef>
+ </soapenv:Body>
+</soapenv:Envelope>
+__EOX__
+ end
+
+ def test_by_stub
+ header, body = ::SOAP::Processor.unmarshal(@xml)
+ ary = ::SOAP::Mapping.soap2obj(body.response)
+ assert_equal(3, ary.size)
+ assert_equal("name1", ary[0].name)
+ assert_equal("name2", ary[1].name)
+ assert_equal("name3", ary[2].name)
+ end
+
+ def test_by_wsdl
+ wsdlfile = File.join(File.dirname(File.expand_path(__FILE__)), 'axisArray.wsdl')
+ wsdl = WSDL::Importer.import(wsdlfile)
+ service = wsdl.services[0]
+ port = service.ports[0]
+ wsdl_types = wsdl.collect_complextypes
+ rpc_decode_typemap = wsdl_types + wsdl.soap_rpc_complextypes(port.find_binding)
+ opt = {}
+ opt[:default_encodingstyle] = ::SOAP::EncodingNamespace
+ opt[:decode_typemap] = rpc_decode_typemap
+ header, body = ::SOAP::Processor.unmarshal(@xml, opt)
+ ary = ::SOAP::Mapping.soap2obj(body.response)
+ assert_equal(3, ary.size)
+ assert_equal("name1", ary[0].name)
+ assert_equal("name2", ary[1].name)
+ assert_equal("name3", ary[2].name)
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/wsdl/datetime/DatetimeService.rb b/ruby_1_8_6/test/wsdl/datetime/DatetimeService.rb
new file mode 100644
index 0000000000..800e06d66f
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/datetime/DatetimeService.rb
@@ -0,0 +1,44 @@
+#!/usr/bin/env ruby
+require 'datetimeServant.rb'
+
+require 'soap/rpc/standaloneServer'
+require 'soap/mapping/registry'
+
+class DatetimePortType
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ Methods = [
+ ["now", "now",
+ [
+ ["in", "now", [::SOAP::SOAPDateTime]],
+ ["retval", "now", [::SOAP::SOAPDateTime]]
+ ],
+ "", "urn:jp.gr.jin.rrr.example.datetime", :rpc
+ ]
+ ]
+end
+
+class DatetimePortTypeApp < ::SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super(*arg)
+ servant = DatetimePortType.new
+ DatetimePortType::Methods.each do |name_as, name, param_def, soapaction, namespace, style|
+ if style == :document
+ @router.add_document_operation(servant, soapaction, name, param_def)
+ else
+ qname = XSD::QName.new(namespace, name_as)
+ @router.add_rpc_operation(servant, qname, soapaction, name, param_def)
+ end
+ end
+ self.mapping_registry = DatetimePortType::MappingRegistry
+ end
+end
+
+if $0 == __FILE__
+ # Change listen port.
+ server = DatetimePortTypeApp.new('app', nil, '0.0.0.0', 10080)
+ trap(:INT) do
+ server.shutdown
+ end
+ server.start
+end
diff --git a/ruby_1_8_6/test/wsdl/datetime/datetime.rb b/ruby_1_8_6/test/wsdl/datetime/datetime.rb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/datetime/datetime.rb
diff --git a/ruby_1_8_6/test/wsdl/datetime/datetime.wsdl b/ruby_1_8_6/test/wsdl/datetime/datetime.wsdl
new file mode 100644
index 0000000000..4998dc48d6
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/datetime/datetime.wsdl
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<wsdl:definitions name = "datetime"
+ targetNamespace="urn:jp.gr.jin.rrr.example.datetime"
+ xmlns:tns="urn:jp.gr.jin.rrr.example.datetime"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+ <wsdl:message name="nowRequest">
+ <wsdl:part name="now" type="xsd:dateTime"/>
+ </wsdl:message>
+
+ <wsdl:message name="nowResponse">
+ <wsdl:part name="now" type="xsd:dateTime"/>
+ </wsdl:message>
+
+ <wsdl:portType name="DatetimePortType">
+ <wsdl:operation name="now">
+ <wsdl:input message="tns:nowRequest" name="nowRequest"/>
+ <wsdl:output message="tns:nowResponse" name="nowResponse"/>
+ </wsdl:operation>
+ </wsdl:portType>
+
+ <wsdl:binding name="DatetimeBinding" type="tns:DatetimePortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <wsdl:operation name="now">
+ <soap:operation soapAction=""/>
+ <wsdl:input name="nowRequest">
+ <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:jp.gr.jin.rrr.example.datetime" use="encoded"/>
+ </wsdl:input>
+ <wsdl:output name="nowResponse">
+ <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:jp.gr.jin.rrr.example.datetime" use="encoded"/>
+ </wsdl:output>
+ </wsdl:operation>
+ </wsdl:binding>
+
+ <wsdl:service name="DatetimeService">
+ <wsdl:port binding="tns:DatetimeBinding" name="DatetimePort">
+ <soap:address location="http://localhost:10080/"/>
+ </wsdl:port>
+ </wsdl:service>
+</wsdl:definitions>
diff --git a/ruby_1_8_6/test/wsdl/datetime/datetimeServant.rb b/ruby_1_8_6/test/wsdl/datetime/datetimeServant.rb
new file mode 100644
index 0000000000..14145c42e5
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/datetime/datetimeServant.rb
@@ -0,0 +1,21 @@
+require 'datetime.rb'
+
+class DatetimePortType
+ # SYNOPSIS
+ # now(now)
+ #
+ # ARGS
+ # now - {http://www.w3.org/2001/XMLSchema}dateTime
+ #
+ # RETURNS
+ # now - {http://www.w3.org/2001/XMLSchema}dateTime
+ #
+ # RAISES
+ # (undefined)
+ #
+ def now(now)
+ #raise NotImplementedError.new
+ now + 1
+ end
+end
+
diff --git a/ruby_1_8_6/test/wsdl/datetime/test_datetime.rb b/ruby_1_8_6/test/wsdl/datetime/test_datetime.rb
new file mode 100644
index 0000000000..7652318205
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/datetime/test_datetime.rb
@@ -0,0 +1,82 @@
+require 'test/unit'
+require 'soap/wsdlDriver'
+require 'DatetimeService.rb'
+
+
+module WSDL
+module Datetime
+
+
+class TestDatetime < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = DatetimePortTypeApp.new('Datetime server', nil, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'datetime.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.generate_explicit_type = true
+ @client.wiredump_dev = STDOUT if $DEBUG
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def test_datetime
+ d = DateTime.now
+ d1 = d + 1
+ d2 = @client.now(d)
+ assert_equal(d1.year, d2.year)
+ assert_equal(d1.month, d2.month)
+ assert_equal(d1.day, d2.day)
+ assert_equal(d1.hour, d2.hour)
+ assert_equal(d1.min, d2.min)
+ assert_equal(d1.sec, d2.sec)
+ assert_equal(d1.sec, d2.sec)
+ end
+
+ def test_time
+ d = DateTime.now
+ t = Time.gm(d.year, d.month, d.day, d.hour, d.min, d.sec)
+ d1 = d + 1
+ d2 = @client.now(t)
+ assert_equal(d1.year, d2.year)
+ assert_equal(d1.month, d2.month)
+ assert_equal(d1.day, d2.day)
+ assert_equal(d1.hour, d2.hour)
+ assert_equal(d1.min, d2.min)
+ assert_equal(d1.sec, d2.sec)
+ assert_equal(d1.sec, d2.sec)
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/wsdl/document/document.wsdl b/ruby_1_8_6/test/wsdl/document/document.wsdl
new file mode 100644
index 0000000000..fbf03fae8b
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/document.wsdl
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions
+ name="echo"
+ targetNamespace="urn:docrpc"
+ xmlns:tns="urn:docrpc"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema elementFormDefault="unqualified" targetNamespace="urn:docrpc">
+ <xsd:complexType name="echo_struct">
+ <xsd:sequence>
+ <xsd:element minOccurs="0" maxOccurs="1" name="m_string" type="xsd:string" />
+ <xsd:element minOccurs="0" maxOccurs="1" name="m_datetime" type="xsd:dateTime" />
+ </xsd:sequence>
+ <xsd:attribute name="m_attr" type="xsd:string" />
+ </xsd:complexType>
+
+ <xsd:element name="echoele">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element minOccurs="0" maxOccurs="1" name="struct1" type="tns:echo_struct" />
+ <xsd:element minOccurs="0" maxOccurs="1" name="struct-2" type="tns:echo_struct" />
+ </xsd:sequence>
+ <xsd:attribute name="attr_string" type="xsd:string" />
+ <xsd:attribute name="attr-int" type="xsd:int" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="echo_response">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element minOccurs="0" maxOccurs="1" name="struct1" type="tns:echo_struct" />
+ <xsd:element minOccurs="0" maxOccurs="1" name="struct-2" type="tns:echo_struct" />
+ </xsd:sequence>
+ <xsd:attribute name="attr_string" type="xsd:string" />
+ <xsd:attribute name="attr-int" type="xsd:int" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ </types>
+
+ <message name="echo_in">
+ <part name="parameters" element="tns:echoele" />
+ </message>
+ <message name="echo_out">
+ <part name="parameters" element="tns:echo_response" />
+ </message>
+
+ <portType name="docrpc_porttype">
+ <operation name="echo">
+ <input message="tns:echo_in" />
+ <output message="tns:echo_out" />
+ </operation>
+ </portType>
+
+ <binding name="docrpc_binding" type="tns:docrpc_porttype">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+ <operation name="echo">
+ <soap:operation soapAction="urn:docrpc:echo" style="document" />
+ <input>
+ <soap:body use="literal" />
+ </input>
+ <output>
+ <soap:body use="literal" />
+ </output>
+ </operation>
+ </binding>
+
+ <service name="docrpc_service">
+ <port name="docprc_service_port" binding="tns:docrpc_binding">
+ <soap:address location="http://localhost:17171/" />
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/document/echo.rb b/ruby_1_8_6/test/wsdl/document/echo.rb
new file mode 100644
index 0000000000..c6df75aca0
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/echo.rb
@@ -0,0 +1,92 @@
+require 'xsd/qname'
+
+# {urn:docrpc}echoele
+class Echoele
+ @@schema_type = "echoele"
+ @@schema_ns = "urn:docrpc"
+ @@schema_attribute = {XSD::QName.new(nil, "attr_string") => "SOAP::SOAPString", XSD::QName.new(nil, "attr-int") => "SOAP::SOAPInt"}
+ @@schema_element = [["struct1", ["Echo_struct", XSD::QName.new(nil, "struct1")]], ["struct_2", ["Echo_struct", XSD::QName.new(nil, "struct-2")]]]
+
+ attr_accessor :struct1
+ attr_accessor :struct_2
+
+ def xmlattr_attr_string
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")]
+ end
+
+ def xmlattr_attr_string=(value)
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")] = value
+ end
+
+ def xmlattr_attr_int
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")]
+ end
+
+ def xmlattr_attr_int=(value)
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")] = value
+ end
+
+ def initialize(struct1 = nil, struct_2 = nil)
+ @struct1 = struct1
+ @struct_2 = struct_2
+ @__xmlattr = {}
+ end
+end
+
+# {urn:docrpc}echo_response
+class Echo_response
+ @@schema_type = "echo_response"
+ @@schema_ns = "urn:docrpc"
+ @@schema_attribute = {XSD::QName.new(nil, "attr_string") => "SOAP::SOAPString", XSD::QName.new(nil, "attr-int") => "SOAP::SOAPInt"}
+ @@schema_element = [["struct1", ["Echo_struct", XSD::QName.new(nil, "struct1")]], ["struct_2", ["Echo_struct", XSD::QName.new(nil, "struct-2")]]]
+
+ attr_accessor :struct1
+ attr_accessor :struct_2
+
+ def xmlattr_attr_string
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")]
+ end
+
+ def xmlattr_attr_string=(value)
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")] = value
+ end
+
+ def xmlattr_attr_int
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")]
+ end
+
+ def xmlattr_attr_int=(value)
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")] = value
+ end
+
+ def initialize(struct1 = nil, struct_2 = nil)
+ @struct1 = struct1
+ @struct_2 = struct_2
+ @__xmlattr = {}
+ end
+end
+
+# {urn:docrpc}echo_struct
+class Echo_struct
+ @@schema_type = "echo_struct"
+ @@schema_ns = "urn:docrpc"
+ @@schema_attribute = {XSD::QName.new(nil, "m_attr") => "SOAP::SOAPString"}
+ @@schema_element = [["m_string", ["SOAP::SOAPString", XSD::QName.new(nil, "m_string")]], ["m_datetime", ["SOAP::SOAPDateTime", XSD::QName.new(nil, "m_datetime")]]]
+
+ attr_accessor :m_string
+ attr_accessor :m_datetime
+
+ def xmlattr_m_attr
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "m_attr")]
+ end
+
+ def xmlattr_m_attr=(value)
+ (@__xmlattr ||= {})[XSD::QName.new(nil, "m_attr")] = value
+ end
+
+ def initialize(m_string = nil, m_datetime = nil)
+ @m_string = m_string
+ @m_datetime = m_datetime
+ @__xmlattr = {}
+ end
+end
diff --git a/ruby_1_8_6/test/wsdl/document/number.wsdl b/ruby_1_8_6/test/wsdl/document/number.wsdl
new file mode 100644
index 0000000000..cc3dd8e9f0
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/number.wsdl
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions
+ name="foo"
+ targetNamespace="urn:foo"
+ xmlns:tns="urn:foo"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema elementFormDefault="unqualified" targetNamespace="urn:foo">
+ <xsd:element name="get_foo">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element minOccurs="0" maxOccurs="1" name="number" type="xsd:string" />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ </types>
+
+ <message name="get_foo_in">
+ <part name="parameters" element="tns:get_foo" />
+ </message>
+ <message name="get_foo_out">
+ <part name="parameters" type="xsd:string" />
+ </message>
+
+ <portType name="foo_porttype">
+ <operation name="get_foo">
+ <input message="tns:get_foo_in" />
+ <output message="tns:get_foo_out" />
+ </operation>
+ </portType>
+
+ <binding name="foo_binding" type="tns:foo_porttype">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
+ style="document" />
+ <operation name="get_foo">
+ <soap:operation soapAction="urn:foo:get_foo" style="document" />
+ <input>
+ <soap:body use="literal" />
+ </input>
+ <output>
+ <soap:body use="literal" />
+ </output>
+ </operation>
+ </binding>
+
+ <service name="foo_service">
+ <port name="foo_service_port" binding="tns:foo_binding">
+ <soap:address location="http://localhost:17171/" />
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/document/ping_nosoapaction.wsdl b/ruby_1_8_6/test/wsdl/document/ping_nosoapaction.wsdl
new file mode 100644
index 0000000000..ab9529e456
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/ping_nosoapaction.wsdl
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions xmlns:tns="http://xmlsoap.org/Ping"
+xmlns="http://schemas.xmlsoap.org/wsdl/"
+xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+targetNamespace="http://xmlsoap.org/Ping" name="Ping">
+ <types>
+ <schema targetNamespace="http://xmlsoap.org/Ping"
+ xmlns="http://www.w3.org/2001/XMLSchema"
+ elementFormDefault="qualified">
+ <complexType name="ping">
+ <sequence>
+ <element name="scenario" type="xsd:string"
+ nillable="true"/>
+ <element name="origin" type="xsd:string"
+ nillable="true"/>
+ <element name="text" type="xsd:string"
+ nillable="true"/>
+ </sequence>
+ </complexType>
+ <complexType name="pingResponse">
+ <sequence>
+ <element name="scenario" type="xsd:string"
+ nillable="true"/>
+ <element name="origin" type="xsd:string"
+ nillable="true"/>
+ <element name="text" type="xsd:string"
+ nillable="true"/>
+ </sequence>
+ </complexType>
+ <element name="Ping" type="tns:ping"/>
+ <element name="PingResponse" type="tns:pingResponse"/>
+ </schema>
+ </types>
+ <message name="PingRequest">
+ <part name="ping" element="tns:Ping"/>
+ </message>
+ <message name="PingResponse">
+ <part name="pingResponse" element="tns:PingResponse"/>
+ </message>
+ <portType name="PingPort">
+ <operation name="Ping">
+ <input message="tns:PingRequest"/>
+ <output message="tns:PingResponse"/>
+ </operation>
+ </portType>
+ <binding name="PingBinding" type="tns:PingPort">
+ <soap:binding style="document"
+ transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="Ping">
+ <soap:operation/>
+ <input>
+ <soap:body use="literal"/>
+ </input>
+ <output>
+ <soap:body use="literal"/>
+ </output>
+ </operation>
+ </binding>
+ <service name="PingService">
+ <port name="PingPort" binding="tns:PingBinding">
+ <soap:address
+ location="http://127.0.0.1:8080/axis/services/PingPort"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/document/test_nosoapaction.rb b/ruby_1_8_6/test/wsdl/document/test_nosoapaction.rb
new file mode 100644
index 0000000000..77f642fe1b
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/test_nosoapaction.rb
@@ -0,0 +1,109 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+require 'soap/rpc/driver'
+
+
+module WSDL; module Document
+
+
+class TestNoSOAPAction < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = 'http://xmlsoap.org/Ping'
+
+ def on_init
+ add_document_method(
+ self,
+ Namespace + '/ping',
+ 'ping_with_soapaction',
+ XSD::QName.new(Namespace, 'Ping'),
+ XSD::QName.new(Namespace, 'PingResponse')
+ )
+
+ add_document_method(
+ self,
+ nil,
+ 'ping',
+ XSD::QName.new(Namespace, 'Ping'),
+ XSD::QName.new(Namespace, 'PingResponse')
+ )
+
+ # When no SOAPAction given, latter method(ping) is called.
+ end
+
+ def ping(arg)
+ arg.text = 'ping'
+ arg
+ end
+
+ def ping_with_soapaction(arg)
+ arg.text = 'ping_with_soapaction'
+ arg
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', Server::Namespace, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_with_soapaction
+ wsdl = File.join(DIR, 'ping_nosoapaction.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDOUT if $DEBUG
+ rv = @client.ping(:scenario => 'scenario', :origin => 'origin',
+ :text => 'text')
+ assert_equal('scenario', rv.scenario)
+ assert_equal('origin', rv.origin)
+ assert_equal('ping', rv.text)
+ end
+
+ def test_without_soapaction
+ @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/",
+ Server::Namespace)
+ @client.add_document_method('ping', Server::Namespace + '/ping',
+ XSD::QName.new(Server::Namespace, 'Ping'),
+ XSD::QName.new(Server::Namespace, 'PingResponse'))
+ @client.wiredump_dev = STDOUT if $DEBUG
+ rv = @client.ping(:scenario => 'scenario', :origin => 'origin',
+ :text => 'text')
+ assert_equal('scenario', rv.scenario)
+ assert_equal('origin', rv.origin)
+ assert_equal('ping_with_soapaction', rv.text)
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/wsdl/document/test_number.rb b/ruby_1_8_6/test/wsdl/document/test_number.rb
new file mode 100644
index 0000000000..a640ef2a25
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/test_number.rb
@@ -0,0 +1,99 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+
+module WSDL; module Document
+
+
+class TestNumber < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = 'urn:foo'
+
+ def on_init
+ add_document_method(
+ self,
+ Namespace + ':get_foo',
+ 'get_foo',
+ XSD::QName.new(Namespace, 'get_foo'),
+ XSD::QName.new(Namespace, 'get_foo_response')
+ )
+ end
+
+ def get_foo(arg)
+ arg.number
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_classdef
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ File.unlink(pathname('foo.rb'))
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:rpc", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_classdef
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("number.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['force'] = true
+ gen.run
+ require pathname('foo')
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def test_wsdl
+ wsdl = File.join(DIR, 'number.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDOUT if $DEBUG
+
+ # with the Struct defined in foo.rb, which is generated from WSDL
+ assert_equal("12345", @client.get_foo(Get_foo.new("12345")))
+
+ # with Hash
+ assert_equal("12345", @client.get_foo({:number => "12345"}))
+
+ # with Original struct
+ get_foo_struct = Struct.new(:number)
+ assert_equal("12345", @client.get_foo(get_foo_struct.new("12345")))
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/wsdl/document/test_rpc.rb b/ruby_1_8_6/test/wsdl/document/test_rpc.rb
new file mode 100644
index 0000000000..56cd0677ad
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/document/test_rpc.rb
@@ -0,0 +1,177 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+
+module WSDL; module Document
+
+
+class TestRPC < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = 'urn:docrpc'
+
+ def on_init
+ add_document_method(
+ self,
+ Namespace + ':echo',
+ 'echo',
+ XSD::QName.new(Namespace, 'echo'),
+ XSD::QName.new(Namespace, 'echo_response')
+ )
+ end
+
+ def echo(arg)
+ if arg.is_a?(Echoele)
+ # swap args
+ tmp = arg.struct1
+ arg.struct1 = arg.struct_2
+ arg.struct_2 = tmp
+ arg
+ else
+ # swap args
+ tmp = arg["struct1"]
+ arg["struct1"] = arg["struct-2"]
+ arg["struct-2"] = tmp
+ arg
+ end
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_classdef
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ #File.unlink(pathname('echo.rb'))
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:rpc", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_classdef
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("document.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['force'] = true
+ gen.run
+ require pathname('echo')
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def test_wsdl
+ wsdl = File.join(DIR, 'document.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDOUT if $DEBUG
+
+ struct1 = Echo_struct.new("mystring1", now1 = Time.now)
+ struct1.xmlattr_m_attr = 'myattr1'
+ struct2 = Echo_struct.new("mystring2", now2 = Time.now)
+ struct2.xmlattr_m_attr = 'myattr2'
+ echo = Echoele.new(struct1, struct2)
+ echo.xmlattr_attr_string = 'attr_string'
+ echo.xmlattr_attr_int = 5
+ ret = @client.echo(echo)
+
+ # struct#m_datetime in a response is a DateTime even though
+ # struct#m_datetime in a request is a Time.
+ timeformat = "%Y-%m-%dT%H:%M:%S"
+ assert_equal("mystring2", ret.struct1.m_string)
+ assert_equal(now2.strftime(timeformat),
+ date2time(ret.struct1.m_datetime).strftime(timeformat))
+ assert_equal("mystring1", ret.struct_2.m_string)
+ assert_equal(now1.strftime(timeformat),
+ date2time(ret.struct_2.m_datetime).strftime(timeformat))
+ assert_equal("attr_string", ret.xmlattr_attr_string)
+ assert_equal(5, ret.xmlattr_attr_int)
+ end
+
+ def date2time(date)
+ if date.respond_to?(:to_time)
+ date.to_time
+ else
+ d = date.new_offset(0)
+ d.instance_eval {
+ Time.utc(year, mon, mday, hour, min, sec,
+ (sec_fraction * 86400000000).to_i)
+ }.getlocal
+ end
+ end
+
+ include ::SOAP
+ def test_naive
+ @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/")
+ @client.add_document_method('echo', 'urn:docrpc:echo',
+ XSD::QName.new('urn:docrpc', 'echoele'),
+ XSD::QName.new('urn:docrpc', 'echo_response'))
+ @client.wiredump_dev = STDOUT if $DEBUG
+
+ echo = SOAPElement.new('foo')
+ echo.extraattr['attr_string'] = 'attr_string'
+ echo.extraattr['attr-int'] = 5
+ echo.add(struct1 = SOAPElement.new('struct1'))
+ struct1.add(SOAPElement.new('m_string', 'mystring1'))
+ struct1.add(SOAPElement.new('m_datetime', '2005-03-17T19:47:31+01:00'))
+ struct1.extraattr['m_attr'] = 'myattr1'
+ echo.add(struct2 = SOAPElement.new('struct-2'))
+ struct2.add(SOAPElement.new('m_string', 'mystring2'))
+ struct2.add(SOAPElement.new('m_datetime', '2005-03-17T19:47:32+02:00'))
+ struct2.extraattr['m_attr'] = 'myattr2'
+ ret = @client.echo(echo)
+ timeformat = "%Y-%m-%dT%H:%M:%S"
+ assert_equal('mystring2', ret.struct1.m_string)
+ assert_equal('2005-03-17T19:47:32',
+ ret.struct1.m_datetime.strftime(timeformat))
+ assert_equal("mystring1", ret.struct_2.m_string)
+ assert_equal('2005-03-17T19:47:31',
+ ret.struct_2.m_datetime.strftime(timeformat))
+ assert_equal('attr_string', ret.xmlattr_attr_string)
+ assert_equal(5, ret.xmlattr_attr_int)
+
+ echo = {'struct1' => {'m_string' => 'mystring1', 'm_datetime' => '2005-03-17T19:47:31+01:00'},
+ 'struct-2' => {'m_string' => 'mystring2', 'm_datetime' => '2005-03-17T19:47:32+02:00'}}
+ ret = @client.echo(echo)
+ timeformat = "%Y-%m-%dT%H:%M:%S"
+ assert_equal('mystring2', ret.struct1.m_string)
+ assert_equal('2005-03-17T19:47:32',
+ ret.struct1.m_datetime.strftime(timeformat))
+ assert_equal("mystring1", ret.struct_2.m_string)
+ assert_equal('2005-03-17T19:47:31',
+ ret.struct_2.m_datetime.strftime(timeformat))
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/wsdl/emptycomplextype.wsdl b/ruby_1_8_6/test/wsdl/emptycomplextype.wsdl
new file mode 100644
index 0000000000..4f8dc4849c
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/emptycomplextype.wsdl
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name = "emptycomplextype"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="urn:jp.gr.jin.rrr.example.emptycomplextype"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+ <types>
+ <xsd:schema elementFormDefault="qualified"
+ targetNamespace="urn:jp.gr.jin.rrr.example.emptycomplextype">
+ <xsd:element name="typeIn">
+ <xsd:complexType />
+ </xsd:element>
+
+ <xsd:element name="typeOut">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element minOccurs="0" maxOccurs="1" name="str1" type="xsd:string" />
+ <xsd:element minOccurs="0" maxOccurs="1" name="str2" type="xsd:string" />
+ <xsd:element minOccurs="0" maxOccurs="1" name="seq">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:any />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ </types>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/map/map.wsdl b/ruby_1_8_6/test/wsdl/map/map.wsdl
new file mode 100644
index 0000000000..e418a4cbbd
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/map/map.wsdl
@@ -0,0 +1,92 @@
+<?xml version="1.0"?>
+<definitions
+ name="map"
+ targetNamespace="urn:map"
+ xmlns:tns="urn:map"
+ xmlns:txd="urn:map"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:apachesoap="http://xml.apache.org/xml-soap">
+
+ <types>
+ <schema
+ xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://xml.apache.org/xml-soap">
+ <complexType name="Map">
+ <sequence>
+ <element name="item" minOccurs="0" maxOccurs="unbounded">
+ <complexType>
+ <sequence>
+ <element name="key" type="xsd:anyType" />
+ <element name="value" type="xsd:anyType" />
+ </sequence>
+ </complexType>
+ </element>
+ </sequence>
+ </complexType>
+ </schema>
+ </types>
+
+ <message name="mapRequest"/>
+ <message name="mapResponse">
+ <part name="return" type="apachesoap:Map"/>
+ </message>
+
+ <message name="map2Request">
+ <part name="arg" type="apachesoap:Map"/>
+ </message>
+ <message name="map2Response">
+ <part name="return" type="apachesoap:Map"/>
+ </message>
+
+ <portType name="MapServicePortType">
+ <operation name="map" parameterOrder="">
+ <input message="tns:mapRequest"/>
+ <output message="tns:mapResponse"/>
+ </operation>
+
+ <operation name="map2" parameterOrder="">
+ <input message="tns:map2Request"/>
+ <output message="tns:map2Response"/>
+ </operation>
+ </portType>
+
+ <binding name="MapServicePortBinding" type="tns:MapServicePortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="map">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:map"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:map"/>
+ </output>
+ </operation>
+
+ <operation name="map2">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:map"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:map"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="MapService">
+ <port name="MapServicePort" binding="tns:MapServicePortBinding">
+ <soap:address location="http://raa.ruby-lang.org/soap/1.0.2/"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/map/map.xml b/ruby_1_8_6/test/wsdl/map/map.xml
new file mode 100644
index 0000000000..7106735ffc
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/map/map.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n2:mapResponse xmlns:n1="http://schemas.xmlsoap.org/soap/encoding/" xmlns:n2="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+ <return xmlns:n3="http://xml.apache.org/xml-soap" xsi:type="n3:Map">
+ <item>
+ <key xsi:type="xsd:string">a</key>
+ <value xsi:type="n3:Map">
+ <item>
+ <key xsi:type="xsd:string">a1</key>
+ <value xsi:type="n1:Array" n1:arrayType="xsd:anyType[1]">
+ <item xsi:type="xsd:string">a1</item>
+ </value>
+ </item>
+ <item>
+ <key xsi:type="xsd:string">a2</key>
+ <value xsi:type="n1:Array" n1:arrayType="xsd:anyType[1]">
+ <item xsi:type="xsd:string">a2</item>
+ </value>
+ </item>
+ </value>
+ </item>
+ <item>
+ <key xsi:type="xsd:string">b</key>
+ <value xsi:type="n3:Map">
+ <item>
+ <key xsi:type="xsd:string">b1</key>
+ <value xsi:type="n1:Array" n1:arrayType="xsd:anyType[1]">
+ <item xsi:type="xsd:string">b1</item>
+ </value>
+ </item>
+ <item>
+ <key xsi:type="xsd:string">b2</key>
+ <value xsi:type="n1:Array" n1:arrayType="xsd:anyType[1]">
+ <item xsi:type="xsd:string">b2</item>
+ </value>
+ </item>
+ </value>
+ </item>
+ </return>
+ </n2:mapResponse>
+ </env:Body>
+</env:Envelope>
diff --git a/ruby_1_8_6/test/wsdl/map/test_map.rb b/ruby_1_8_6/test/wsdl/map/test_map.rb
new file mode 100644
index 0000000000..68f7d76e05
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/map/test_map.rb
@@ -0,0 +1,99 @@
+require 'test/unit'
+require 'soap/rpc/httpserver'
+require 'soap/wsdlDriver'
+
+
+module WSDL
+
+
+class TestMap < Test::Unit::TestCase
+ Port = 17171
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ class Server < ::SOAP::RPC::HTTPServer
+ def on_init
+ add_method(self, 'map')
+ add_method(self, 'map2', 'arg')
+ end
+
+ def map
+ {1 => "a", 2 => "b"}
+ end
+
+ def map2(arg)
+ arg
+ end
+ end
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new(
+ :BindAddress => "0.0.0.0",
+ :Port => Port,
+ :AccessLog => [],
+ :SOAPDefaultNamespace => "urn:map"
+ )
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'map.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.generate_explicit_type = true
+ @client.wiredump_dev = STDOUT if $DEBUG
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def test_by_wsdl
+ dir = File.dirname(File.expand_path(__FILE__))
+ wsdlfile = File.join(dir, 'map.wsdl')
+ xml = File.open(File.join(dir, 'map.xml')) { |f| f.read }
+ wsdl = WSDL::Importer.import(wsdlfile)
+ service = wsdl.services[0]
+ port = service.ports[0]
+ wsdl_types = wsdl.collect_complextypes
+ rpc_decode_typemap = wsdl_types + wsdl.soap_rpc_complextypes(port.find_binding)
+ opt = {}
+ opt[:default_encodingstyle] = ::SOAP::EncodingNamespace
+ opt[:decode_typemap] = rpc_decode_typemap
+ header, body = ::SOAP::Processor.unmarshal(xml, opt)
+ map = ::SOAP::Mapping.soap2obj(body.response)
+ assert_equal(["a1"], map["a"]["a1"])
+ assert_equal(["a2"], map["a"]["a2"])
+ assert_equal(["b1"], map["b"]["b1"])
+ assert_equal(["b2"], map["b"]["b2"])
+ end
+
+ def test_wsdldriver
+ assert_equal({1 => "a", 2 => "b"}, @client.map)
+ assert_equal({1 => 2}, @client.map2({1 => 2}))
+ assert_equal({1 => {2 => 3}}, @client.map2({1 => {2 => 3}}))
+ assert_equal({["a", 2] => {2 => 3}}, @client.map2({["a", 2] => {2 => 3}}))
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/wsdl/marshal/person.wsdl b/ruby_1_8_6/test/wsdl/marshal/person.wsdl
new file mode 100644
index 0000000000..6ea8a04825
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/marshal/person.wsdl
@@ -0,0 +1,21 @@
+<?xml version="1.0"?>
+<definitions name="Person"
+ targetNamespace="http://www.jin.gr.jp/~nahi/xmlns/sample/Person"
+ xmlns:tns="http://www.jin.gr.jp/~nahi/xmlns/sample/Person"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://www.jin.gr.jp/~nahi/xmlns/sample/Person">
+ <complexType name="Person">
+ <all>
+ <element name="familyname" type="xsd:string"/>
+ <element name="givenname" type="xsd:string"/>
+ <element name="var1" type="xsd:int"/>
+ <element name="var2" type="xsd:double"/>
+ <element name="var3" type="xsd:string"/>
+ </all>
+ </complexType>
+ </xsd:schema>
+ </types>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/marshal/person_org.rb b/ruby_1_8_6/test/wsdl/marshal/person_org.rb
new file mode 100644
index 0000000000..f8c0e0db76
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/marshal/person_org.rb
@@ -0,0 +1,22 @@
+require 'xsd/qname'
+
+# {http://www.jin.gr.jp/~nahi/xmlns/sample/Person}Person
+class Person
+ @@schema_type = "Person"
+ @@schema_ns = "http://www.jin.gr.jp/~nahi/xmlns/sample/Person"
+ @@schema_element = [["familyname", ["SOAP::SOAPString", XSD::QName.new(nil, "familyname")]], ["givenname", ["SOAP::SOAPString", XSD::QName.new(nil, "givenname")]], ["var1", ["SOAP::SOAPInt", XSD::QName.new(nil, "var1")]], ["var2", ["SOAP::SOAPDouble", XSD::QName.new(nil, "var2")]], ["var3", ["SOAP::SOAPString", XSD::QName.new(nil, "var3")]]]
+
+ attr_accessor :familyname
+ attr_accessor :givenname
+ attr_accessor :var1
+ attr_accessor :var2
+ attr_accessor :var3
+
+ def initialize(familyname = nil, givenname = nil, var1 = nil, var2 = nil, var3 = nil)
+ @familyname = familyname
+ @givenname = givenname
+ @var1 = var1
+ @var2 = var2
+ @var3 = var3
+ end
+end
diff --git a/ruby_1_8_6/test/wsdl/marshal/test_wsdlmarshal.rb b/ruby_1_8_6/test/wsdl/marshal/test_wsdlmarshal.rb
new file mode 100644
index 0000000000..cd2bdb198a
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/marshal/test_wsdlmarshal.rb
@@ -0,0 +1,80 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'soap/mapping/wsdlencodedregistry'
+require 'soap/marshal'
+require 'wsdl/soap/wsdl2ruby'
+
+class WSDLMarshaller
+ include SOAP
+
+ def initialize(wsdlfile)
+ wsdl = WSDL::Parser.new.parse(File.open(wsdlfile) { |f| f.read })
+ types = wsdl.collect_complextypes
+ @opt = {
+ :decode_typemap => types,
+ :generate_explicit_type => false,
+ :pretty => true
+ }
+ @mapping_registry = Mapping::WSDLEncodedRegistry.new(types)
+ end
+
+ def dump(obj, io = nil)
+ type = Mapping.class2element(obj.class)
+ ele = Mapping.obj2soap(obj, @mapping_registry, type)
+ ele.elename = ele.type
+ Processor.marshal(SOAPEnvelope.new(nil, SOAPBody.new(ele)), @opt, io)
+ end
+
+ def load(io)
+ header, body = Processor.unmarshal(io, @opt)
+ Mapping.soap2obj(body.root_node)
+ end
+end
+
+
+require File.join(File.dirname(__FILE__), 'person_org')
+
+class Person
+ def ==(rhs)
+ @familyname == rhs.familyname and @givenname == rhs.givenname and
+ @var1 == rhs.var1 and @var2 == rhs.var2 and @var3 == rhs.var3
+ end
+end
+
+
+class TestWSDLMarshal < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def test_marshal
+ marshaller = WSDLMarshaller.new(pathname('person.wsdl'))
+ obj = Person.new("NAKAMURA", "Hiroshi", 1, 1.0, "1")
+ str = marshaller.dump(obj)
+ obj2 = marshaller.load(str)
+ assert_equal(obj, obj2)
+ assert_equal(str, marshaller.dump(obj2))
+ end
+
+ def test_classdef
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("person.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['force'] = true
+ gen.run
+ compare("person_org.rb", "Person.rb")
+ File.unlink(pathname('Person.rb'))
+ end
+
+ def compare(expected, actual)
+ assert_equal(loadfile(expected), loadfile(actual), actual)
+ end
+
+ def loadfile(file)
+ File.open(pathname(file)) { |f| f.read }
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+end
diff --git a/ruby_1_8_6/test/wsdl/multiplefault.wsdl b/ruby_1_8_6/test/wsdl/multiplefault.wsdl
new file mode 100644
index 0000000000..2d928b60b0
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/multiplefault.wsdl
@@ -0,0 +1,68 @@
+<?xml version="1.0"?>
+<definitions name="MultipleFaultTest"
+ targetNamespace="urn:jp.gr.jin.rrr.example.ele"
+ xmlns:tns="urn:jp.gr.jin.rrr.example.ele"
+ xmlns:typens="urn:jp.gr.jin.rrr.example.datatypes"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+ <types>
+ <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="urn:jp.gr.jin.rrr.example.datatypes">
+ <xsd:complexType name="AuthenticationError">
+ <all>
+ <element name="message" type="xsd:string" />
+ <element name="backtrace" type="xoapenc:Array" />
+ </all>
+ </xsd:complexType>
+ <xsd:complexType name="AuthorizationError">
+ <all>
+ <element name="message" type="xsd:string" />
+ <element name="backtrace" type="xoapenc:Array" />
+ </all>
+ </xsd:complexType>
+ </xsd:schema>
+ </types>
+
+ <message name="inputmsg"/>
+ <message name="outputmsg"/>
+ <message name="faultmsg1" >
+ <part name="exception" type="typens:AuthenticationError" />
+ </message>
+ <message name="faultmsg2" >
+ <part name="exception" type="typens:AuthorizationError" />
+ </message>
+
+ <portType name="MultipleFaultPortType">
+ <operation name="myoperation">
+ <input message="tns:inputmsg"/>
+ <output message="tns:outputmsg"/>
+ <fault message="tns:faultmsg1"/>
+ <fault message="tns:faultmsg2"/>
+ </operation>
+ </portType>
+
+ <binding name="MultipleFaultBinding" type="tns:MultipleFaultPortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="myoperation">
+ <soap:operation soapAction="urn:jp.gr.jin.rrr.example.ele"/>
+ <input>
+ <soap:body use="encoded" namespace="urn:jp.gr.jin.rrr.example.ele"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:jp.gr.jin.rrr.example.ele"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="MultipleFaultService">
+ <port name="MultipleFaultPortType" binding="tns:MultipleFaultBinding">
+ <soap:address location="http://localhost:17171/"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/qualified/lp.rb b/ruby_1_8_6/test/wsdl/qualified/lp.rb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/qualified/lp.rb
diff --git a/ruby_1_8_6/test/wsdl/qualified/lp.wsdl b/ruby_1_8_6/test/wsdl/qualified/lp.wsdl
new file mode 100644
index 0000000000..b107b7b392
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/qualified/lp.wsdl
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions
+ name="lp"
+ targetNamespace="urn:lp"
+ xmlns:tns="urn:lp"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <schema xmlns="http://www.w3.org/2001/XMLSchema">
+ <import namespace="urn:lp" schemaLocation="lp.xsd"/>
+ </schema>
+ </types>
+
+ <message name="login_in">
+ <part name="parameters" element="tns:login" />
+ </message>
+ <message name="login_out">
+ <part name="parameters" element="tns:loginResponse" />
+ </message>
+
+ <portType name="lp_porttype">
+ <operation name="login">
+ <input message="tns:login_in" />
+ <output message="tns:login_out" />
+ </operation>
+ </portType>
+
+ <binding name="lp_binding" type="tns:lp_porttype">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+ <operation name="login">
+ <soap:operation soapAction="urn:lp:login" style="document" />
+ <input>
+ <soap:body use="literal" />
+ </input>
+ <output>
+ <soap:body use="literal" />
+ </output>
+ </operation>
+ </binding>
+
+ <service name="lp_service">
+ <port name="lp_service_port" binding="tns:lp_binding">
+ <soap:address location="http://localhost:17171/" />
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/qualified/lp.xsd b/ruby_1_8_6/test/wsdl/qualified/lp.xsd
new file mode 100644
index 0000000000..12bcbd8cef
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/qualified/lp.xsd
@@ -0,0 +1,26 @@
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:lp="urn:lp" targetNamespace="urn:lp" elementFormDefault="unqualified">
+
+ <xs:complexType name="login">
+ <xs:sequence>
+ <xs:element name="username" type="xs:string"/>
+ <xs:element name="password" type="xs:string"/>
+ <xs:element name="timezone" type="xs:string" minOccurs="0" maxOccurs="1"/>
+ </xs:sequence>
+ </xs:complexType>
+
+ <xs:element name="login" type="lp:login"/>
+
+ <xs:complexType name="loginResponse">
+ <xs:sequence>
+ <xs:element name="loginResult">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="sessionID" type="xs:string"/>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+ </xs:sequence>
+ </xs:complexType>
+
+ <xs:element name="loginResponse" type="lp:loginResponse"/>
+</xs:schema>
diff --git a/ruby_1_8_6/test/wsdl/qualified/np.wsdl b/ruby_1_8_6/test/wsdl/qualified/np.wsdl
new file mode 100644
index 0000000000..e2b7253d0e
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/qualified/np.wsdl
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www50.brinkster.com/vbfacileinpt/np" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" targetNamespace="http://www50.brinkster.com/vbfacileinpt/np" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
+ <wsdl:types>
+ <s:schema elementFormDefault="qualified" targetNamespace="http://www50.brinkster.com/vbfacileinpt/np">
+ <s:element name="GetPrimeNumbers">
+ <s:complexType>
+ <s:sequence>
+ <s:element minOccurs="0" maxOccurs="1" name="Max" type="s:string" />
+ </s:sequence>
+ </s:complexType>
+ </s:element>
+ <s:element name="GetPrimeNumbersResponse">
+ <s:complexType>
+ <s:sequence>
+ <s:element minOccurs="0" maxOccurs="1" name="GetPrimeNumbersResult" type="s:string" />
+ </s:sequence>
+ </s:complexType>
+ </s:element>
+ </s:schema>
+ </wsdl:types>
+ <wsdl:message name="GetPrimeNumbersSoapIn">
+ <wsdl:part name="parameters" element="tns:GetPrimeNumbers" />
+ </wsdl:message>
+ <wsdl:message name="GetPrimeNumbersSoapOut">
+ <wsdl:part name="parameters" element="tns:GetPrimeNumbersResponse" />
+ </wsdl:message>
+ <wsdl:portType name="pnumSoap">
+ <wsdl:operation name="GetPrimeNumbers">
+ <wsdl:input message="tns:GetPrimeNumbersSoapIn" />
+ <wsdl:output message="tns:GetPrimeNumbersSoapOut" />
+ </wsdl:operation>
+ </wsdl:portType>
+ <wsdl:binding name="pnumSoap" type="tns:pnumSoap">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+ <wsdl:operation name="GetPrimeNumbers">
+ <soap:operation soapAction="http://www50.brinkster.com/vbfacileinpt/np/GetPrimeNumbers" style="document" />
+ <wsdl:input>
+ <soap:body use="literal" />
+ </wsdl:input>
+ <wsdl:output>
+ <soap:body use="literal" />
+ </wsdl:output>
+ </wsdl:operation>
+ </wsdl:binding>
+ <wsdl:service name="pnum">
+ <wsdl:port name="pnumSoap" binding="tns:pnumSoap">
+ <soap:address location="http://www50.brinkster.com/vbfacileinpt/np.asmx" />
+ </wsdl:port>
+ </wsdl:service>
+</wsdl:definitions> \ No newline at end of file
diff --git a/ruby_1_8_6/test/wsdl/qualified/test_qualified.rb b/ruby_1_8_6/test/wsdl/qualified/test_qualified.rb
new file mode 100644
index 0000000000..d6c1159a87
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/qualified/test_qualified.rb
@@ -0,0 +1,154 @@
+require 'test/unit'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+if defined?(HTTPAccess2)
+
+module WSDL
+
+
+class TestQualified < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = 'http://www50.brinkster.com/vbfacileinpt/np'
+
+ def on_init
+ add_document_method(
+ self,
+ Namespace + '/GetPrimeNumbers',
+ 'GetPrimeNumbers',
+ XSD::QName.new(Namespace, 'GetPrimeNumbers'),
+ XSD::QName.new(Namespace, 'GetPrimeNumbersResponse')
+ )
+ end
+
+ def GetPrimeNumbers(arg)
+ nil
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_clientdef
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ unless $DEBUG
+ File.unlink(pathname('default.rb'))
+ File.unlink(pathname('defaultDriver.rb'))
+ end
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:lp", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_clientdef
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("np.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['driver'] = nil
+ gen.opt['force'] = true
+ gen.run
+ require pathname('default.rb')
+ ensure
+ Dir.chdir(backupdir)
+ end
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ LOGIN_REQUEST_QUALIFIED_NS =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:GetPrimeNumbers xmlns:n1="http://www50.brinkster.com/vbfacileinpt/np">
+ <n1:Max>10</n1:Max>
+ </n1:GetPrimeNumbers>
+ </env:Body>
+</env:Envelope>]
+
+ LOGIN_REQUEST_QUALIFIED =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <GetPrimeNumbers xmlns="http://www50.brinkster.com/vbfacileinpt/np">
+ <Max>10</Max>
+ </GetPrimeNumbers>
+ </env:Body>
+</env:Envelope>]
+
+ def test_wsdl
+ wsdl = File.join(DIR, 'np.wsdl')
+ @client = nil
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ ensure
+ Dir.chdir(backupdir)
+ end
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = str = ''
+ @client.GetPrimeNumbers(:Max => 10)
+ assert_equal(LOGIN_REQUEST_QUALIFIED_NS, parse_requestxml(str))
+ end
+
+ include ::SOAP
+ def test_naive
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ require pathname('defaultDriver')
+ ensure
+ Dir.chdir(backupdir)
+ end
+ @client = PnumSoap.new("http://localhost:#{Port}/")
+
+ @client.wiredump_dev = str = ''
+ @client.getPrimeNumbers(GetPrimeNumbers.new(10))
+ assert_equal(LOGIN_REQUEST_QUALIFIED, parse_requestxml(str))
+ end
+
+ def parse_requestxml(str)
+ str.split(/\r?\n\r?\n/)[3]
+ end
+end
+
+
+end
+
+end
diff --git a/ruby_1_8_6/test/wsdl/qualified/test_unqualified.rb b/ruby_1_8_6/test/wsdl/qualified/test_unqualified.rb
new file mode 100644
index 0000000000..bcfed73e58
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/qualified/test_unqualified.rb
@@ -0,0 +1,143 @@
+require 'test/unit'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+if defined?(HTTPAccess2)
+
+module WSDL
+
+
+class TestUnqualified < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = 'urn:lp'
+
+ def on_init
+ add_document_method(
+ self,
+ Namespace + ':login',
+ 'login',
+ XSD::QName.new(Namespace, 'login'),
+ XSD::QName.new(Namespace, 'loginResponse')
+ )
+ end
+
+ def login(arg)
+ nil
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_clientdef
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ File.unlink(pathname('lp.rb'))
+ File.unlink(pathname('lpDriver.rb'))
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:lp", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_clientdef
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("lp.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['driver'] = nil
+ gen.opt['force'] = true
+ gen.run
+ require pathname('lp')
+ ensure
+ Dir.chdir(backupdir)
+ end
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ LOGIN_REQUEST_QUALIFIED =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:login xmlns:n1="urn:lp">
+ <username>NaHi</username>
+ <password>passwd</password>
+ <timezone>JST</timezone>
+ </n1:login>
+ </env:Body>
+</env:Envelope>]
+
+ def test_wsdl
+ wsdl = File.join(DIR, 'lp.wsdl')
+ @client = nil
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ ensure
+ Dir.chdir(backupdir)
+ end
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = str = ''
+ @client.login(:timezone => 'JST', :password => 'passwd',
+ :username => 'NaHi')
+ assert_equal(LOGIN_REQUEST_QUALIFIED, parse_requestxml(str))
+ end
+
+ include ::SOAP
+ def test_naive
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ require pathname('lpDriver')
+ ensure
+ Dir.chdir(backupdir)
+ end
+ @client = Lp_porttype.new("http://localhost:#{Port}/")
+
+ @client.wiredump_dev = str = ''
+ @client.login(Login.new('NaHi', 'passwd', 'JST'))
+ assert_equal(LOGIN_REQUEST_QUALIFIED, parse_requestxml(str))
+ end
+
+ def parse_requestxml(str)
+ str.split(/\r?\n\r?\n/)[3]
+ end
+end
+
+
+end
+
+end
diff --git a/ruby_1_8_6/test/wsdl/raa/RAA.rb b/ruby_1_8_6/test/wsdl/raa/RAA.rb
new file mode 100644
index 0000000000..aff0525480
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/RAA.rb
@@ -0,0 +1,243 @@
+# http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/
+class Category
+ @@schema_type = "Category"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+
+ def major
+ @major
+ end
+
+ def major=(value)
+ @major = value
+ end
+
+ def minor
+ @minor
+ end
+
+ def minor=(value)
+ @minor = value
+ end
+
+ def initialize(major = nil,
+ minor = nil)
+ @major = major
+ @minor = minor
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/
+class Product
+ @@schema_type = "Product"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+
+ def id
+ @id
+ end
+
+ def id=(value)
+ @id = value
+ end
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def short_description
+ @short_description
+ end
+
+ def short_description=(value)
+ @short_description = value
+ end
+
+ def version
+ @version
+ end
+
+ def version=(value)
+ @version = value
+ end
+
+ def status
+ @status
+ end
+
+ def status=(value)
+ @status = value
+ end
+
+ def homepage
+ @homepage
+ end
+
+ def homepage=(value)
+ @homepage = value
+ end
+
+ def download
+ @download
+ end
+
+ def download=(value)
+ @download = value
+ end
+
+ def license
+ @license
+ end
+
+ def license=(value)
+ @license = value
+ end
+
+ def description
+ @description
+ end
+
+ def description=(value)
+ @description = value
+ end
+
+ def initialize(id = nil,
+ name = nil,
+ short_description = nil,
+ version = nil,
+ status = nil,
+ homepage = nil,
+ download = nil,
+ license = nil,
+ description = nil)
+ @id = id
+ @name = name
+ @short_description = short_description
+ @version = version
+ @status = status
+ @homepage = homepage
+ @download = download
+ @license = license
+ @description = description
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/
+class Owner
+ @@schema_type = "Owner"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+
+ def id
+ @id
+ end
+
+ def id=(value)
+ @id = value
+ end
+
+ def email
+ @email
+ end
+
+ def email=(value)
+ @email = value
+ end
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def initialize(id = nil,
+ email = nil,
+ name = nil)
+ @id = id
+ @email = email
+ @name = name
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/
+class Info
+ @@schema_type = "Info"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+
+ def category
+ @category
+ end
+
+ def category=(value)
+ @category = value
+ end
+
+ def product
+ @product
+ end
+
+ def product=(value)
+ @product = value
+ end
+
+ def owner
+ @owner
+ end
+
+ def owner=(value)
+ @owner = value
+ end
+
+ def created
+ @created
+ end
+
+ def created=(value)
+ @created = value
+ end
+
+ def updated
+ @updated
+ end
+
+ def updated=(value)
+ @updated = value
+ end
+
+ def initialize(category = nil,
+ product = nil,
+ owner = nil,
+ created = nil,
+ updated = nil)
+ @category = category
+ @product = product
+ @owner = owner
+ @created = created
+ @updated = updated
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/
+class InfoArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "InfoArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/
+class StringArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "StringArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+end
+
+# http://xml.apache.org/xml-soap
+class Map < Array
+ # Contents type should be dumped here...
+ @@schema_type = "Map"
+ @@schema_ns = "http://xml.apache.org/xml-soap"
+end
+
diff --git a/ruby_1_8_6/test/wsdl/raa/RAAServant.rb b/ruby_1_8_6/test/wsdl/raa/RAAServant.rb
new file mode 100644
index 0000000000..68380f8e48
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/RAAServant.rb
@@ -0,0 +1,99 @@
+class RAABaseServicePortType
+ # SYNOPSIS
+ # getAllListings
+ #
+ # ARGS
+ # N/A
+ #
+ # RETURNS
+ # return StringArray - {http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/}StringArray
+ #
+ # RAISES
+ # (undefined)
+ #
+ def getAllListings
+ #raise NotImplementedError.new
+ ["ruby", "soap4r"]
+ end
+
+ # SYNOPSIS
+ # getProductTree
+ #
+ # ARGS
+ # N/A
+ #
+ # RETURNS
+ # return Map - {http://xml.apache.org/xml-soap}Map
+ #
+ # RAISES
+ # (undefined)
+ #
+ def getProductTree
+ raise NotImplementedError.new
+ end
+
+ # SYNOPSIS
+ # getInfoFromCategory(category)
+ #
+ # ARGS
+ # category Category - {http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/}Category
+ #
+ # RETURNS
+ # return InfoArray - {http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/}InfoArray
+ #
+ # RAISES
+ # (undefined)
+ #
+ def getInfoFromCategory(category)
+ raise NotImplementedError.new
+ end
+
+ # SYNOPSIS
+ # getModifiedInfoSince(timeInstant)
+ #
+ # ARGS
+ # timeInstant - {http://www.w3.org/2001/XMLSchema}dateTime
+ #
+ # RETURNS
+ # return InfoArray - {http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/}InfoArray
+ #
+ # RAISES
+ # (undefined)
+ #
+ def getModifiedInfoSince(timeInstant)
+ raise NotImplementedError.new
+ end
+
+ # SYNOPSIS
+ # getInfoFromName(productName)
+ #
+ # ARGS
+ # productName - {http://www.w3.org/2001/XMLSchema}string
+ #
+ # RETURNS
+ # return Info - {http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/}Info
+ #
+ # RAISES
+ # (undefined)
+ #
+ def getInfoFromName(productName)
+ raise NotImplementedError.new
+ end
+
+ # SYNOPSIS
+ # getInfoFromOwnerId(ownerId)
+ #
+ # ARGS
+ # ownerId - {http://www.w3.org/2001/XMLSchema}int
+ #
+ # RETURNS
+ # return InfoArray - {http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/}InfoArray
+ #
+ # RAISES
+ # (undefined)
+ #
+ def getInfoFromOwnerId(ownerId)
+ raise NotImplementedError.new
+ end
+end
+
diff --git a/ruby_1_8_6/test/wsdl/raa/RAAService.rb b/ruby_1_8_6/test/wsdl/raa/RAAService.rb
new file mode 100644
index 0000000000..9d0813304c
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/RAAService.rb
@@ -0,0 +1,100 @@
+#!/usr/bin/env ruby
+require 'RAAServant.rb'
+
+require 'soap/rpc/standaloneServer'
+
+class RAABaseServicePortType
+ MappingRegistry = SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ StringArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") }
+ )
+ MappingRegistry.set(
+ Map,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "anyType") }
+ )
+ MappingRegistry.set(
+ Category,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Category") }
+ )
+ MappingRegistry.set(
+ InfoArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info") }
+ )
+ MappingRegistry.set(
+ Info,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info") }
+ )
+ MappingRegistry.set(
+ Product,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Product") }
+ )
+ MappingRegistry.set(
+ Owner,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Owner") }
+ )
+
+
+ Methods = [
+ ["getAllListings", "getAllListings", [
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]], "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getProductTree", "getProductTree", [
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "anyType"]]], "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getInfoFromCategory", "getInfoFromCategory", [
+ ["in", "category",
+ [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Category"]],
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]], "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getModifiedInfoSince", "getModifiedInfoSince", [
+ ["in", "timeInstant",
+ [SOAP::SOAPDateTime]],
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]], "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getInfoFromName", "getInfoFromName", [
+ ["in", "productName",
+ [SOAP::SOAPString]],
+ ["retval", "return",
+ [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]], "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getInfoFromOwnerId", "getInfoFromOwnerId", [
+ ["in", "ownerId",
+ [SOAP::SOAPInt]],
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]], "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"]
+ ]
+end
+
+class App < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+
+ servant = RAABaseServicePortType.new
+ RAABaseServicePortType::Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = XSD::QName.new(namespace, name_as)
+ @router.add_method(servant, qname, soapaction, name, params)
+ end
+
+ self.mapping_registry = RAABaseServicePortType::MappingRegistry
+ end
+end
+
+# Change listen port.
+if $0 == __FILE__
+ App.new('app', nil, '0.0.0.0', 10080).start
+end
diff --git a/ruby_1_8_6/test/wsdl/raa/README.txt b/ruby_1_8_6/test/wsdl/raa/README.txt
new file mode 100644
index 0000000000..efbaf9d87c
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/README.txt
@@ -0,0 +1,8 @@
+RAAServant.rb: based on the file which is generated with the following command;
+ bin/wsdl2ruby.rb --wsdl raa.wsdl --servant_skelton --force
+
+RAAService.rb: generated with the following command;
+ bin/wsdl2ruby.rb --wsdl raa.wsdl --standalone_server_stub --force
+
+RAA.rb: generated with the following command;
+ bin/wsdl2ruby.rb --wsdl raa.wsdl --classdef --force
diff --git a/ruby_1_8_6/test/wsdl/raa/raa.wsdl b/ruby_1_8_6/test/wsdl/raa/raa.wsdl
new file mode 100644
index 0000000000..78376893dd
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/raa.wsdl
@@ -0,0 +1,264 @@
+<?xml version="1.0"?>
+<definitions
+ name="RAA"
+ targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns:tns="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns:txd="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:apachesoap="http://xml.apache.org/xml-soap">
+
+ <types>
+ <schema
+ xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/">
+
+ <complexType name="Category">
+ <all>
+ <element name="major" type="string"/>
+ <element name="minor" type="string"/>
+ </all>
+ </complexType>
+
+ <complexType name="Product">
+ <all>
+ <element name="id" type="int"/>
+ <element name="name" type="string"/>
+ <element name="short_description" type="string"/>
+ <element name="version" type="string"/>
+ <element name="status" type="string"/>
+ <element name="homepage" type="anyURI"/>
+ <element name="download" type="anyURI"/>
+ <element name="license" type="string"/>
+ <element name="description" type="string"/>
+ </all>
+ </complexType>
+
+ <complexType name="Owner">
+ <all>
+ <element name="id" type="int"/>
+ <element name="email" type="anyURI"/>
+ <element name="name" type="string"/>
+ </all>
+ </complexType>
+
+ <complexType name="Info">
+ <all>
+ <element name="category" type="txd:Category"/>
+ <element name="product" type="txd:Product"/>
+ <element name="owner" type="txd:Owner"/>
+ <element name="created" type="xsd:dateTime"/>
+ <element name="updated" type="xsd:dateTime"/>
+ </all>
+ </complexType>
+
+ <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+ <complexType name="InfoArray">
+ <complexContent>
+ <restriction base="soapenc:Array">
+ <attribute ref="soapenc:arrayType" wsdl:arrayType="txd:Info[]"/>
+ </restriction>
+ </complexContent>
+ </complexType>
+
+ <complexType name="StringArray">
+ <complexContent>
+ <restriction base="soapenc:Array">
+ <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:string[]"/>
+ </restriction>
+ </complexContent>
+ </complexType>
+ </schema>
+
+ <!-- type definition for ApacheSOAP's Map -->
+ <schema
+ xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://xml.apache.org/xml-soap">
+ <complexType name="Map">
+ <sequence>
+ <element name="item" minOccurs="0" maxOccurs="unbounded">
+ <complexType>
+ <sequence>
+ <element name="key" type="anyType" />
+ <element name="value" type="anyType" />
+ </sequence>
+ </complexType>
+ </element>
+ </sequence>
+ </complexType>
+ </schema>
+ </types>
+
+ <message name="getAllListingsRequest"/>
+ <message name="getAllListingsResponse">
+ <part name="return" type="txd:StringArray"/>
+ </message>
+
+ <message name="getProductTreeRequest"/>
+ <message name="getProductTreeResponse">
+ <part name="return" type="apachesoap:Map"/>
+ </message>
+
+ <message name="getInfoFromCategoryRequest">
+ <part name="category" type="txd:Category"/>
+ </message>
+ <message name="getInfoFromCategoryResponse">
+ <part name="return" type="txd:InfoArray"/>
+ </message>
+
+ <message name="getModifiedInfoSinceRequest">
+ <part name="timeInstant" type="xsd:dateTime"/>
+ </message>
+ <message name="getModifiedInfoSinceResponse">
+ <part name="return" type="txd:InfoArray"/>
+ </message>
+
+ <message name="getInfoFromNameRequest">
+ <part name="productName" type="xsd:string"/>
+ </message>
+ <message name="getInfoFromNameResponse">
+ <part name="return" type="txd:Info"/>
+ </message>
+
+ <message name="getInfoFromOwnerIdRequest">
+ <part name="ownerId" type="xsd:int"/>
+ </message>
+ <message name="getInfoFromOwnerIdResponse">
+ <part name="return" type="txd:InfoArray"/>
+ </message>
+
+ <portType name="RAABaseServicePortType">
+ <operation name="getAllListings"
+ parameterOrder="">
+ <input message="tns:getAllListingsRequest"/>
+ <output message="tns:getAllListingsResponse"/>
+ </operation>
+
+ <operation name="getProductTree"
+ parameterOrder="">
+ <input message="tns:getProductTreeRequest"/>
+ <output message="tns:getProductTreeResponse"/>
+ </operation>
+
+ <operation name="getInfoFromCategory"
+ parameterOrder="category">
+ <input message="tns:getInfoFromCategoryRequest"/>
+ <output message="tns:getInfoFromCategoryResponse"/>
+ </operation>
+
+ <operation name="getModifiedInfoSince"
+ parameterOrder="timeInstant">
+ <input message="tns:getModifiedInfoSinceRequest"/>
+ <output message="tns:getModifiedInfoSinceResponse"/>
+ </operation>
+
+ <operation name="getInfoFromName"
+ parameterOrder="productName">
+ <input message="tns:getInfoFromNameRequest"/>
+ <output message="tns:getInfoFromNameResponse"/>
+ </operation>
+
+ <operation name="getInfoFromOwnerId"
+ parameterOrder="ownerId">
+ <input message="tns:getInfoFromOwnerIdRequest"/>
+ <output message="tns:getInfoFromOwnerIdResponse"/>
+ </operation>
+ </portType>
+
+ <binding name="RAABaseServicePortBinding" type="tns:RAABaseServicePortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+
+ <operation name="getAllListings">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getProductTree">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getInfoFromCategory">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getModifiedInfoSince">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getInfoFromName">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getInfoFromOwnerId">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="RAAService">
+ <port name="RAABaseServicePort" binding="tns:RAABaseServicePortBinding">
+ <soap:address location="http://raa.ruby-lang.org/soap/1.0.2/"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/raa/server.rb b/ruby_1_8_6/test/wsdl/raa/server.rb
new file mode 100644
index 0000000000..87bbc6f569
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/server.rb
@@ -0,0 +1,103 @@
+#!/usr/bin/env ruby
+require 'soap/rpc/standaloneServer'
+require 'RAA.rb'
+
+class RAABaseServicePortType
+ MappingRegistry = SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ StringArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") }
+ )
+ MappingRegistry.set(
+ Map,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://xml.apache.org/xml-soap", "Map") }
+ )
+ MappingRegistry.set(
+ Category,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Category") }
+ )
+ MappingRegistry.set(
+ InfoArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info") }
+ )
+ MappingRegistry.set(
+ Info,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info") }
+ )
+ MappingRegistry.set(
+ Product,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Product") }
+ )
+ MappingRegistry.set(
+ Owner,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Owner") }
+ )
+
+ Methods = [
+ ["getAllListings", "getAllListings", [
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getProductTree", "getProductTree", [
+ ["retval", "return",
+ [::SOAP::SOAPStruct, "http://xml.apache.org/xml-soap", "Map"]]],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getInfoFromCategory", "getInfoFromCategory", [
+ ["in", "category",
+ [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Category"]],
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getModifiedInfoSince", "getModifiedInfoSince", [
+ ["in", "timeInstant",
+ [SOAP::SOAPDateTime]],
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getInfoFromName", "getInfoFromName", [
+ ["in", "productName",
+ [SOAP::SOAPString]],
+ ["retval", "return",
+ [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"],
+ ["getInfoFromOwnerId", "getInfoFromOwnerId", [
+ ["in", "ownerId",
+ [SOAP::SOAPInt]],
+ ["retval", "return",
+ [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/", "Info"]]],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"]
+ ]
+
+ def getAllListings
+ ["ruby", "soap4r"]
+ end
+end
+
+class RAABaseServiceServer < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+
+ servant = RAABaseServicePortType.new
+ RAABaseServicePortType::Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = XSD::QName.new(namespace, name_as)
+ @router.add_method(servant, qname, soapaction, name, params)
+ end
+
+ self.mapping_registry = RAABaseServicePortType::MappingRegistry
+ end
+end
diff --git a/ruby_1_8_6/test/wsdl/raa/test_raa.rb b/ruby_1_8_6/test/wsdl/raa/test_raa.rb
new file mode 100644
index 0000000000..0b00042ffb
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/raa/test_raa.rb
@@ -0,0 +1,71 @@
+require 'test/unit'
+require 'soap/wsdlDriver'
+require 'RAA.rb'
+require 'RAAServant.rb'
+require 'RAAService.rb'
+
+
+module WSDL
+module RAA
+
+
+class TestRAA < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = App.new('RAA server', nil, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'raa.wsdl')
+ @raa = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @raa.endpoint_url = "http://localhost:#{Port}/"
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @raa.reset_stream
+ end
+
+ def test_raa
+ assert_equal(["ruby", "soap4r"], @raa.getAllListings)
+ end
+
+ def foo
+ p @raa.getProductTree()
+ p @raa.getInfoFromCategory(Category.new("Library", "XML"))
+ t = Time.at(Time.now.to_i - 24 * 3600)
+ p @raa.getModifiedInfoSince(t)
+ p @raa.getModifiedInfoSince(DateTime.new(t.year, t.mon, t.mday, t.hour, t.min, t.sec))
+ o = @raa.getInfoFromName("SOAP4R")
+ p o.type
+ p o.owner.name
+ p o
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/wsdl/ref/expectedProduct.rb b/ruby_1_8_6/test/wsdl/ref/expectedProduct.rb
new file mode 100644
index 0000000000..91c6e4c566
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/ref/expectedProduct.rb
@@ -0,0 +1,90 @@
+require 'xsd/qname'
+
+# {urn:product}Rating
+module Rating
+ C_0 = "0"
+ C_1 = "+1"
+ C_1_2 = "-1"
+end
+
+# {urn:product}Product-Bag
+class ProductBag
+ @@schema_type = "Product-Bag"
+ @@schema_ns = "urn:product"
+ @@schema_attribute = {XSD::QName.new("urn:product", "version") => "SOAP::SOAPString", XSD::QName.new("urn:product", "yesno") => "SOAP::SOAPString"}
+ @@schema_element = [["bag", ["Product[]", XSD::QName.new(nil, "bag")]], ["rating", ["SOAP::SOAPString[]", XSD::QName.new("urn:product", "Rating")]], ["product_Bag", [nil, XSD::QName.new("urn:product", "Product-Bag")]], ["comment_1", [nil, XSD::QName.new(nil, "comment_1")]], ["comment_2", ["Comment[]", XSD::QName.new(nil, "comment-2")]]]
+
+ attr_accessor :bag
+ attr_accessor :product_Bag
+ attr_accessor :comment_1
+ attr_accessor :comment_2
+
+ def Rating
+ @rating
+ end
+
+ def Rating=(value)
+ @rating = value
+ end
+
+ def xmlattr_version
+ (@__xmlattr ||= {})[XSD::QName.new("urn:product", "version")]
+ end
+
+ def xmlattr_version=(value)
+ (@__xmlattr ||= {})[XSD::QName.new("urn:product", "version")] = value
+ end
+
+ def xmlattr_yesno
+ (@__xmlattr ||= {})[XSD::QName.new("urn:product", "yesno")]
+ end
+
+ def xmlattr_yesno=(value)
+ (@__xmlattr ||= {})[XSD::QName.new("urn:product", "yesno")] = value
+ end
+
+ def initialize(bag = [], rating = [], product_Bag = nil, comment_1 = [], comment_2 = [])
+ @bag = bag
+ @rating = rating
+ @product_Bag = product_Bag
+ @comment_1 = comment_1
+ @comment_2 = comment_2
+ @__xmlattr = {}
+ end
+end
+
+# {urn:product}Creator
+class Creator
+ @@schema_type = "Creator"
+ @@schema_ns = "urn:product"
+ @@schema_element = []
+
+ def initialize
+ end
+end
+
+# {urn:product}Product
+class Product
+ @@schema_type = "Product"
+ @@schema_ns = "urn:product"
+ @@schema_element = [["name", ["SOAP::SOAPString", XSD::QName.new(nil, "name")]], ["rating", ["SOAP::SOAPString", XSD::QName.new("urn:product", "Rating")]]]
+
+ attr_accessor :name
+
+ def Rating
+ @rating
+ end
+
+ def Rating=(value)
+ @rating = value
+ end
+
+ def initialize(name = nil, rating = nil)
+ @name = name
+ @rating = rating
+ end
+end
+
+# {urn:product}Comment
+class Comment < String
+end
diff --git a/ruby_1_8_6/test/wsdl/ref/product.wsdl b/ruby_1_8_6/test/wsdl/ref/product.wsdl
new file mode 100644
index 0000000000..993fe217aa
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/ref/product.wsdl
@@ -0,0 +1,86 @@
+<?xml version="1.0"?>
+<definitions name="product"
+ targetNamespace="urn:product"
+ xmlns:tns="urn:product"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="urn:product">
+ <simpleType name="non-empty-string">
+ <restriction base="xsd:string">
+ <minLength value="1"/>
+ </restriction>
+ </simpleType>
+
+ <complexType name="Product">
+ <all>
+ <element name="name" type="xsd:string"/>
+ <element ref="tns:Rating"/>
+ </all>
+ </complexType>
+
+ <complexType name="Comment">
+ <simpleContent>
+ <extension base="xsd:string">
+ <attribute name="msgid" type="xsd:string" use="required"/>
+ </extension>
+ </simpleContent>
+ </complexType>
+
+ <attribute name="version" type="tns:non-empty-string"/>
+
+ <attribute default="Y" name="yesno">
+ <simpleType>
+ <restriction base="xsd:string">
+ <enumeration value="Y"/>
+ <enumeration value="N"/>
+ </restriction>
+ </simpleType>
+ </attribute>
+
+ <element name="Rating">
+ <simpleType>
+ <restriction base="xsd:string">
+ <enumeration value="+1"/>
+ <enumeration value="0"/>
+ <enumeration value="-1"/>
+ </restriction>
+ </simpleType>
+ </element>
+
+ <element name="Product-Bag">
+ <complexType>
+ <sequence>
+ <element name="bag" type="tns:Product" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="tns:Rating" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="tns:Product-Bag"/>
+ <element name="comment_1" minOccurs="0" maxOccurs="unbounded">
+ <complexType>
+ <simpleContent>
+ <extension base="xsd:string">
+ <attribute name="msgid" type="xsd:string" use="required"/>
+ </extension>
+ </simpleContent>
+ </complexType>
+ </element>
+ <element name="comment-2" type="tns:Comment" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ <attribute ref="tns:version"/>
+ <attribute ref="tns:yesno"/>
+ </complexType>
+ </element>
+
+ <element name="Creator" minOccurs="0" maxOccurs="unbounded">
+ <complexType>
+ <simpleContent>
+ <extension base="xsd:string">
+ <attribute name="Role" type="xs:string" use="required"/>
+ </extension>
+ </simpleContent>
+ </complexType>
+ </element>
+ </xsd:schema>
+ </types>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/ref/test_ref.rb b/ruby_1_8_6/test/wsdl/ref/test_ref.rb
new file mode 100644
index 0000000000..9e29fa31e0
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/ref/test_ref.rb
@@ -0,0 +1,54 @@
+require 'test/unit'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+require 'wsdl/soap/wsdl2ruby'
+
+
+module WSDL
+module Ref
+
+
+class TestRef < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+ Port = 17171
+
+ def test_classdef
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("product.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['force'] = true
+ suppress_warning do
+ gen.run
+ end
+ compare("expectedProduct.rb", "product.rb")
+ File.unlink(pathname('product.rb'))
+ end
+
+ def compare(expected, actual)
+ assert_equal(loadfile(expected), loadfile(actual), actual)
+ end
+
+ def loadfile(file)
+ File.open(pathname(file)) { |f| f.read }
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def suppress_warning
+ back = $VERBOSE
+ $VERBOSE = nil
+ begin
+ yield
+ ensure
+ $VERBOSE = back
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/wsdl/rpc/echoDriver.rb b/ruby_1_8_6/test/wsdl/rpc/echoDriver.rb
new file mode 100644
index 0000000000..51e82076e7
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/echoDriver.rb
@@ -0,0 +1,55 @@
+require 'echo.rb'
+
+require 'soap/rpc/driver'
+
+class Echo_port_type < ::SOAP::RPC::Driver
+ DefaultEndpointUrl = "http://localhost:10080"
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ Person,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:rpc-type", "person") }
+ )
+
+ Methods = [
+ ["echo", "echo",
+ [
+ ["in", "arg1", [::SOAP::SOAPStruct, "urn:rpc-type", "person"]],
+ ["in", "arg2", [::SOAP::SOAPStruct, "urn:rpc-type", "person"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "urn:rpc-type", "person"]]
+ ],
+ "", "urn:rpc", :rpc
+ ]
+ ]
+
+ def initialize(endpoint_url = nil)
+ endpoint_url ||= DefaultEndpointUrl
+ super(endpoint_url, nil)
+ self.mapping_registry = MappingRegistry
+ init_methods
+ end
+
+private
+
+ def init_methods
+ Methods.each do |name_as, name, params, soapaction, namespace, style|
+ qname = XSD::QName.new(namespace, name_as)
+ if style == :document
+ @proxy.add_document_method(soapaction, name, params)
+ add_document_method_interface(name, params)
+ else
+ @proxy.add_rpc_method(qname, soapaction, name, params)
+ add_rpc_method_interface(name, params)
+ end
+ if name_as != name and name_as.capitalize == name.capitalize
+ sclass = class << self; self; end
+ sclass.__send__(:define_method, name_as, proc { |*arg|
+ __send__(name, *arg)
+ })
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/wsdl/rpc/echo_serviceClient.rb b/ruby_1_8_6/test/wsdl/rpc/echo_serviceClient.rb
new file mode 100644
index 0000000000..40264834e9
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/echo_serviceClient.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+require 'echoDriver.rb'
+
+endpoint_url = ARGV.shift
+obj = Echo_port_type.new(endpoint_url)
+
+# Uncomment the below line to see SOAP wiredumps.
+# obj.wiredump_dev = STDERR
+
+# SYNOPSIS
+# echo(arg1, arg2)
+#
+# ARGS
+# arg1 Person - {urn:rpc-type}person
+# arg2 Person - {urn:rpc-type}person
+#
+# RETURNS
+# v_return Person - {urn:rpc-type}person
+#
+arg1 = arg2 = nil
+puts obj.echo(arg1, arg2)
+
+
diff --git a/ruby_1_8_6/test/wsdl/rpc/rpc.wsdl b/ruby_1_8_6/test/wsdl/rpc/rpc.wsdl
new file mode 100644
index 0000000000..b0ee5c5e56
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/rpc.wsdl
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name="echo"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="urn:rpc"
+ xmlns:txd="urn:rpc-type"
+ targetNamespace="urn:rpc"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema targetNamespace="urn:rpc-type">
+ <xsd:complexType name="person">
+ <xsd:all>
+ <xsd:element name="family-name" type="xsd:string" />
+ <xsd:element name="given_name" type="xsd:string" />
+ <xsd:element name="age" type="xsd:int" />
+ <xsd:element name="link" type="txd:person" />
+ </xsd:all>
+ </xsd:complexType>
+ </xsd:schema>
+ </types>
+
+ <message name="echo_in">
+ <part name="arg1" type="txd:person"/>
+ <part name="arg2" type="txd:person"/>
+ </message>
+
+ <message name="echo_out">
+ <part name="return" type="txd:person"/>
+ </message>
+
+ <portType name="echo_port_type">
+ <operation name="echo">
+ <input message="tns:echo_in"/>
+ <output message="tns:echo_out"/>
+ </operation>
+
+ <operation name="echo_err">
+ <input message="tns:echo_in"/>
+ <output message="tns:echo_out"/>
+ </operation>
+ </portType>
+
+ <binding name="echo_binding" type="tns:echo_port_type">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
+ <operation name="echo">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded" namespace="urn:rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+
+ <operation name="echo_err">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded" namespace="urn:rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="echo_service">
+ <port name="echo_port" binding="tns:echo_binding">
+ <soap:address location="http://localhost:10080"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/rpc/test-rpc-lit.wsdl b/ruby_1_8_6/test/wsdl/rpc/test-rpc-lit.wsdl
new file mode 100644
index 0000000000..72de747e36
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/test-rpc-lit.wsdl
@@ -0,0 +1,364 @@
+<?xml version="1.0"?>
+
+<definitions name="RPC-Literal-TestDefinitions"
+ targetNamespace="http://whitemesa.net/wsdl/rpc-lit-test"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:soap11="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="http://whitemesa.net/wsdl/rpc-lit-test"
+ xmlns:types="http://soapbuilders.org/rpc-lit-test/types"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://soapbuilders.org/rpc-lit-test/types">
+
+ <element name="stringItem" type="xsd:string" />
+ <complexType name="ArrayOfstring">
+ <sequence>
+ <element ref="types:stringItem" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <complexType name="ArrayOfstringInline">
+ <sequence>
+ <element name="stringItem" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <complexType name="ArrayOfint">
+ <sequence>
+ <element name="integer" type="xsd:int" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <element name="structItem" type="types:SOAPStruct" />
+ <complexType name="SOAPStruct">
+ <all>
+ <element name="varString" type="xsd:string"/>
+ <element name="varInt" type="xsd:int"/>
+ <element name="varFloat" type="xsd:float"/>
+ </all>
+ </complexType>
+
+ <complexType name="ArrayOfSOAPStruct">
+ <sequence>
+ <element ref="types:structItem" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <complexType name="SOAPStructStruct">
+ <all>
+ <element name="varString" type="xsd:string"/>
+ <element name="varInt" type="xsd:int"/>
+ <element name="varFloat" type="xsd:float"/>
+ <element ref="types:structItem" />
+ </all>
+ </complexType>
+
+ <complexType name="SOAPArrayStruct">
+ <all>
+ <element name="varString" type="xsd:string"/>
+ <element name="varInt" type="xsd:int"/>
+ <element name="varFloat" type="xsd:float"/>
+ <element name="varArray" type="types:ArrayOfstring"/>
+ </all>
+ </complexType>
+
+ </schema>
+
+ </types>
+
+ <!-- echoStruct rpc operation -->
+ <message name="echoStructRequest">
+ <part name="inputStruct" type="types:SOAPStruct"/>
+ </message>
+ <message name="echoStructResponse">
+ <part name="return" type="types:SOAPStruct"/>
+ </message>
+
+ <!-- echoStructArray rpc operation -->
+ <message name="echoStructArrayRequest">
+ <part name="inputStructArray" type="types:ArrayOfSOAPStruct"/>
+ </message>
+ <message name="echoStructArrayResponse">
+ <part name="return" type="types:ArrayOfSOAPStruct"/>
+ </message>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <message name="echoStructAsSimpleTypesRequest">
+ <part name="inputStruct" type="types:SOAPStruct"/>
+ </message>
+ <message name="echoStructAsSimpleTypesResponse">
+ <part name="outputString" type="xsd:string"/>
+ <part name="outputInteger" type="xsd:int"/>
+ <part name="outputFloat" type="xsd:float"/>
+ </message>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <message name="echoSimpleTypesAsStructRequest">
+ <part name="inputString" type="xsd:string"/>
+ <part name="inputInteger" type="xsd:int"/>
+ <part name="inputFloat" type="xsd:float"/>
+ </message>
+ <message name="echoSimpleTypesAsStructResponse">
+ <part name="return" type="types:SOAPStruct"/>
+ </message>
+
+ <!-- echoNestedStruct rpc operation -->
+ <message name="echoNestedStructRequest">
+ <part name="inputStruct" type="types:SOAPStructStruct"/>
+ </message>
+ <message name="echoNestedStructResponse">
+ <part name="return" type="types:SOAPStructStruct"/>
+ </message>
+
+ <!-- echoNestedArray rpc operation -->
+ <message name="echoNestedArrayRequest">
+ <part name="inputStruct" type="types:SOAPArrayStruct"/>
+ </message>
+ <message name="echoNestedArrayResponse">
+ <part name="return" type="types:SOAPArrayStruct"/>
+ </message>
+
+ <!-- echoStringArray rpc operation -->
+ <message name="echoStringArrayRequest">
+ <part name="inputStringArray" type="types:ArrayOfstring"/>
+ </message>
+ <message name="echoStringArrayResponse">
+ <part name="return" type="types:ArrayOfstring"/>
+ </message>
+
+ <message name="echoStringArrayInlineRequest">
+ <part name="inputStringArray" type="types:ArrayOfstringInline"/>
+ </message>
+ <message name="echoStringArrayInlineResponse">
+ <part name="return" type="types:ArrayOfstringInline"/>
+ </message>
+
+ <!-- echoIntegerArray rpc operation -->
+ <message name="echoIntegerArrayRequest">
+ <part name="inputIntegerArray" type="types:ArrayOfint"/>
+ </message>
+ <message name="echoIntegerArrayResponse">
+ <part name="return" type="types:ArrayOfint"/>
+ </message>
+
+ <!-- echoBoolean rpc operation -->
+ <message name="echoBooleanRequest">
+ <part name="inputBoolean" type="xsd:boolean"/>
+ </message>
+ <message name="echoBooleanResponse">
+ <part name="return" type="xsd:boolean"/>
+ </message>
+
+ <!-- echoString rpc operation -->
+ <message name="echoStringRequest">
+ <part name="inputString" type="xsd:string"/>
+ </message>
+ <message name="echoStringResponse">
+ <part name="return" type="xsd:string"/>
+ </message>
+
+
+ <portType name="SoapTestPortTypeRpc">
+
+ <!-- echoStruct rpc operation -->
+ <operation name="echoStruct" parameterOrder="inputStruct">
+ <input message="tns:echoStructRequest"/>
+ <output message="tns:echoStructResponse"/>
+ </operation>
+
+ <!-- echoStructArray rpc operation -->
+ <operation name="echoStructArray" parameterOrder="inputStructArray">
+ <input message="tns:echoStructArrayRequest"/>
+ <output message="tns:echoStructArrayResponse"/>
+ </operation>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <operation name="echoStructAsSimpleTypes" parameterOrder="inputStruct outputString outputInteger outputFloat">
+ <input message="tns:echoStructAsSimpleTypesRequest"/>
+ <output message="tns:echoStructAsSimpleTypesResponse"/>
+ </operation>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <operation name="echoSimpleTypesAsStruct" parameterOrder="inputString inputInteger inputFloat">
+ <input message="tns:echoSimpleTypesAsStructRequest"/>
+ <output message="tns:echoSimpleTypesAsStructResponse"/>
+ </operation>
+
+ <!-- echoNestedStruct rpc operation -->
+ <operation name="echoNestedStruct" parameterOrder="inputStruct">
+ <input message="tns:echoNestedStructRequest"/>
+ <output message="tns:echoNestedStructResponse"/>
+ </operation>
+
+ <!-- echoNestedArray rpc operation -->
+ <operation name="echoNestedArray" parameterOrder="inputStruct">
+ <input message="tns:echoNestedArrayRequest"/>
+ <output message="tns:echoNestedArrayResponse"/>
+ </operation>
+
+ <!-- echoStringArray rpc operation -->
+ <operation name="echoStringArray" parameterOrder="inputStringArray">
+ <input message="tns:echoStringArrayRequest"/>
+ <output message="tns:echoStringArrayResponse"/>
+ </operation>
+
+ <operation name="echoStringArrayInline" parameterOrder="inputStringArray">
+ <input message="tns:echoStringArrayInlineRequest"/>
+ <output message="tns:echoStringArrayInlineResponse"/>
+ </operation>
+
+ <!-- echoIntegerArray rpc operation -->
+ <operation name="echoIntegerArray" parameterOrder="inputIntegerArray">
+ <input message="tns:echoIntegerArrayRequest"/>
+ <output message="tns:echoIntegerArrayResponse"/>
+ </operation>
+
+ <!-- echoBoolean rpc operation -->
+ <operation name="echoBoolean" parameterOrder="inputBoolean">
+ <input message="tns:echoBooleanRequest"/>
+ <output message="tns:echoBooleanResponse"/>
+ </operation>
+
+ <!-- echoString rpc operation -->
+ <operation name="echoString" parameterOrder="inputString">
+ <input message="tns:echoStringRequest"/>
+ <output message="tns:echoStringResponse"/>
+ </operation>
+
+ </portType>
+
+ <binding name="Soap11TestRpcLitBinding" type="tns:SoapTestPortTypeRpc">
+ <soap11:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+
+ <!-- echoStruct rpc operation -->
+ <operation name="echoStruct">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStructArray rpc operation -->
+ <operation name="echoStructArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <operation name="echoStructAsSimpleTypes">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <operation name="echoSimpleTypesAsStruct">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoNestedStruct rpc operation -->
+ <operation name="echoNestedStruct">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoNestedArray rpc operation -->
+ <operation name="echoNestedArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStringArray rpc operation -->
+ <operation name="echoStringArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <operation name="echoStringArrayInline">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoIntegerArray rpc operation -->
+ <operation name="echoIntegerArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoBoolean rpc operation -->
+ <operation name="echoBoolean">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoString rpc operation -->
+ <operation name="echoString">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ </binding>
+
+ <service name="WhiteMesaSoapRpcLitTestSvc">
+
+ <port name="Soap11TestRpcLitPort" binding="tns:Soap11TestRpcLitBinding">
+ <soap11:address location="http://www.whitemesa.net/test-rpc-lit"/>
+ </port>
+
+ </service>
+
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/rpc/test-rpc-lit12.wsdl b/ruby_1_8_6/test/wsdl/rpc/test-rpc-lit12.wsdl
new file mode 100644
index 0000000000..901cde6f9c
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/test-rpc-lit12.wsdl
@@ -0,0 +1,455 @@
+<?xml version="1.0"?>
+
+<definitions name="RPC-Literal-TestDefinitions"
+ targetNamespace="http://whitemesa.net/wsdl/rpc-lit-test"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
+ xmlns:soap11="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="http://whitemesa.net/wsdl/rpc-lit-test"
+ xmlns:types="http://soapbuilders.org/rpc-lit-test/types"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://soapbuilders.org/rpc-lit-test/types">
+
+ <element name="stringItem" type="xsd:string" />
+ <complexType name="ArrayOfstring">
+ <sequence>
+ <element ref="types:stringItem" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <complexType name="ArrayOfint">
+ <sequence>
+ <element name="integer" type="xsd:int" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <element name="structItem" type="types:SOAPStruct" />
+ <complexType name="SOAPStruct">
+ <all>
+ <element name="varString" type="xsd:string"/>
+ <element name="varInt" type="xsd:int"/>
+ <element name="varFloat" type="xsd:float"/>
+ </all>
+ </complexType>
+
+ <complexType name="ArrayOfSOAPStruct">
+ <sequence>
+ <element ref="types:structItem" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+
+ <complexType name="SOAPStructStruct">
+ <all>
+ <element name="varString" type="xsd:string"/>
+ <element name="varInt" type="xsd:int"/>
+ <element name="varFloat" type="xsd:float"/>
+ <element ref="types:structItem" />
+ </all>
+ </complexType>
+
+ <complexType name="SOAPArrayStruct">
+ <all>
+ <element name="varString" type="xsd:string"/>
+ <element name="varInt" type="xsd:int"/>
+ <element name="varFloat" type="xsd:float"/>
+ <element name="varArray" type="types:ArrayOfstring"/>
+ </all>
+ </complexType>
+
+ </schema>
+
+ </types>
+
+ <!-- echoStruct rpc operation -->
+ <message name="echoStructRequest">
+ <part name="inputStruct" type="types:SOAPStruct"/>
+ </message>
+ <message name="echoStructResponse">
+ <part name="return" type="types:SOAPStruct"/>
+ </message>
+
+ <!-- echoStructArray rpc operation -->
+ <message name="echoStructArrayRequest">
+ <part name="inputStructArray" type="types:ArrayOfSOAPStruct"/>
+ </message>
+ <message name="echoStructArrayResponse">
+ <part name="return" type="types:ArrayOfSOAPStruct"/>
+ </message>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <message name="echoStructAsSimpleTypesRequest">
+ <part name="inputStruct" type="types:SOAPStruct"/>
+ </message>
+ <message name="echoStructAsSimpleTypesResponse">
+ <part name="outputString" type="xsd:string"/>
+ <part name="outputInteger" type="xsd:int"/>
+ <part name="outputFloat" type="xsd:float"/>
+ </message>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <message name="echoSimpleTypesAsStructRequest">
+ <part name="inputString" type="xsd:string"/>
+ <part name="inputInteger" type="xsd:int"/>
+ <part name="inputFloat" type="xsd:float"/>
+ </message>
+ <message name="echoSimpleTypesAsStructResponse">
+ <part name="return" type="types:SOAPStruct"/>
+ </message>
+
+ <!-- echoNestedStruct rpc operation -->
+ <message name="echoNestedStructRequest">
+ <part name="inputStruct" type="types:SOAPStructStruct"/>
+ </message>
+ <message name="echoNestedStructResponse">
+ <part name="return" type="types:SOAPStructStruct"/>
+ </message>
+
+ <!-- echoNestedArray rpc operation -->
+ <message name="echoNestedArrayRequest">
+ <part name="inputStruct" type="types:SOAPArrayStruct"/>
+ </message>
+ <message name="echoNestedArrayResponse">
+ <part name="return" type="types:SOAPArrayStruct"/>
+ </message>
+
+ <!-- echoStringArray rpc operation -->
+ <message name="echoStringArrayRequest">
+ <part name="inputStringArray" type="types:ArrayOfstring"/>
+ </message>
+ <message name="echoStringArrayResponse">
+ <part name="return" type="types:ArrayOfstring"/>
+ </message>
+
+ <!-- echoIntegerArray rpc operation -->
+ <message name="echoIntegerArrayRequest">
+ <part name="inputIntegerArray" type="types:ArrayOfint"/>
+ </message>
+ <message name="echoIntegerArrayResponse">
+ <part name="return" type="types:ArrayOfint"/>
+ </message>
+
+ <!-- echoBoolean rpc operation -->
+ <message name="echoBooleanRequest">
+ <part name="inputBoolean" type="xsd:boolean"/>
+ </message>
+ <message name="echoBooleanResponse">
+ <part name="return" type="xsd:boolean"/>
+ </message>
+
+ <!-- echoString rpc operation -->
+ <message name="echoStringRequest">
+ <part name="inputString" type="xsd:string"/>
+ </message>
+ <message name="echoStringResponse">
+ <part name="return" type="xsd:string"/>
+ </message>
+
+
+ <portType name="SoapTestPortTypeRpc">
+
+ <!-- echoStruct rpc operation -->
+ <operation name="echoStruct" parameterOrder="inputStruct">
+ <input message="tns:echoStructRequest"/>
+ <output message="tns:echoStructResponse"/>
+ </operation>
+
+ <!-- echoStructArray rpc operation -->
+ <operation name="echoStructArray" parameterOrder="inputStructArray">
+ <input message="tns:echoStructArrayRequest"/>
+ <output message="tns:echoStructArrayResponse"/>
+ </operation>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <operation name="echoStructAsSimpleTypes" parameterOrder="inputStruct outputString outputInteger outputFloat">
+ <input message="tns:echoStructAsSimpleTypesRequest"/>
+ <output message="tns:echoStructAsSimpleTypesResponse"/>
+ </operation>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <operation name="echoSimpleTypesAsStruct" parameterOrder="inputString inputInteger inputFloat">
+ <input message="tns:echoSimpleTypesAsStructRequest"/>
+ <output message="tns:echoSimpleTypesAsStructResponse"/>
+ </operation>
+
+ <!-- echoNestedStruct rpc operation -->
+ <operation name="echoNestedStruct" parameterOrder="inputStruct">
+ <input message="tns:echoNestedStructRequest"/>
+ <output message="tns:echoNestedStructResponse"/>
+ </operation>
+
+ <!-- echoNestedArray rpc operation -->
+ <operation name="echoNestedArray" parameterOrder="inputStruct">
+ <input message="tns:echoNestedArrayRequest"/>
+ <output message="tns:echoNestedArrayResponse"/>
+ </operation>
+
+ <!-- echoStringArray rpc operation -->
+ <operation name="echoStringArray" parameterOrder="inputStringArray">
+ <input message="tns:echoStringArrayRequest"/>
+ <output message="tns:echoStringArrayResponse"/>
+ </operation>
+
+ <!-- echoIntegerArray rpc operation -->
+ <operation name="echoIntegerArray" parameterOrder="inputIntegerArray">
+ <input message="tns:echoIntegerArrayRequest"/>
+ <output message="tns:echoIntegerArrayResponse"/>
+ </operation>
+
+ <!-- echoBoolean rpc operation -->
+ <operation name="echoBoolean" parameterOrder="inputBoolean">
+ <input message="tns:echoBooleanRequest"/>
+ <output message="tns:echoBooleanResponse"/>
+ </operation>
+
+ <!-- echoString rpc operation -->
+ <operation name="echoString" parameterOrder="inputString">
+ <input message="tns:echoStringRequest"/>
+ <output message="tns:echoStringResponse"/>
+ </operation>
+
+ </portType>
+
+ <binding name="Soap11TestRpcLitBinding" type="tns:SoapTestPortTypeRpc">
+ <soap11:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+
+ <!-- echoStruct rpc operation -->
+ <operation name="echoStruct">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStructArray rpc operation -->
+ <operation name="echoStructArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <operation name="echoStructAsSimpleTypes">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <operation name="echoSimpleTypesAsStruct">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoNestedStruct rpc operation -->
+ <operation name="echoNestedStruct">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoNestedArray rpc operation -->
+ <operation name="echoNestedArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStringArray rpc operation -->
+ <operation name="echoStringArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoIntegerArray rpc operation -->
+ <operation name="echoIntegerArray">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoBoolean rpc operation -->
+ <operation name="echoBoolean">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoString rpc operation -->
+ <operation name="echoString">
+ <soap11:operation soapAction="http://soapinterop.org/"/>
+ <input>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap11:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ </binding>
+
+ <binding name="Soap12TestRpcLitBinding" type="tns:SoapTestPortTypeRpc">
+ <soap12:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+
+ <!-- echoStruct rpc operation -->
+ <operation name="echoStruct">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStructArray rpc operation -->
+ <operation name="echoStructArray">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStructAsSimpleTypes rpc operation -->
+ <operation name="echoStructAsSimpleTypes">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoSimpleTypesAsStruct rpc operation -->
+ <operation name="echoSimpleTypesAsStruct">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoNestedStruct rpc operation -->
+ <operation name="echoNestedStruct">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoNestedArray rpc operation -->
+ <operation name="echoNestedArray">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoStringArray rpc operation -->
+ <operation name="echoStringArray">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoIntegerArray rpc operation -->
+ <operation name="echoIntegerArray">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoBoolean rpc operation -->
+ <operation name="echoBoolean">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ <!-- echoString rpc operation -->
+ <operation name="echoString">
+ <soap12:operation/>
+ <input>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </input>
+ <output>
+ <soap12:body use="literal" namespace="http://soapbuilders.org/rpc-lit-test" />
+ </output>
+ </operation>
+
+ </binding>
+
+ <service name="WhiteMesaSoapRpcLitTestSvc">
+
+ <port name="Soap12TestRpcLitPort" binding="tns:Soap12TestRpcLitBinding">
+ <soap12:address location="http://www.whitemesa.net/soap12/test-rpc-lit"/>
+ </port>
+ <port name="Soap11TestRpcLitPort" binding="tns:Soap11TestRpcLitBinding">
+ <soap11:address location="http://www.whitemesa.net/test-rpc-lit"/>
+ </port>
+
+ </service>
+
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/rpc/test_rpc.rb b/ruby_1_8_6/test/wsdl/rpc/test_rpc.rb
new file mode 100644
index 0000000000..7c4c3a7ad6
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/test_rpc.rb
@@ -0,0 +1,118 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+
+module WSDL; module RPC
+
+
+class TestRPC < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ def on_init
+ self.generate_explicit_type = false
+ add_rpc_method(self, 'echo', 'arg1', 'arg2')
+ add_rpc_method(self, 'echo_err', 'arg1', 'arg2')
+ end
+
+ DummyPerson = Struct.new("family-name".intern, :given_name)
+ def echo(arg1, arg2)
+ case arg1.family_name
+ when 'normal'
+ arg1.family_name = arg2.family_name
+ arg1.given_name = arg2.given_name
+ arg1.age = arg2.age
+ arg1
+ when 'dummy'
+ DummyPerson.new("family-name", "given_name")
+ else
+ raise
+ end
+ end
+
+ ErrPerson = Struct.new(:given_name, :no_such_element)
+ def echo_err(arg1, arg2)
+ ErrPerson.new(58, Time.now)
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_classdef
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ File.unlink(pathname('echo.rb'))
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:rpc", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_classdef
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("rpc.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['force'] = true
+ gen.run
+ require pathname('echo')
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def test_wsdl
+ wsdl = File.join(DIR, 'rpc.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDOUT if $DEBUG
+
+ ret = @client.echo(Person.new("normal", "", 12), Person.new("Hi", "Na", 21))
+ assert_equal(Person, ret.class)
+ assert_equal("Hi", ret.family_name)
+ assert_equal("Na", ret.given_name)
+ assert_equal(21, ret.age)
+
+ ret = @client.echo(Person.new("dummy", "", 12), Person.new("Hi", "Na", 21))
+ assert_equal(Person, ret.class)
+ assert_equal("family-name", ret.family_name)
+ assert_equal("given_name", ret.given_name)
+ assert_equal(nil, ret.age)
+
+ ret = @client.echo_err(Person.new("Na", "Hi"), Person.new("Hi", "Na"))
+ assert_equal(Person, ret.class)
+ assert_equal("58", ret.given_name)
+ assert_equal(nil, ret.family_name)
+ assert_equal(nil, ret.age)
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/wsdl/rpc/test_rpc_lit.rb b/ruby_1_8_6/test/wsdl/rpc/test_rpc_lit.rb
new file mode 100644
index 0000000000..080dbb82cf
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/rpc/test_rpc_lit.rb
@@ -0,0 +1,399 @@
+require 'test/unit'
+require 'wsdl/soap/wsdl2ruby'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+if defined?(HTTPAccess2) and defined?(OpenSSL)
+
+module WSDL; module RPC
+
+
+class TestRPCLIT < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ Namespace = "http://soapbuilders.org/rpc-lit-test"
+
+ def on_init
+ self.generate_explicit_type = false
+ add_rpc_operation(self,
+ XSD::QName.new(Namespace, 'echoStringArray'),
+ nil,
+ 'echoStringArray', [
+ ['in', 'inputStringArray', nil],
+ ['retval', 'return', nil]
+ ],
+ {
+ :request_style => :rpc,
+ :request_use => :literal,
+ :response_style => :rpc,
+ :response_use => :literal
+ }
+ )
+ add_rpc_operation(self,
+ XSD::QName.new(Namespace, 'echoStringArrayInline'),
+ nil,
+ 'echoStringArrayInline', [
+ ['in', 'inputStringArray', nil],
+ ['retval', 'return', nil]
+ ],
+ {
+ :request_style => :rpc,
+ :request_use => :literal,
+ :response_style => :rpc,
+ :response_use => :literal
+ }
+ )
+ add_rpc_operation(self,
+ XSD::QName.new(Namespace, 'echoNestedStruct'),
+ nil,
+ 'echoNestedStruct', [
+ ['in', 'inputNestedStruct', nil],
+ ['retval', 'return', nil]
+ ],
+ {
+ :request_style => :rpc,
+ :request_use => :literal,
+ :response_style => :rpc,
+ :response_use => :literal
+ }
+ )
+ add_rpc_operation(self,
+ XSD::QName.new(Namespace, 'echoStructArray'),
+ nil,
+ 'echoStructArray', [
+ ['in', 'inputStructArray', nil],
+ ['retval', 'return', nil]
+ ],
+ {
+ :request_style => :rpc,
+ :request_use => :literal,
+ :response_style => :rpc,
+ :response_use => :literal
+ }
+ )
+ end
+
+ def echoStringArray(strings)
+ # strings.stringItem => Array
+ ArrayOfstring[*strings.stringItem]
+ end
+
+ def echoStringArrayInline(strings)
+ ArrayOfstringInline[*strings.stringItem]
+ end
+
+ def echoNestedStruct(struct)
+ struct
+ end
+
+ def echoStructArray(ary)
+ ary
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_classdef
+ @client = nil
+ end
+
+ def teardown
+ teardown_server
+ unless $DEBUG
+ File.unlink(pathname('RPC-Literal-TestDefinitions.rb'))
+ File.unlink(pathname('RPC-Literal-TestDefinitionsDriver.rb'))
+ end
+ @client.reset_stream if @client
+ end
+
+ def setup_server
+ @server = Server.new('Test', Server::Namespace, '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_classdef
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("test-rpc-lit.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['driver'] = nil
+ gen.opt['force'] = true
+ gen.run
+ backupdir = Dir.pwd
+ begin
+ Dir.chdir(DIR)
+ require pathname('RPC-Literal-TestDefinitions.rb')
+ require pathname('RPC-Literal-TestDefinitionsDriver.rb')
+ ensure
+ Dir.chdir(backupdir)
+ end
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def test_wsdl_echoStringArray
+ wsdl = pathname('test-rpc-lit.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDOUT if $DEBUG
+ # response contains only 1 part.
+ result = @client.echoStringArray(ArrayOfstring["a", "b", "c"])[0]
+ assert_equal(["a", "b", "c"], result.stringItem)
+ end
+
+ ECHO_STRING_ARRAY_REQUEST =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoStringArray xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <inputStringArray xmlns:n2="http://soapbuilders.org/rpc-lit-test/types">
+ <n2:stringItem>a</n2:stringItem>
+ <n2:stringItem>b</n2:stringItem>
+ <n2:stringItem>c</n2:stringItem>
+ </inputStringArray>
+ </n1:echoStringArray>
+ </env:Body>
+</env:Envelope>]
+
+ ECHO_STRING_ARRAY_RESPONSE =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoStringArrayResponse xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <return xmlns:n2="http://soapbuilders.org/rpc-lit-test/types">
+ <n2:stringItem>a</n2:stringItem>
+ <n2:stringItem>b</n2:stringItem>
+ <n2:stringItem>c</n2:stringItem>
+ </return>
+ </n1:echoStringArrayResponse>
+ </env:Body>
+</env:Envelope>]
+
+ def test_stub_echoStringArray
+ drv = SoapTestPortTypeRpc.new("http://localhost:#{Port}/")
+ drv.wiredump_dev = str = ''
+ # response contains only 1 part.
+ result = drv.echoStringArray(ArrayOfstring["a", "b", "c"])[0]
+ assert_equal(["a", "b", "c"], result.stringItem)
+ assert_equal(ECHO_STRING_ARRAY_REQUEST, parse_requestxml(str))
+ assert_equal(ECHO_STRING_ARRAY_RESPONSE, parse_responsexml(str))
+ end
+
+ ECHO_STRING_ARRAY_INLINE_REQUEST =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoStringArrayInline xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <inputStringArray>
+ <stringItem>a</stringItem>
+ <stringItem>b</stringItem>
+ <stringItem>c</stringItem>
+ </inputStringArray>
+ </n1:echoStringArrayInline>
+ </env:Body>
+</env:Envelope>]
+
+ ECHO_STRING_ARRAY_INLINE_RESPONSE =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoStringArrayInlineResponse xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <return>
+ <stringItem>a</stringItem>
+ <stringItem>b</stringItem>
+ <stringItem>c</stringItem>
+ </return>
+ </n1:echoStringArrayInlineResponse>
+ </env:Body>
+</env:Envelope>]
+
+ def test_stub_echoStringArrayInline
+ drv = SoapTestPortTypeRpc.new("http://localhost:#{Port}/")
+ drv.wiredump_dev = str = ''
+ # response contains only 1 part.
+ result = drv.echoStringArrayInline(ArrayOfstringInline["a", "b", "c"])[0]
+ assert_equal(["a", "b", "c"], result.stringItem)
+ assert_equal(ECHO_STRING_ARRAY_INLINE_REQUEST, parse_requestxml(str))
+ assert_equal(ECHO_STRING_ARRAY_INLINE_RESPONSE, parse_responsexml(str))
+ end
+
+ ECHO_NESTED_STRUCT_REQUEST =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoNestedStruct xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <inputStruct xmlns:n2="http://soapbuilders.org/rpc-lit-test/types">
+ <varString>str</varString>
+ <varInt>1</varInt>
+ <varFloat>+1</varFloat>
+ <n2:structItem>
+ <varString>str</varString>
+ <varInt>1</varInt>
+ <varFloat>+1</varFloat>
+ </n2:structItem>
+ </inputStruct>
+ </n1:echoNestedStruct>
+ </env:Body>
+</env:Envelope>]
+
+ ECHO_NESTED_STRUCT_RESPONSE =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoNestedStructResponse xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <return xmlns:n2="http://soapbuilders.org/rpc-lit-test/types">
+ <varString>str</varString>
+ <varInt>1</varInt>
+ <varFloat>+1</varFloat>
+ <n2:structItem>
+ <varString>str</varString>
+ <varInt>1</varInt>
+ <varFloat>+1</varFloat>
+ </n2:structItem>
+ </return>
+ </n1:echoNestedStructResponse>
+ </env:Body>
+</env:Envelope>]
+
+ def test_wsdl_echoNestedStruct
+ wsdl = pathname('test-rpc-lit.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = str = ''
+ # response contains only 1 part.
+ result = @client.echoNestedStruct(SOAPStructStruct.new("str", 1, 1.0, SOAPStruct.new("str", 1, 1.0)))[0]
+ assert_equal('str', result.varString)
+ assert_equal('1', result.varInt)
+ assert_equal('+1', result.varFloat)
+ assert_equal('str', result.structItem.varString)
+ assert_equal('1', result.structItem.varInt)
+ assert_equal('+1', result.structItem.varFloat)
+ assert_equal(ECHO_NESTED_STRUCT_REQUEST, parse_requestxml(str))
+ assert_equal(ECHO_NESTED_STRUCT_RESPONSE, parse_responsexml(str))
+ end
+
+ def test_stub_echoNestedStruct
+ drv = SoapTestPortTypeRpc.new("http://localhost:#{Port}/")
+ drv.wiredump_dev = str = ''
+ # response contains only 1 part.
+ result = drv.echoNestedStruct(SOAPStructStruct.new("str", 1, 1.0, SOAPStruct.new("str", 1, 1.0)))[0]
+ assert_equal('str', result.varString)
+ assert_equal('1', result.varInt)
+ assert_equal('+1', result.varFloat)
+ assert_equal('str', result.structItem.varString)
+ assert_equal('1', result.structItem.varInt)
+ assert_equal('+1', result.structItem.varFloat)
+ assert_equal(ECHO_NESTED_STRUCT_REQUEST, parse_requestxml(str))
+ assert_equal(ECHO_NESTED_STRUCT_RESPONSE, parse_responsexml(str))
+ end
+
+ ECHO_STRUCT_ARRAY_REQUEST =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoStructArray xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <inputStructArray xmlns:n2="http://soapbuilders.org/rpc-lit-test/types">
+ <n2:structItem>
+ <varString>str</varString>
+ <varInt>2</varInt>
+ <varFloat>+2.1</varFloat>
+ </n2:structItem>
+ <n2:structItem>
+ <varString>str</varString>
+ <varInt>2</varInt>
+ <varFloat>+2.1</varFloat>
+ </n2:structItem>
+ </inputStructArray>
+ </n1:echoStructArray>
+ </env:Body>
+</env:Envelope>]
+
+ ECHO_STRUCT_ARRAY_RESPONSE =
+%q[<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <n1:echoStructArrayResponse xmlns:n1="http://soapbuilders.org/rpc-lit-test">
+ <return xmlns:n2="http://soapbuilders.org/rpc-lit-test/types">
+ <n2:structItem>
+ <varString>str</varString>
+ <varInt>2</varInt>
+ <varFloat>+2.1</varFloat>
+ </n2:structItem>
+ <n2:structItem>
+ <varString>str</varString>
+ <varInt>2</varInt>
+ <varFloat>+2.1</varFloat>
+ </n2:structItem>
+ </return>
+ </n1:echoStructArrayResponse>
+ </env:Body>
+</env:Envelope>]
+
+ def test_wsdl_echoStructArray
+ wsdl = pathname('test-rpc-lit.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = str = ''
+ # response contains only 1 part.
+ e = SOAPStruct.new("str", 2, 2.1)
+ result = @client.echoStructArray(ArrayOfSOAPStruct[e, e])
+ assert_equal(ECHO_STRUCT_ARRAY_REQUEST, parse_requestxml(str))
+ assert_equal(ECHO_STRUCT_ARRAY_RESPONSE, parse_responsexml(str))
+ end
+
+ def test_stub_echoStructArray
+ drv = SoapTestPortTypeRpc.new("http://localhost:#{Port}/")
+ drv.wiredump_dev = str = ''
+ # response contains only 1 part.
+ e = SOAPStruct.new("str", 2, 2.1)
+ result = drv.echoStructArray(ArrayOfSOAPStruct[e, e])
+ assert_equal(ECHO_STRUCT_ARRAY_REQUEST, parse_requestxml(str))
+ assert_equal(ECHO_STRUCT_ARRAY_RESPONSE, parse_responsexml(str))
+ end
+
+ def parse_requestxml(str)
+ str.split(/\r?\n\r?\n/)[3]
+ end
+
+ def parse_responsexml(str)
+ str.split(/\r?\n\r?\n/)[6]
+ end
+end
+
+
+end; end
+
+end
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedClient.rb b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedClient.rb
new file mode 100644
index 0000000000..55eb58c3dd
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedClient.rb
@@ -0,0 +1,34 @@
+#!/usr/bin/env ruby
+require 'echo_versionDriver.rb'
+
+endpoint_url = ARGV.shift
+obj = Echo_version_port_type.new(endpoint_url)
+
+# run ruby with -d to see SOAP wiredumps.
+obj.wiredump_dev = STDERR if $DEBUG
+
+# SYNOPSIS
+# echo_version(version)
+#
+# ARGS
+# version Version - {urn:example.com:simpletype-rpc-type}version
+#
+# RETURNS
+# version_struct Version_struct - {urn:example.com:simpletype-rpc-type}version_struct
+#
+version = nil
+puts obj.echo_version(version)
+
+# SYNOPSIS
+# echo_version_r(version_struct)
+#
+# ARGS
+# version_struct Version_struct - {urn:example.com:simpletype-rpc-type}version_struct
+#
+# RETURNS
+# version Version - {urn:example.com:simpletype-rpc-type}version
+#
+version_struct = nil
+puts obj.echo_version_r(version_struct)
+
+
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedDriver.rb b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedDriver.rb
new file mode 100644
index 0000000000..81c72d1acf
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedDriver.rb
@@ -0,0 +1,62 @@
+require 'echo_version.rb'
+
+require 'soap/rpc/driver'
+
+class Echo_version_port_type < ::SOAP::RPC::Driver
+ DefaultEndpointUrl = "http://localhost:10080"
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ Version_struct,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:example.com:simpletype-rpc-type", "version_struct") }
+ )
+
+ Methods = [
+ [ XSD::QName.new("urn:example.com:simpletype-rpc", "echo_version"),
+ "urn:example.com:simpletype-rpc",
+ "echo_version",
+ [ ["in", "version", ["::SOAP::SOAPString"]],
+ ["retval", "version_struct", ["Version_struct", "urn:example.com:simpletype-rpc-type", "version_struct"]] ],
+ { :request_style => :rpc, :request_use => :encoded,
+ :response_style => :rpc, :response_use => :encoded }
+ ],
+ [ XSD::QName.new("urn:example.com:simpletype-rpc", "echo_version_r"),
+ "urn:example.com:simpletype-rpc",
+ "echo_version_r",
+ [ ["in", "version_struct", ["Version_struct", "urn:example.com:simpletype-rpc-type", "version_struct"]],
+ ["retval", "version", ["::SOAP::SOAPString"]] ],
+ { :request_style => :rpc, :request_use => :encoded,
+ :response_style => :rpc, :response_use => :encoded }
+ ]
+ ]
+
+ def initialize(endpoint_url = nil)
+ endpoint_url ||= DefaultEndpointUrl
+ super(endpoint_url, nil)
+ self.mapping_registry = MappingRegistry
+ init_methods
+ end
+
+private
+
+ def init_methods
+ Methods.each do |definitions|
+ opt = definitions.last
+ if opt[:request_style] == :document
+ add_document_operation(*definitions)
+ else
+ add_rpc_operation(*definitions)
+ qname = definitions[0]
+ name = definitions[2]
+ if qname.name != name and qname.name.capitalize == name.capitalize
+ ::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg|
+ __send__(name, *arg)
+ end
+ end
+ end
+ end
+ end
+end
+
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedEchoVersion.rb b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedEchoVersion.rb
new file mode 100644
index 0000000000..806ece1626
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedEchoVersion.rb
@@ -0,0 +1,23 @@
+require 'xsd/qname'
+
+# {urn:example.com:simpletype-rpc-type}version_struct
+class Version_struct
+ @@schema_type = "version_struct"
+ @@schema_ns = "urn:example.com:simpletype-rpc-type"
+ @@schema_element = [["version", ["SOAP::SOAPString", XSD::QName.new(nil, "version")]], ["msg", ["SOAP::SOAPString", XSD::QName.new(nil, "msg")]]]
+
+ attr_accessor :version
+ attr_accessor :msg
+
+ def initialize(version = nil, msg = nil)
+ @version = version
+ @msg = msg
+ end
+end
+
+# {urn:example.com:simpletype-rpc-type}version
+module Version
+ C_16 = "1.6"
+ C_18 = "1.8"
+ C_19 = "1.9"
+end
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedServant.rb b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedServant.rb
new file mode 100644
index 0000000000..81cf50218e
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedServant.rb
@@ -0,0 +1,32 @@
+require 'echo_version.rb'
+
+class Echo_version_port_type
+ # SYNOPSIS
+ # echo_version(version)
+ #
+ # ARGS
+ # version Version - {urn:example.com:simpletype-rpc-type}version
+ #
+ # RETURNS
+ # version_struct Version_struct - {urn:example.com:simpletype-rpc-type}version_struct
+ #
+ def echo_version(version)
+ p [version]
+ raise NotImplementedError.new
+ end
+
+ # SYNOPSIS
+ # echo_version_r(version_struct)
+ #
+ # ARGS
+ # version_struct Version_struct - {urn:example.com:simpletype-rpc-type}version_struct
+ #
+ # RETURNS
+ # version Version - {urn:example.com:simpletype-rpc-type}version
+ #
+ def echo_version_r(version_struct)
+ p [version_struct]
+ raise NotImplementedError.new
+ end
+end
+
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedService.rb b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedService.rb
new file mode 100644
index 0000000000..be6f996562
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/expectedService.rb
@@ -0,0 +1,60 @@
+#!/usr/bin/env ruby
+require 'echo_versionServant.rb'
+
+require 'soap/rpc/standaloneServer'
+require 'soap/mapping/registry'
+
+class Echo_version_port_type
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ Version_struct,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:example.com:simpletype-rpc-type", "version_struct") }
+ )
+
+ Methods = [
+ [ XSD::QName.new("urn:example.com:simpletype-rpc", "echo_version"),
+ "urn:example.com:simpletype-rpc",
+ "echo_version",
+ [ ["in", "version", ["::SOAP::SOAPString"]],
+ ["retval", "version_struct", ["Version_struct", "urn:example.com:simpletype-rpc-type", "version_struct"]] ],
+ { :request_style => :rpc, :request_use => :encoded,
+ :response_style => :rpc, :response_use => :encoded }
+ ],
+ [ XSD::QName.new("urn:example.com:simpletype-rpc", "echo_version_r"),
+ "urn:example.com:simpletype-rpc",
+ "echo_version_r",
+ [ ["in", "version_struct", ["Version_struct", "urn:example.com:simpletype-rpc-type", "version_struct"]],
+ ["retval", "version", ["::SOAP::SOAPString"]] ],
+ { :request_style => :rpc, :request_use => :encoded,
+ :response_style => :rpc, :response_use => :encoded }
+ ]
+ ]
+end
+
+class Echo_version_port_typeApp < ::SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super(*arg)
+ servant = Echo_version_port_type.new
+ Echo_version_port_type::Methods.each do |definitions|
+ opt = definitions.last
+ if opt[:request_style] == :document
+ @router.add_document_operation(servant, *definitions)
+ else
+ @router.add_rpc_operation(servant, *definitions)
+ end
+ end
+ self.mapping_registry = Echo_version_port_type::MappingRegistry
+ end
+end
+
+if $0 == __FILE__
+ # Change listen port.
+ server = Echo_version_port_typeApp.new('app', nil, '0.0.0.0', 10080)
+ trap(:INT) do
+ server.shutdown
+ end
+ server.start
+end
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/rpc.wsdl b/ruby_1_8_6/test/wsdl/simpletype/rpc/rpc.wsdl
new file mode 100644
index 0000000000..91f71a8831
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/rpc.wsdl
@@ -0,0 +1,80 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name="echo_version"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="urn:example.com:simpletype-rpc"
+ xmlns:txd="urn:example.com:simpletype-rpc-type"
+ targetNamespace="urn:example.com:simpletype-rpc"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema targetNamespace="urn:example.com:simpletype-rpc-type">
+ <xsd:complexType name="version_struct">
+ <xsd:all>
+ <xsd:element name="version" type="txd:version" />
+ <xsd:element name="msg" type="xsd:string" />
+ </xsd:all>
+ </xsd:complexType>
+
+ <xsd:simpleType name="version">
+ <xsd:restriction base="xsd:string">
+ <xsd:enumeration value="1.6"/>
+ <xsd:enumeration value="1.8"/>
+ <xsd:enumeration value="1.9"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:schema>
+ </types>
+
+ <message name="msg_version">
+ <part name="version" type="txd:version"/>
+ </message>
+
+ <message name="msg_version_struct">
+ <part name="version_struct" type="txd:version_struct"/>
+ </message>
+
+ <portType name="echo_version_port_type">
+ <operation name="echo_version">
+ <input message="tns:msg_version"/>
+ <output message="tns:msg_version_struct"/>
+ </operation>
+
+ <operation name="echo_version_r">
+ <input message="tns:msg_version_struct"/>
+ <output message="tns:msg_version"/>
+ </operation>
+ </portType>
+
+ <binding name="echo_version_binding" type="tns:echo_version_port_type">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
+ <operation name="echo_version">
+ <soap:operation soapAction="urn:example.com:simpletype-rpc"/>
+ <input>
+ <soap:body use="encoded" namespace="urn:example.com:simpletype-rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:example.com:simpletype-rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+
+ <operation name="echo_version_r">
+ <soap:operation soapAction="urn:example.com:simpletype-rpc"/>
+ <input>
+ <soap:body use="encoded" namespace="urn:example.com:simpletype-rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </input>
+ <output>
+ <soap:body use="encoded" namespace="urn:example.com:simpletype-rpc"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="echo_version_service">
+ <port name="echo_version_port" binding="tns:echo_version_binding">
+ <soap:address location="http://localhost:10080"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/simpletype/rpc/test_rpc.rb b/ruby_1_8_6/test/wsdl/simpletype/rpc/test_rpc.rb
new file mode 100644
index 0000000000..fdd55552d0
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/rpc/test_rpc.rb
@@ -0,0 +1,62 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/wsdl2ruby'
+
+
+module WSDL; module SimpleType
+
+
+class TestRPC < Test::Unit::TestCase
+ DIR = File.dirname(File.expand_path(__FILE__))
+ def pathname(filename)
+ File.join(DIR, filename)
+ end
+
+ def test_rpc
+ gen = WSDL::SOAP::WSDL2Ruby.new
+ gen.location = pathname("rpc.wsdl")
+ gen.basedir = DIR
+ gen.logger.level = Logger::FATAL
+ gen.opt['classdef'] = nil
+ gen.opt['driver'] = nil
+ gen.opt['client_skelton'] = nil
+ gen.opt['servant_skelton'] = nil
+ gen.opt['standalone_server_stub'] = nil
+ gen.opt['force'] = true
+ suppress_warning do
+ gen.run
+ end
+ compare("expectedEchoVersion.rb", "echo_version.rb")
+ compare("expectedDriver.rb", "echo_versionDriver.rb")
+ compare("expectedService.rb", "echo_version_service.rb")
+ compare("expectedClient.rb", "echo_version_serviceClient.rb")
+ compare("expectedServant.rb", "echo_versionServant.rb")
+
+ File.unlink(pathname("echo_version.rb"))
+ File.unlink(pathname("echo_versionDriver.rb"))
+ File.unlink(pathname("echo_version_service.rb"))
+ File.unlink(pathname("echo_version_serviceClient.rb"))
+ File.unlink(pathname("echo_versionServant.rb"))
+ end
+
+ def compare(expected, actual)
+ assert_equal(loadfile(expected), loadfile(actual), actual)
+ end
+
+ def loadfile(file)
+ File.open(pathname(file)) { |f| f.read }
+ end
+
+ def suppress_warning
+ back = $VERBOSE
+ $VERBOSE = nil
+ begin
+ yield
+ ensure
+ $VERBOSE = back
+ end
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/wsdl/simpletype/simpletype.wsdl b/ruby_1_8_6/test/wsdl/simpletype/simpletype.wsdl
new file mode 100644
index 0000000000..623969c794
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/simpletype.wsdl
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="utf-8"?>
+<definitions name="ping_service"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:tns="urn:example.com:simpletype"
+ targetNamespace="urn:example.com:simpletype"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+ <types>
+ <xsd:schema targetNamespace="urn:example.com:simpletype">
+ <xsd:element name="ruby">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element minOccurs="1" maxOccurs="1" name="myversion" type="tns:myversion"/>
+ <xsd:element minOccurs="0" maxOccurs="1" name="date" type="xsd:dateTime"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+ <xsd:simpleType name="myversion">
+ <xsd:restriction base="xsd:string">
+ <xsd:enumeration value="1.6"/>
+ <xsd:enumeration value="1.8"/>
+ <xsd:enumeration value="1.9"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:element name="myid" type="tns:ID"/>
+
+ <xsd:simpleType name="ID">
+ <xsd:restriction base="xsd:string">
+ <xsd:length value="18"/>
+ <xsd:pattern value='[a-zA-Z0-9]{18}'/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:schema>
+ </types>
+
+ <message name="ping_in">
+ <part name="parameters" element="tns:ruby"/>
+ </message>
+
+ <message name="ping_out">
+ <part name="parameters" type="xsd:string"/>
+ </message>
+
+ <message name="ping_id_in">
+ <part name="parameters" element="tns:myid"/>
+ </message>
+
+ <message name="ping_id_out">
+ <part name="parameters" element="tns:myid"/>
+ </message>
+
+ <message name="versionmsg">
+ <part name="myversion" element="tns:myversion"/>
+ </message>
+
+ <portType name="ping_port_type">
+ <operation name="ping">
+ <input message="tns:ping_in"/>
+ <output message="tns:ping_out"/>
+ </operation>
+
+ <operation name="ping_id">
+ <input message="tns:ping_id_in"/>
+ <output message="tns:ping_id_out"/>
+ </operation>
+
+ <operation name="echo_version">
+ <input message="tns:versionmsg"/>
+ <output message="tns:versionmsg"/>
+ </operation>
+ </portType>
+
+ <binding name="ping_binding" type="tns:ping_port_type">
+ <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
+ <operation name="ping">
+ <soap:operation soapAction="urn:example.com:simpletype:ping" style="document"/>
+ <input><soap:body use="literal"/></input>
+ <output><soap:body use="literal"/></output>
+ </operation>
+
+ <operation name="ping_id">
+ <soap:operation soapAction="urn:example.com:simpletype:ping_id" style="document"/>
+ <input><soap:body use="literal"/></input>
+ <output><soap:body use="literal"/></output>
+ </operation>
+ </binding>
+
+ <service name="ping_service">
+ <port name="ping_port" binding="tns:ping_binding">
+ <soap:address location="http://localhost:10080"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/simpletype/test_simpletype.rb b/ruby_1_8_6/test/wsdl/simpletype/test_simpletype.rb
new file mode 100644
index 0000000000..7e644c3042
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/simpletype/test_simpletype.rb
@@ -0,0 +1,99 @@
+require 'test/unit'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+
+module WSDL
+module SimpleType
+
+
+class TestSimpleType < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ def on_init
+ add_document_method(self, 'urn:example.com:simpletype:ping', 'ping',
+ XSD::QName.new('urn:example.com:simpletype', 'ruby'),
+ XSD::QName.new('http://www.w3.org/2001/XMLSchema', 'string'))
+ add_document_method(self, 'urn:example.com:simpletype:ping_id', 'ping_id',
+ XSD::QName.new('urn:example.com:simpletype', 'myid'),
+ XSD::QName.new('urn:example.com:simpletype', 'myid'))
+ end
+
+ def ping(ruby)
+ version = ruby["myversion"]
+ date = ruby["date"]
+ "#{version} (#{date})"
+ end
+
+ def ping_id(id)
+ id
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:example.com:simpletype", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @server_thread = start_server_thread(@server)
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'simpletype.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.generate_explicit_type = false
+ @client.wiredump_dev = STDOUT if $DEBUG
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @server_thread.kill
+ @server_thread.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def start_server_thread(server)
+ t = Thread.new {
+ Thread.current.abort_on_exception = true
+ server.start
+ }
+ t
+ end
+
+ def test_ping
+ ret = @client.ping({:myversion => "1.9", :date => "2004-01-01T00:00:00Z"})
+ assert_equal("1.9 (2004-01-01T00:00:00Z)", ret)
+ end
+
+ def test_ping_id
+ ret = @client.ping_id("012345678901234567")
+ assert_equal("012345678901234567", ret)
+ # length
+ assert_raise(XSD::ValueSpaceError) do
+ @client.ping_id("0123456789012345678")
+ end
+ # pattern
+ assert_raise(XSD::ValueSpaceError) do
+ @client.ping_id("01234567890123456;")
+ end
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/wsdl/soap/soapbodyparts.wsdl b/ruby_1_8_6/test/wsdl/soap/soapbodyparts.wsdl
new file mode 100644
index 0000000000..0e6da0ebee
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/soap/soapbodyparts.wsdl
@@ -0,0 +1,103 @@
+<?xml version="1.0"?>
+<definitions
+ name="soapbodyparts"
+ targetNamespace="urn:www.example.com:soapbodyparts:v1"
+ xmlns:tns="urn:www.example.com:soapbodyparts:v1"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
+
+ <types>
+ <schema xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="urn:www.example.com:soapbodyparts:v1">
+ <import namespace = "http://schemas.xmlsoap.org/soap/encoding/"/>
+ <complexType name="StringArray">
+ <complexContent>
+ <restriction base="soapenc:Array">
+ <attribute ref="soapenc:arrayType" wsdl:arrayType="string[]"/>
+ </restriction>
+ </complexContent>
+ </complexType>
+ </schema>
+ </types>
+
+ <message name="fooRequest">
+ <part name="param1" type="xsd:string"/>
+ <part name="param2" type="xsd:string"/>
+ <part name="param3" type="xsd:string"/>
+ </message>
+
+ <message name="fooResponse">
+ <part name="return" type="tns:StringArray"/>
+ </message>
+
+ <portType name="FooServicePortType">
+ <operation name="foo"
+ parameterOrder="param3 param2 param1">
+ <input message="tns:fooRequest"/>
+ <output message="tns:fooResponse"/>
+ </operation>
+ <operation name="bar"
+ parameterOrder="param1 param2 param3">
+ <input message="tns:fooRequest"/>
+ <output message="tns:fooResponse"/>
+ </operation>
+ <operation name="baz">
+ <input message="tns:fooRequest"/>
+ <output message="tns:fooResponse"/>
+ </operation>
+ </portType>
+
+ <binding name="FooServicePortBinding" type="tns:FooServicePortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="foo">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ parts="param1 param3"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:www.example.com:soapbodyparts:v1"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:www.example.com:soapbodyparts:v1"/>
+ </output>
+ </operation>
+ <operation name="bar">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ parts="param3 param2"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:www.example.com:soapbodyparts:v1"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:www.example.com:soapbodyparts:v1"/>
+ </output>
+ </operation>
+ <operation name="baz">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:www.example.com:soapbodyparts:v1"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="urn:www.example.com:soapbodyparts:v1"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="FooService">
+ <port name="FooServicePort" binding="tns:FooServicePortBinding">
+ <soap:address location="http://raa.ruby-lang.org/soap/1.0.2/"/>
+ </port>
+ </service>
+</definitions>
diff --git a/ruby_1_8_6/test/wsdl/soap/test_soapbodyparts.rb b/ruby_1_8_6/test/wsdl/soap/test_soapbodyparts.rb
new file mode 100644
index 0000000000..291319aedf
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/soap/test_soapbodyparts.rb
@@ -0,0 +1,79 @@
+require 'test/unit'
+require 'soap/rpc/standaloneServer'
+require 'soap/wsdlDriver'
+
+
+module WSDL
+module SOAP
+
+
+class TestSOAPBodyParts < Test::Unit::TestCase
+ class Server < ::SOAP::RPC::StandaloneServer
+ def on_init
+ add_method(self, 'foo', 'p1', 'p2', 'p3')
+ add_method(self, 'bar', 'p1', 'p2', 'p3')
+ add_method(self, 'baz', 'p1', 'p2', 'p3')
+ end
+
+ def foo(p1, p2, p3)
+ [p1, p2, p3]
+ end
+
+ alias bar foo
+
+ def baz(p1, p2, p3)
+ [p3, p2, p1]
+ end
+ end
+
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ Port = 17171
+
+ def setup
+ setup_server
+ setup_client
+ end
+
+ def setup_server
+ @server = Server.new('Test', "urn:www.example.com:soapbodyparts:v1", '0.0.0.0', Port)
+ @server.level = Logger::Severity::ERROR
+ @t = Thread.new {
+ Thread.current.abort_on_exception = true
+ @server.start
+ }
+ end
+
+ def setup_client
+ wsdl = File.join(DIR, 'soapbodyparts.wsdl')
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client.endpoint_url = "http://localhost:#{Port}/"
+ @client.wiredump_dev = STDERR if $DEBUG
+ end
+
+ def teardown
+ teardown_server
+ teardown_client
+ end
+
+ def teardown_server
+ @server.shutdown
+ @t.kill
+ @t.join
+ end
+
+ def teardown_client
+ @client.reset_stream
+ end
+
+ def test_soapbodyparts
+ assert_equal(["1", "2", "3"], @client.foo("1", "2", "3"))
+ assert_equal(["3", "2", "1"], @client.foo("3", "2", "1"))
+ assert_equal(["1", "2", "3"], @client.bar("1", "2", "3"))
+ assert_equal(["3", "2", "1"], @client.baz("1", "2", "3"))
+ end
+end
+
+
+end
+end
diff --git a/ruby_1_8_6/test/wsdl/test_emptycomplextype.rb b/ruby_1_8_6/test/wsdl/test_emptycomplextype.rb
new file mode 100644
index 0000000000..71d1b8641d
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/test_emptycomplextype.rb
@@ -0,0 +1,21 @@
+require 'test/unit'
+require 'wsdl/parser'
+
+
+module WSDL
+
+
+class TestWSDL < Test::Unit::TestCase
+ def setup
+ @file = File.join(File.dirname(File.expand_path(__FILE__)), 'emptycomplextype.wsdl')
+ end
+
+ def test_wsdl
+ @wsdl = WSDL::Parser.new.parse(File.open(@file) { |f| f.read })
+ assert(/\{urn:jp.gr.jin.rrr.example.emptycomplextype\}emptycomplextype/ =~ @wsdl.inspect)
+ end
+end
+
+
+
+end
diff --git a/ruby_1_8_6/test/wsdl/test_fault.rb b/ruby_1_8_6/test/wsdl/test_fault.rb
new file mode 100644
index 0000000000..ec414528ee
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/test_fault.rb
@@ -0,0 +1,51 @@
+require 'test/unit'
+require 'soap/processor'
+require 'soap/mapping'
+require 'soap/rpc/element'
+require 'wsdl/parser'
+
+
+module WSDL
+
+
+class TestFault < Test::Unit::TestCase
+ def setup
+ @xml =<<__EOX__
+<?xml version="1.0" encoding="utf-8" ?>
+<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <env:Body>
+ <env:Fault xmlns:n1="http://schemas.xmlsoap.org/soap/encoding/"
+ env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+ <faultcode xsi:type="xsd:string">Server</faultcode>
+ <faultstring xsi:type="xsd:string">faultstring</faultstring>
+ <faultactor xsi:type="xsd:string">faultactor</faultactor>
+ <detail xmlns:n2="http://www.ruby-lang.org/xmlns/ruby/type/custom"
+ xsi:type="n2:SOAPException">
+ <excn_type_name xsi:type="xsd:string">type</excn_type_name>
+ <cause href="#id123"/>
+ </detail>
+ </env:Fault>
+ <cause id="id123" xsi:type="xsd:int">5</cause>
+ </env:Body>
+</env:Envelope>
+__EOX__
+ end
+
+ def test_by_wsdl
+ rpc_decode_typemap = WSDL::Definitions.soap_rpc_complextypes
+ opt = {}
+ opt[:default_encodingstyle] = ::SOAP::EncodingNamespace
+ opt[:decode_typemap] = rpc_decode_typemap
+ header, body = ::SOAP::Processor.unmarshal(@xml, opt)
+ fault = ::SOAP::Mapping.soap2obj(body.response)
+ assert_equal("Server", fault.faultcode)
+ assert_equal("faultstring", fault.faultstring)
+ assert_equal(URI.parse("faultactor"), fault.faultactor)
+ assert_equal(5, fault.detail.cause)
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/wsdl/test_multiplefault.rb b/ruby_1_8_6/test/wsdl/test_multiplefault.rb
new file mode 100644
index 0000000000..7004297dc9
--- /dev/null
+++ b/ruby_1_8_6/test/wsdl/test_multiplefault.rb
@@ -0,0 +1,39 @@
+require 'test/unit'
+require 'wsdl/parser'
+require 'wsdl/soap/classDefCreator'
+
+
+module WSDL
+
+
+class TestMultipleFault < Test::Unit::TestCase
+ def self.setup(filename)
+ @@filename = filename
+ end
+
+ def test_multiplefault
+ @wsdl = WSDL::Parser.new.parse(File.open(@@filename) { |f| f.read })
+ classdefstr = WSDL::SOAP::ClassDefCreator.new(@wsdl).dump
+ yield_eval_binding(classdefstr) do |b|
+ assert_equal(
+ WSDL::TestMultipleFault::AuthenticationError,
+ eval("AuthenticationError", b)
+ )
+ assert_equal(
+ WSDL::TestMultipleFault::AuthorizationError,
+ eval("AuthorizationError", b)
+ )
+ end
+ end
+
+ def yield_eval_binding(evaled)
+ b = binding
+ eval(evaled, b)
+ yield(b)
+ end
+end
+
+TestMultipleFault.setup(File.join(File.dirname(__FILE__), 'multiplefault.wsdl'))
+
+
+end
diff --git a/ruby_1_8_6/test/xmlrpc/data/bug_bool.expected b/ruby_1_8_6/test/xmlrpc/data/bug_bool.expected
new file mode 100644
index 0000000000..121e3a84ba
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/bug_bool.expected
@@ -0,0 +1,3 @@
+---
+- true
+- false \ No newline at end of file
diff --git a/ruby_1_8_6/test/xmlrpc/data/bug_bool.xml b/ruby_1_8_6/test/xmlrpc/data/bug_bool.xml
new file mode 100644
index 0000000000..04ed00709e
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/bug_bool.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0"?>
+<methodResponse>
+ <params>
+ <param>
+ <value><boolean>0</boolean></value>
+ </param>
+ </params>
+</methodResponse>
diff --git a/ruby_1_8_6/test/xmlrpc/data/bug_cdata.expected b/ruby_1_8_6/test/xmlrpc/data/bug_cdata.expected
new file mode 100644
index 0000000000..17d7861318
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/bug_cdata.expected
@@ -0,0 +1,3 @@
+---
+- true
+- test \ No newline at end of file
diff --git a/ruby_1_8_6/test/xmlrpc/data/bug_cdata.xml b/ruby_1_8_6/test/xmlrpc/data/bug_cdata.xml
new file mode 100644
index 0000000000..ba990e04f1
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/bug_cdata.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0"?>
+<methodResponse>
+ <params>
+ <param>
+ <value><string><![CDATA[test]]></string></value>
+ </param>
+ </params>
+</methodResponse>
diff --git a/ruby_1_8_6/test/xmlrpc/data/bug_covert.expected b/ruby_1_8_6/test/xmlrpc/data/bug_covert.expected
new file mode 100644
index 0000000000..a9ac103c64
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/bug_covert.expected
@@ -0,0 +1,10 @@
+---
+- true
+- >
+ Site,SANs,Array
+
+ Configured Capacity,Array Reserved Capacity,Array Ava
+
+ ilable Capacity,Array % Reserved,Host Allocated,Host Used,Host Free,Host %
+
+ Used
diff --git a/ruby_1_8_6/test/xmlrpc/data/bug_covert.xml b/ruby_1_8_6/test/xmlrpc/data/bug_covert.xml
new file mode 100644
index 0000000000..1d9abd2a06
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/bug_covert.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0"
+encoding="ISO-8859-1"?><methodResponse><params><param><value>Site,SANs,Array
+Configured Capacity,Array Reserved Capacity,Array Ava
+ilable Capacity,Array % Reserved,Host Allocated,Host Used,Host Free,Host %
+Used
+</value></param></params></methodResponse>
diff --git a/ruby_1_8_6/test/xmlrpc/data/datetime_iso8601.xml b/ruby_1_8_6/test/xmlrpc/data/datetime_iso8601.xml
new file mode 100644
index 0000000000..43d8da6c13
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/datetime_iso8601.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0"?>
+<methodResponse>
+ <params>
+ <param>
+ <value><dateTime.iso8601>20041105T01:15:23Z</dateTime.iso8601></value>
+ </param>
+ </params>
+</methodResponse>
diff --git a/ruby_1_8_6/test/xmlrpc/data/fault.xml b/ruby_1_8_6/test/xmlrpc/data/fault.xml
new file mode 100644
index 0000000000..041c464eb3
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/fault.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<methodResponse>
+ <fault>
+ <value><struct>
+ <member>
+ <name>faultCode</name>
+ <value><int>4</int></value>
+ </member>
+ <member>
+ <name>faultString</name>
+ <value>an error message</value>
+ </member>
+ </struct></value>
+ </fault>
+</methodResponse>
+
diff --git a/ruby_1_8_6/test/xmlrpc/data/value.expected b/ruby_1_8_6/test/xmlrpc/data/value.expected
new file mode 100644
index 0000000000..9463d02b13
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/value.expected
@@ -0,0 +1,7 @@
+---
+- Test
+-
+ - Hallo Leute
+ - " Hallo "
+ - ''
+ - " " \ No newline at end of file
diff --git a/ruby_1_8_6/test/xmlrpc/data/value.xml b/ruby_1_8_6/test/xmlrpc/data/value.xml
new file mode 100644
index 0000000000..1978616099
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/value.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<methodCall>
+ <methodName>Test</methodName>
+ <params>
+ <param>
+ <value>Hallo Leute</value>
+ </param>
+ <param>
+ <value> Hallo </value>
+ </param>
+ <param>
+ <value></value>
+ </param>
+ <param>
+ <value> </value>
+ </param>
+ </params>
+</methodCall>
+
+
+
+
diff --git a/ruby_1_8_6/test/xmlrpc/data/xml1.expected b/ruby_1_8_6/test/xmlrpc/data/xml1.expected
new file mode 100644
index 0000000000..ff96de8df3
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/xml1.expected
@@ -0,0 +1,243 @@
+---
+- true
+-
+ -
+ subscriber: MegaCorp
+ lastName: Baker
+ telephone1: 1-508-791-1267
+ telephone2: 1-800-445-2588
+ password: p1111
+ OID: "1"
+ email: hbaker@yahoo.com
+ adminId: hbaker
+ objectName: AdministratorDO
+ -
+ subscriber: CornerStore
+ lastName: Dragon
+ telephone1: 1-781-789-9089
+ telephone2: 1-800-445-2588
+ password: p3333
+ OID: "3"
+ email: adragon@yahoo.com
+ adminId: adragon
+ objectName: AdministratorDO
+ -
+ subscriber: Cyberdyne
+ lastName: Rodman
+ telephone1: 1-617-789-1890
+ telephone2: 1-800-445-2588
+ password: p4444
+ OID: "4"
+ email: mrodman@yahoo.com
+ adminId: mrodman
+ objectName: AdministratorDO
+ -
+ subscriber: StarSports
+ lastName: Jordan
+ telephone1: 1-617-890-7897
+ telephone2: 1-800-445-2588
+ password: p5555
+ OID: "5"
+ email: mjordan@yahoo.com
+ adminId: mjordan
+ objectName: AdministratorDO
+ -
+ subscriber: GreatBooks
+ lastName: Pippen
+ telephone1: 1-781-789-9876
+ telephone2: 1-800-445-2588
+ password: p6666
+ OID: "6"
+ email: gpippen@yahoo.com
+ adminId: gpippen
+ objectName: AdministratorDO
+ -
+ subscriber: AxisChemicals
+ lastName: Andhrew
+ telephone1: 1-781-678-8970
+ telephone2: 1-800-445-2588
+ password: p7777
+ OID: "7"
+ email: aandrew@yahoo.com
+ adminId: aandrew
+ objectName: AdministratorDO
+ -
+ subscriber: MediaShop
+ lastName: Vincent
+ telephone1: 1-786-897-8908
+ telephone2: 1-800-445-2588
+ password: p8888
+ OID: "8"
+ email: tvincent@yahoo.com
+ adminId: tvincent
+ objectName: AdministratorDO
+ -
+ subscriber: SmartShop
+ lastName: Richard
+ telephone1: 1-508-789-6789
+ telephone2: 1-800-445-2588
+ password: p9999
+ OID: "9"
+ email: krichard@yahoo.com
+ adminId: krichard
+ objectName: AdministratorDO
+ -
+ subscriber: HomeNeeds
+ lastName: Cornell
+ telephone1: 1-617-789-8979
+ telephone2: 1-800-445-2588
+ password: paaaa
+ OID: "10"
+ email: gconell@yahoo.com
+ adminId: gcornell
+ objectName: AdministratorDO
+ -
+ subscriber: MegaCorp
+ lastName: HorstMann
+ telephone1: 1-508-791-1267
+ telephone2: 1-800-445-2588
+ password: p1111
+ OID: "11"
+ email: shorstmann@yahoo.com
+ adminId: shorstmann
+ objectName: AdministratorDO
+ -
+ subscriber: CornerStore
+ lastName: Bob
+ telephone1: 1-781-789-9089
+ telephone2: 1-800-445-2588
+ password: p3333
+ OID: "13"
+ email: rbob@yahoo.com
+ adminId: rbob
+ objectName: AdministratorDO
+ -
+ subscriber: Cyberdyne
+ lastName: Peter
+ telephone1: 1-617-789-1890
+ telephone2: 1-800-445-2588
+ password: p4444
+ OID: "14"
+ email: speter@yahoo.com
+ adminId: speter
+ objectName: AdministratorDO
+ -
+ subscriber: StarSports
+ lastName: Novak
+ telephone1: 1-617-890-7897
+ telephone2: 1-800-445-2588
+ password: p5555
+ OID: "15"
+ email: pnovak@yahoo.com
+ adminId: pnovak
+ objectName: AdministratorDO
+ -
+ subscriber: GreatBooks
+ lastName: Nancy
+ telephone1: 1-781-789-9876
+ telephone2: 1-800-445-2588
+ password: p6666
+ OID: "16"
+ email: pnancy@yahoo.com
+ adminId: pnancy
+ objectName: AdministratorDO
+ -
+ subscriber: AxisChemicals
+ lastName: Michel
+ telephone1: 1-781-678-8970
+ telephone2: 1-800-445-2588
+ password: p7777
+ OID: "17"
+ email: hmichel@yahoo.com
+ adminId: hmichel
+ objectName: AdministratorDO
+ -
+ subscriber: MediaShop
+ lastName: David
+ telephone1: 1-786-897-8908
+ telephone2: 1-800-445-2588
+ password: p8888
+ OID: "18"
+ email: kdavid@yahoo.com
+ adminId: kdavid
+ objectName: AdministratorDO
+ -
+ subscriber: SmartShop
+ lastName: Valnoor
+ telephone1: 1-508-789-6789
+ telephone2: 1-800-445-2588
+ password: p9999
+ OID: "19"
+ email: pvalnoor@yahoo.com
+ adminId: pvalnoor
+ objectName: AdministratorDO
+ -
+ subscriber: HomeNeeds
+ lastName: Smith
+ telephone1: 1-617-789-8979
+ telephone2: 1-800-445-2588
+ password: paaaa
+ OID: "20"
+ email: wsmith@yahoo.com
+ adminId: wsmith
+ objectName: AdministratorDO
+ -
+ subscriber: MegaCorp
+ lastName: Caral
+ telephone1: 1-781-789-9876
+ telephone2: 1-800-445-2588
+ password: p6666
+ OID: "21"
+ email: gcaral@yahoo.com
+ adminId: gcaral
+ objectName: AdministratorDO
+ -
+ subscriber: CornerStore
+ lastName: Hillary
+ telephone1: 1-786-897-8908
+ telephone2: 1-800-445-2588
+ password: p8888
+ OID: "23"
+ email: phillary@yahoo.com
+ adminId: phillary
+ objectName: AdministratorDO
+ -
+ subscriber: Cyberdyne
+ lastName: Philip
+ telephone1: 1-508-789-6789
+ telephone2: 1-800-445-2588
+ password: p9999
+ OID: "24"
+ email: bphilip@yahoo.com
+ adminId: bphilip
+ objectName: AdministratorDO
+ -
+ subscriber: StarSports
+ lastName: Andrea
+ telephone1: 1-617-789-8979
+ telephone2: 1-800-445-2588
+ password: paaaa
+ OID: "25"
+ email: sandrea@yahoo.com
+ adminId: sandrea
+ objectName: AdministratorDO
+ -
+ subscriber: s4
+ lastName: "null"
+ telephone1: "null"
+ telephone2: "null"
+ password: s4
+ OID: "26"
+ email: "null"
+ adminId: s4
+ objectName: AdministratorDO
+ -
+ subscriber: BigBank
+ lastName: administrator
+ telephone1: ''
+ telephone2: ''
+ password: admin
+ OID: "82"
+ email: ''
+ adminId: admin
+ objectName: AdministratorDO \ No newline at end of file
diff --git a/ruby_1_8_6/test/xmlrpc/data/xml1.xml b/ruby_1_8_6/test/xmlrpc/data/xml1.xml
new file mode 100644
index 0000000000..10aa55483b
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/data/xml1.xml
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="ISO-8859-1"?><methodResponse><params><param><value><array><data><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>hbaker</value></member><member><name>email</name><value>hbaker@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-508-791-1267</value></member><member><name>OID</name><value>1</value></member><member><name>password</name><value>p1111</value></member><member><name>lastName</name><value>Baker</value></member><member><name>subscriber</name><value>MegaCorp</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>adragon</value></member><member><name>email</name><value>adragon@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-789-9089</value></member><member><name>OID</name><value>3</value></member><member><name>password</name><value>p3333</value></member><member><name>lastName</name><value>Dragon</value></member><member><name>subscriber</name><value>CornerStore</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>mrodman</value></member><member><name>email</name><value>mrodman@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-789-1890</value></member><member><name>OID</name><value>4</value></member><member><name>password</name><value>p4444</value></member><member><name>lastName</name><value>Rodman</value></member><member><name>subscriber</name><value>Cyberdyne</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>mjordan</value></member><member><name>email</name><value>mjordan@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-890-7897</value></member><member><name>OID</name><value>5</value></member><member><name>password</name><value>p5555</value></member><member><name>lastName</name><value>Jordan</value></member><member><name>subscriber</name><value>StarSports</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>gpippen</value></member><member><name>email</name><value>gpippen@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-789-9876</value></member><member><name>OID</name><value>6</value></member><member><name>password</name><value>p6666</value></member><member><name>lastName</name><value>Pippen</value></member><member><name>subscriber</name><value>GreatBooks</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>aandrew</value></member><member><name>email</name><value>aandrew@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-678-8970</value></member><member><name>OID</name><value>7</value></member><member><name>password</name><value>p7777</value></member><member><name>lastName</name><value>Andhrew</value></member><member><name>subscriber</name><value>AxisChemicals</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>tvincent</value></member><member><name>email</name><value>tvincent@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-786-897-8908</value></member><member><name>OID</name><value>8</value></member><member><name>password</name><value>p8888</value></member><member><name>lastName</name><value>Vincent</value></member><member><name>subscriber</name><value>MediaShop</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>krichard</value></member><member><name>email</name><value>krichard@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-508-789-6789</value></member><member><name>OID</name><value>9</value></member><member><name>password</name><value>p9999</value></member><member><name>lastName</name><value>Richard</value></member><member><name>subscriber</name><value>SmartShop</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>gcornell</value></member><member><name>email</name><value>gconell@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-789-8979</value></member><member><name>OID</name><value>10</value></member><member><name>password</name><value>paaaa</value></member><member><name>lastName</name><value>Cornell</value></member><member><name>subscriber</name><value>HomeNeeds</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>shorstmann</value></member><member><name>email</name><value>shorstmann@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-508-791-1267</value></member><member><name>OID</name><value>11</value></member><member><name>password</name><value>p1111</value></member><member><name>lastName</name><value>HorstMann</value></member><member><name>subscriber</name><value>MegaCorp</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>rbob</value></member><member><name>email</name><value>rbob@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-789-9089</value></member><member><name>OID</name><value>13</value></member><member><name>password</name><value>p3333</value></member><member><name>lastName</name><value>Bob</value></member><member><name>subscriber</name><value>CornerStore</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>speter</value></member><member><name>email</name><value>speter@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-789-1890</value></member><member><name>OID</name><value>14</value></member><member><name>password</name><value>p4444</value></member><member><name>lastName</name><value>Peter</value></member><member><name>subscriber</name><value>Cyberdyne</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>pnovak</value></member><member><name>email</name><value>pnovak@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-890-7897</value></member><member><name>OID</name><value>15</value></member><member><name>password</name><value>p5555</value></member><member><name>lastName</name><value>Novak</value></member><member><name>subscriber</name><value>StarSports</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>pnancy</value></member><member><name>email</name><value>pnancy@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-789-9876</value></member><member><name>OID</name><value>16</value></member><member><name>password</name><value>p6666</value></member><member><name>lastName</name><value>Nancy</value></member><member><name>subscriber</name><value>GreatBooks</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>hmichel</value></member><member><name>email</name><value>hmichel@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-678-8970</value></member><member><name>OID</name><value>17</value></member><member><name>password</name><value>p7777</value></member><member><name>lastName</name><value>Michel</value></member><member><name>subscriber</name><value>AxisChemicals</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>kdavid</value></member><member><name>email</name><value>kdavid@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-786-897-8908</value></member><member><name>OID</name><value>18</value></member><member><name>password</name><value>p8888</value></member><member><name>lastName</name><value>David</value></member><member><name>subscriber</name><value>MediaShop</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>pvalnoor</value></member><member><name>email</name><value>pvalnoor@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-508-789-6789</value></member><member><name>OID</name><value>19</value></member><member><name>password</name><value>p9999</value></member><member><name>lastName</name><value>Valnoor</value></member><member><name>subscriber</name><value>SmartShop</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>wsmith</value></member><member><name>email</name><value>wsmith@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-789-8979</value></member><member><name>OID</name><value>20</value></member><member><name>password</name><value>paaaa</value></member><member><name>lastName</name><value>Smith</value></member><member><name>subscriber</name><value>HomeNeeds</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>gcaral</value></member><member><name>email</name><value>gcaral@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-781-789-9876</value></member><member><name>OID</name><value>21</value></member><member><name>password</name><value>p6666</value></member><member><name>lastName</name><value>Caral</value></member><member><name>subscriber</name><value>MegaCorp</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>phillary</value></member><member><name>email</name><value>phillary@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-786-897-8908</value></member><member><name>OID</name><value>23</value></member><member><name>password</name><value>p8888</value></member><member><name>lastName</name><value>Hillary</value></member><member><name>subscriber</name><value>CornerStore</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>bphilip</value></member><member><name>email</name><value>bphilip@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-508-789-6789</value></member><member><name>OID</name><value>24</value></member><member><name>password</name><value>p9999</value></member><member><name>lastName</name><value>Philip</value></member><member><name>subscriber</name><value>Cyberdyne</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>sandrea</value></member><member><name>email</name><value>sandrea@yahoo.com</value></member><member><name>telephone2</name><value>1-800-445-2588</value></member><member><name>telephone1</name><value>1-617-789-8979</value></member><member><name>OID</name><value>25</value></member><member><name>password</name><value>paaaa</value></member><member><name>lastName</name><value>Andrea</value></member><member><name>subscriber</name><value>StarSports</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>s4</value></member><member><name>email</name><value>null</value></member><member><name>telephone2</name><value>null</value></member><member><name>telephone1</name><value>null</value></member><member><name>OID</name><value>26</value></member><member><name>password</name><value>s4</value></member><member><name>lastName</name><value>null</value></member><member><name>subscriber</name><value>s4</value></member></struct></value><value><struct><member><name>objectName</name><value>AdministratorDO</value></member><member><name>adminId</name><value>admin</value></member><member><name>email</name><value></value></member><member><name>telephone2</name><value></value></member><member><name>telephone1</name><value></value></member><member><name>OID</name><value>82</value></member><member><name>password</name><value>admin</value></member><member><name>lastName</name><value>administrator</value></member><member><name>subscriber</name><value>BigBank</value></member></struct></value></data></array></value></param></params></methodResponse>
diff --git a/ruby_1_8_6/test/xmlrpc/test_datetime.rb b/ruby_1_8_6/test/xmlrpc/test_datetime.rb
new file mode 100644
index 0000000000..e38cea6f74
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/test_datetime.rb
@@ -0,0 +1,159 @@
+require 'test/unit'
+require "xmlrpc/datetime"
+
+class Test_DateTime < Test::Unit::TestCase
+
+ def test_new
+ dt = createDateTime()
+
+ assert_instance_of(XMLRPC::DateTime, dt)
+ end
+
+ def test_new_exception
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(4.5, 13, 32, 25, 60, 60) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 12, 32, 25, 60, 60) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 12, 31, 25, 60, 60) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 12, 31, 24, 60, 60) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 12, 31, 24, 59, 60) }
+ assert_nothing_raised(ArgumentError) { XMLRPC::DateTime.new(2001, 12, 31, 24, 59, 59) }
+
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 0, 0, -1, -1, -1) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 1, 0, -1, -1, -1) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 1, 1, -1, -1, -1) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 1, 1, 0, -1, -1) }
+ assert_raises(ArgumentError) { XMLRPC::DateTime.new(2001, 1, 1, 0, 0, -1) }
+ assert_nothing_raised(ArgumentError) { XMLRPC::DateTime.new(2001, 1, 1, 0, 0, 0) }
+ end
+
+
+ def test_get_values
+ y, m, d, h, mi, s = 1970, 3, 24, 12, 0, 5
+ dt = XMLRPC::DateTime.new(y, m, d, h, mi, s)
+
+ assert_equal(y, dt.year)
+ assert_equal(m, dt.month)
+ assert_equal(m, dt.mon)
+ assert_equal(d, dt.day)
+
+ assert_equal(h, dt.hour)
+ assert_equal(mi,dt.min)
+ assert_equal(s, dt.sec)
+ end
+
+ def test_set_values
+ dt = createDateTime()
+ y, m, d, h, mi, s = 1950, 12, 9, 8, 52, 30
+
+ dt.year = y
+ dt.month = m
+ dt.day = d
+ dt.hour = h
+ dt.min = mi
+ dt.sec = s
+
+ assert_equal(y, dt.year)
+ assert_equal(m, dt.month)
+ assert_equal(m, dt.mon)
+ assert_equal(d, dt.day)
+
+ assert_equal(h, dt.hour)
+ assert_equal(mi,dt.min)
+ assert_equal(s, dt.sec)
+
+ dt.mon = 5
+ assert_equal(5, dt.month)
+ assert_equal(5, dt.mon)
+ end
+
+ def test_set_exception
+ dt = createDateTime()
+
+ assert_raises(ArgumentError) { dt.year = 4.5 }
+ assert_nothing_raised(ArgumentError) { dt.year = -2000 }
+
+ assert_raises(ArgumentError) { dt.month = 0 }
+ assert_raises(ArgumentError) { dt.month = 13 }
+ assert_nothing_raised(ArgumentError) { dt.month = 7 }
+
+ assert_raises(ArgumentError) { dt.mon = 0 }
+ assert_raises(ArgumentError) { dt.mon = 13 }
+ assert_nothing_raised(ArgumentError) { dt.mon = 7 }
+
+ assert_raises(ArgumentError) { dt.day = 0 }
+ assert_raises(ArgumentError) { dt.day = 32 }
+ assert_nothing_raised(ArgumentError) { dt.day = 16 }
+
+ assert_raises(ArgumentError) { dt.hour = -1 }
+ assert_raises(ArgumentError) { dt.hour = 25 }
+ assert_nothing_raised(ArgumentError) { dt.hour = 12 }
+
+ assert_raises(ArgumentError) { dt.min = -1 }
+ assert_raises(ArgumentError) { dt.min = 60 }
+ assert_nothing_raised(ArgumentError) { dt.min = 30 }
+
+ assert_raises(ArgumentError) { dt.sec = -1 }
+ assert_raises(ArgumentError) { dt.sec = 60 }
+ assert_nothing_raised(ArgumentError) { dt.sec = 30 }
+ end
+
+ def test_to_a
+ y, m, d, h, mi, s = 1970, 3, 24, 12, 0, 5
+ dt = XMLRPC::DateTime.new(y, m, d, h, mi, s)
+ a = dt.to_a
+
+ assert_instance_of(Array, a)
+ assert_equal(6, a.size, "Returned array has wrong size")
+
+ assert_equal(y, a[0])
+ assert_equal(m, a[1])
+ assert_equal(d, a[2])
+ assert_equal(h, a[3])
+ assert_equal(mi, a[4])
+ assert_equal(s, a[5])
+ end
+
+ def test_to_time1
+ y, m, d, h, mi, s = 1970, 3, 24, 12, 0, 5
+ dt = XMLRPC::DateTime.new(y, m, d, h, mi, s)
+ time = dt.to_time
+
+ assert_not_nil(time)
+
+ assert_equal(y, time.year)
+ assert_equal(m, time.month)
+ assert_equal(d, time.day)
+ assert_equal(h, time.hour)
+ assert_equal(mi, time.min)
+ assert_equal(s, time.sec)
+ end
+
+ def test_to_time2
+ dt = createDateTime()
+ dt.year = 1969
+
+ assert_nil(dt.to_time)
+ end
+
+ def test_to_date1
+ y, m, d, h, mi, s = 1970, 3, 24, 12, 0, 5
+ dt = XMLRPC::DateTime.new(y, m, d, h, mi, s)
+ date = dt.to_date
+
+ assert_equal(y, date.year)
+ assert_equal(m, date.month)
+ assert_equal(d, date.day)
+ end
+
+ def test_to_date2
+ dt = createDateTime()
+ dt.year = 666
+
+ assert_equal(666, dt.to_date.year)
+ end
+
+
+ def createDateTime
+ XMLRPC::DateTime.new(1970, 3, 24, 12, 0, 5)
+ end
+
+end
diff --git a/ruby_1_8_6/test/xmlrpc/test_features.rb b/ruby_1_8_6/test/xmlrpc/test_features.rb
new file mode 100644
index 0000000000..96a6313202
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/test_features.rb
@@ -0,0 +1,48 @@
+require 'test/unit'
+require "xmlrpc/create"
+require "xmlrpc/parser"
+require "xmlrpc/config"
+
+class Test_Features < Test::Unit::TestCase
+
+ def setup
+ @params = [nil, {"test" => nil}, [nil, 1, nil]]
+ end
+
+ def test_nil_create
+ XMLRPC::XMLWriter.each_installed_writer do |writer|
+ c = XMLRPC::Create.new(writer)
+
+ XMLRPC::Config.module_eval {remove_const(:ENABLE_NIL_CREATE)}
+ XMLRPC::Config.const_set(:ENABLE_NIL_CREATE, false)
+ assert_raises(RuntimeError) { str = c.methodCall("test", *@params) }
+
+ XMLRPC::Config.module_eval {remove_const(:ENABLE_NIL_CREATE)}
+ XMLRPC::Config.const_set(:ENABLE_NIL_CREATE, true)
+ assert_nothing_raised { str = c.methodCall("test", *@params) }
+ end
+ end
+
+ def test_nil_parse
+ XMLRPC::Config.module_eval {remove_const(:ENABLE_NIL_CREATE)}
+ XMLRPC::Config.const_set(:ENABLE_NIL_CREATE, true)
+
+ XMLRPC::XMLWriter.each_installed_writer do |writer|
+ c = XMLRPC::Create.new(writer)
+ str = c.methodCall("test", *@params)
+ XMLRPC::XMLParser.each_installed_parser do |parser|
+ para = nil
+
+ XMLRPC::Config.module_eval {remove_const(:ENABLE_NIL_PARSER)}
+ XMLRPC::Config.const_set(:ENABLE_NIL_PARSER, false)
+ assert_raises(RuntimeError) { para = parser.parseMethodCall(str) }
+
+ XMLRPC::Config.module_eval {remove_const(:ENABLE_NIL_PARSER)}
+ XMLRPC::Config.const_set(:ENABLE_NIL_PARSER, true)
+ assert_nothing_raised { para = parser.parseMethodCall(str) }
+ assert_equal(para[1], @params)
+ end
+ end
+ end
+
+end
diff --git a/ruby_1_8_6/test/xmlrpc/test_marshal.rb b/ruby_1_8_6/test/xmlrpc/test_marshal.rb
new file mode 100644
index 0000000000..38bc8c646f
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/test_marshal.rb
@@ -0,0 +1,93 @@
+require 'test/unit'
+require "xmlrpc/marshal"
+
+class Test_Marshal < Test::Unit::TestCase
+ # for test_parser_values
+ class Person
+ include XMLRPC::Marshallable
+ attr_reader :name
+ def initialize(name)
+ @name = name
+ end
+ end
+
+
+ def test1_dump_response
+ assert_nothing_raised(NameError) {
+ XMLRPC::Marshal.dump_response('arg')
+ }
+ end
+
+ def test1_dump_call
+ assert_nothing_raised(NameError) {
+ XMLRPC::Marshal.dump_call('methodName', 'arg')
+ }
+ end
+
+ def test2_dump_load_response
+ value = [1, 2, 3, {"test" => true}, 3.4]
+ res = XMLRPC::Marshal.dump_response(value)
+
+ assert_equal(value, XMLRPC::Marshal.load_response(res))
+ end
+
+ def test2_dump_load_call
+ methodName = "testMethod"
+ value = [1, 2, 3, {"test" => true}, 3.4]
+ exp = [methodName, [value, value]]
+
+ res = XMLRPC::Marshal.dump_call(methodName, value, value)
+
+ assert_equal(exp, XMLRPC::Marshal.load_call(res))
+ end
+
+ def test_parser_values
+ v1 = [
+ 1, -7778, # integers
+ 1.0, 0.0, -333.0, 2343434343.0, # floats
+ false, true, true, false, # booleans
+ "Hallo", "with < and >", "" # strings
+ ]
+
+ v2 = [
+ [v1, v1, v1],
+ {"a" => v1}
+ ]
+
+ v3 = [
+ XMLRPC::Base64.new("\001"*1000), # base64
+ :aSymbol, :anotherSym # symbols (-> string)
+ ]
+ v3_exp = [
+ "\001"*1000,
+ "aSymbol", "anotherSym"
+ ]
+ person = Person.new("Michael")
+
+ XMLRPC::XMLParser.each_installed_parser do |parser|
+ m = XMLRPC::Marshal.new(parser)
+
+ assert_equal( v1, m.load_response(m.dump_response(v1)) )
+ assert_equal( v2, m.load_response(m.dump_response(v2)) )
+ assert_equal( v3_exp, m.load_response(m.dump_response(v3)) )
+
+ pers = m.load_response(m.dump_response(person))
+
+ assert( pers.is_a?(Person) )
+ assert( person.name == pers.name )
+ end
+
+ # missing, Date, Time, DateTime
+ # Struct
+ end
+
+ def test_no_params_tag
+ # bug found by Idan Sofer
+
+ expect = %{<?xml version="1.0" ?><methodCall><methodName>myMethod</methodName><params/></methodCall>\n}
+
+ str = XMLRPC::Marshal.dump_call("myMethod")
+ assert_equal(expect, str)
+ end
+
+end
diff --git a/ruby_1_8_6/test/xmlrpc/test_parser.rb b/ruby_1_8_6/test/xmlrpc/test_parser.rb
new file mode 100644
index 0000000000..44ca1f88b7
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/test_parser.rb
@@ -0,0 +1,85 @@
+require 'test/unit'
+require 'xmlrpc/datetime'
+require "xmlrpc/parser"
+require 'yaml'
+
+module GenericParserTest
+ def datafile(base)
+ File.join(File.dirname(__FILE__), "data", base)
+ end
+
+ def load_data(name)
+ [File.read(datafile(name) + ".xml"), YAML.load(File.read(datafile(name) + ".expected"))]
+ end
+
+ def setup
+ @xml1, @expected1 = load_data('xml1')
+ @xml2, @expected2 = load_data('bug_covert')
+ @xml3, @expected3 = load_data('bug_bool')
+ @xml4, @expected4 = load_data('value')
+
+ @cdata_xml, @cdata_expected = load_data('bug_cdata')
+
+ @datetime_xml = File.read(datafile('datetime_iso8601.xml'))
+ @datetime_expected = XMLRPC::DateTime.new(2004, 11, 5, 1, 15, 23)
+
+ @fault_doc = File.read(datafile('fault.xml'))
+ end
+
+ # test parseMethodResponse --------------------------------------------------
+
+ def test_parseMethodResponse1
+ assert_equal(@expected1, @p.parseMethodResponse(@xml1))
+ end
+
+ def test_parseMethodResponse2
+ assert_equal(@expected2, @p.parseMethodResponse(@xml2))
+ end
+
+ def test_parseMethodResponse3
+ assert_equal(@expected3, @p.parseMethodResponse(@xml3))
+ end
+
+ def test_cdata
+ assert_equal(@cdata_expected, @p.parseMethodResponse(@cdata_xml))
+ end
+
+ def test_dateTime
+ assert_equal(@datetime_expected, @p.parseMethodResponse(@datetime_xml)[1])
+ end
+
+ # test parseMethodCall ------------------------------------------------------
+
+ def test_parseMethodCall
+ assert_equal(@expected4, @p.parseMethodCall(@xml4))
+ end
+
+ # test fault ----------------------------------------------------------------
+
+ def test_fault
+ flag, fault = @p.parseMethodResponse(@fault_doc)
+ assert_equal(flag, false)
+ unless fault.is_a? XMLRPC::FaultException
+ assert(false, "must be an instance of class XMLRPC::FaultException")
+ end
+ assert_equal(fault.faultCode, 4)
+ assert_equal(fault.faultString, "an error message")
+ end
+end
+
+# create test class for each installed parser
+XMLRPC::XMLParser.each_installed_parser do |parser|
+ klass = parser.class
+ name = klass.to_s.split("::").last
+
+ eval %{
+ class Test_#{name} < Test::Unit::TestCase
+ include GenericParserTest
+
+ def setup
+ super
+ @p = #{klass}.new
+ end
+ end
+ }
+end
diff --git a/ruby_1_8_6/test/xmlrpc/test_webrick_server.rb b/ruby_1_8_6/test/xmlrpc/test_webrick_server.rb
new file mode 100644
index 0000000000..4cd63cfa74
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/test_webrick_server.rb
@@ -0,0 +1,98 @@
+require 'test/unit'
+require 'webrick'
+require File.join(File.dirname(__FILE__), 'webrick_testing')
+require "xmlrpc/server"
+require 'xmlrpc/client'
+
+class Test_Webrick < Test::Unit::TestCase
+ include WEBrick_Testing
+
+ def create_servlet
+ s = XMLRPC::WEBrickServlet.new
+
+ s.add_handler("test.add") do |a,b|
+ a + b
+ end
+
+ s.add_handler("test.div") do |a,b|
+ if b == 0
+ raise XMLRPC::FaultException.new(1, "division by zero")
+ else
+ a / b
+ end
+ end
+
+ s.set_default_handler do |name, *args|
+ raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
+ " or wrong number of parameters!")
+ end
+
+ s.add_introspection
+
+ return s
+ end
+
+ def setup_http_server(port, use_ssl)
+ option = {
+ :Port => port,
+ :SSLEnable => use_ssl,
+ }
+ if use_ssl
+ require 'webrick/https'
+ option.update(
+ :SSLVerifyClient => ::OpenSSL::SSL::VERIFY_NONE,
+ :SSLCertName => []
+ )
+ end
+
+ start_server(option) {|w| w.mount('/RPC2', create_servlet) }
+
+ @s = XMLRPC::Client.new3(:port => port, :use_ssl => use_ssl)
+ end
+
+ PORT = 8070
+ def test_client_server
+ # NOTE: I don't enable SSL testing as this hangs
+ [false].each do |use_ssl|
+ begin
+ setup_http_server(PORT, use_ssl)
+ do_test
+ ensure
+ stop_server
+ end
+ end
+ end
+
+ def do_test
+ # simple call
+ assert_equal 9, @s.call('test.add', 4, 5)
+
+ # fault exception
+ assert_raises(XMLRPC::FaultException) { @s.call('test.div', 1, 0) }
+
+ # fault exception via call2
+ ok, param = @s.call2('test.div', 1, 0)
+ assert_equal false, ok
+ assert_instance_of XMLRPC::FaultException, param
+ assert_equal 1, param.faultCode
+ assert_equal 'division by zero', param.faultString
+
+ # call2 without fault exception
+ ok, param = @s.call2('test.div', 10, 5)
+ assert_equal true, ok
+ assert_equal param, 2
+
+ # introspection
+ assert_equal ["test.add", "test.div", "system.listMethods", "system.methodSignature", "system.methodHelp"], @s.call("system.listMethods")
+
+ # default handler (missing handler)
+ ok, param = @s.call2('test.nonexisting')
+ assert_equal false, ok
+ assert_equal -99, param.faultCode
+
+ # default handler (wrong number of arguments)
+ ok, param = @s.call2('test.add', 1, 2, 3)
+ assert_equal false, ok
+ assert_equal -99, param.faultCode
+ end
+end
diff --git a/ruby_1_8_6/test/xmlrpc/webrick_testing.rb b/ruby_1_8_6/test/xmlrpc/webrick_testing.rb
new file mode 100644
index 0000000000..a6830cece1
--- /dev/null
+++ b/ruby_1_8_6/test/xmlrpc/webrick_testing.rb
@@ -0,0 +1,37 @@
+require 'timeout'
+
+module WEBrick_Testing
+ class DummyLog < WEBrick::BasicLog
+ def initialize() super(self) end
+ def <<(*args) end
+ end
+
+ def start_server(config={})
+ raise "already started" if @__server
+ @__started = false
+
+ Thread.new {
+ @__server = WEBrick::HTTPServer.new(
+ {
+ :Logger => DummyLog.new,
+ :AccessLog => [],
+ :StartCallback => proc { @__started = true }
+ }.update(config))
+ yield @__server
+ @__server.start
+ @__started = false
+ }
+
+ Timeout.timeout(5) {
+ nil until @__started # wait until the server is ready
+ }
+ end
+
+ def stop_server
+ Timeout.timeout(5) {
+ @__server.shutdown
+ nil while @__started # wait until the server is down
+ }
+ @__server = nil
+ end
+end
diff --git a/ruby_1_8_6/test/xsd/codegen/test_classdef.rb b/ruby_1_8_6/test/xsd/codegen/test_classdef.rb
new file mode 100644
index 0000000000..64c4771918
--- /dev/null
+++ b/ruby_1_8_6/test/xsd/codegen/test_classdef.rb
@@ -0,0 +1,214 @@
+require 'test/unit'
+require 'xsd/codegen/classdef'
+
+
+module XSD; module CodeGen
+
+
+class TestClassDefCreator < Test::Unit::TestCase
+ include XSD::CodeGen
+ include GenSupport
+
+ def test_classdef_simple
+ c = ClassDef.new("Foo")
+ assert_equal(format(<<-EOD), c.dump)
+ class Foo
+ end
+ EOD
+ end
+
+ def test_classdef_complex
+ c = ClassDef.new("Foo::Bar::Baz", String)
+ assert_equal(format(<<-EOD), c.dump)
+ module Foo; module Bar
+
+ class Baz < String
+ end
+
+ end; end
+ EOD
+ end
+
+ def test_require
+ c = ClassDef.new("Foo")
+ c.def_require("foo/bar")
+ assert_equal(format(<<-EOD), c.dump)
+ require 'foo/bar'
+
+ class Foo
+ end
+ EOD
+ end
+
+ def test_comment
+ c = ClassDef.new("Foo")
+ c.def_require("foo/bar")
+ c.comment = <<-EOD
+ foo
+ EOD
+ assert_equal(format(<<-EOD), c.dump)
+ require 'foo/bar'
+
+ # foo
+ class Foo
+ end
+ EOD
+ c.comment = <<-EOD
+ foo
+
+ bar
+ baz
+
+ EOD
+ assert_equal(format(<<-EOD), c.dump)
+ require 'foo/bar'
+
+ # foo
+ #
+ # bar
+ # baz
+ #
+ class Foo
+ end
+ EOD
+ end
+
+ def test_emptymethod
+ c = ClassDef.new("Foo")
+ c.def_method('foo') do
+ end
+ c.def_method('bar') do
+ ''
+ end
+ assert_equal(format(<<-EOD), c.dump)
+ class Foo
+ def foo
+ end
+
+ def bar
+ end
+ end
+ EOD
+ end
+
+ def test_full
+ c = ClassDef.new("Foo::Bar::HobbitName", String)
+ c.def_require("foo/bar")
+ c.comment = <<-EOD
+ foo
+ bar
+ baz
+ EOD
+ c.def_const("FOO", 1)
+ c.def_classvar("@@foo", "var".dump)
+ c.def_classvar("baz", "1".dump)
+ c.def_attr("Foo", true, "foo")
+ c.def_attr("bar")
+ c.def_attr("baz", true)
+ c.def_attr("Foo2", true, "foo2")
+ c.def_attr("foo3", false, "foo3")
+ c.def_method("foo") do
+ <<-EOD
+ foo.bar = 1
+\tbaz.each do |ele|
+\t ele
+ end
+ EOD
+ end
+ c.def_method("baz", "qux") do
+ <<-EOD
+ [1, 2, 3].each do |i|
+ p i
+ end
+ EOD
+ end
+
+ m = MethodDef.new("qux", "quxx", "quxxx") do
+ <<-EOD
+ p quxx + quxxx
+ EOD
+ end
+ m.comment = "hello world\n123"
+ c.add_method(m)
+ c.def_code <<-EOD
+ Foo.new
+ Bar.z
+ EOD
+ c.def_code <<-EOD
+ Foo.new
+ Bar.z
+ EOD
+ c.def_privatemethod("foo", "baz", "*arg", "&block")
+
+ assert_equal(format(<<-EOD), c.dump)
+ require 'foo/bar'
+
+ module Foo; module Bar
+
+ # foo
+ # bar
+ # baz
+ class HobbitName < String
+ @@foo = "var"
+ @@baz = "1"
+
+ FOO = 1
+
+ Foo.new
+ Bar.z
+
+ Foo.new
+ Bar.z
+
+ attr_accessor :bar
+ attr_accessor :baz
+ attr_reader :foo3
+
+ def Foo
+ @foo
+ end
+
+ def Foo=(value)
+ @foo = value
+ end
+
+ def Foo2
+ @foo2
+ end
+
+ def Foo2=(value)
+ @foo2 = value
+ end
+
+ def foo
+ foo.bar = 1
+ baz.each do |ele|
+ ele
+ end
+ end
+
+ def baz(qux)
+ [1, 2, 3].each do |i|
+ p i
+ end
+ end
+
+ # hello world
+ # 123
+ def qux(quxx, quxxx)
+ p quxx + quxxx
+ end
+
+ private
+
+ def foo(baz, *arg, &block)
+ end
+ end
+
+ end; end
+ EOD
+ end
+end
+
+
+end; end
diff --git a/ruby_1_8_6/test/xsd/noencoding.xml b/ruby_1_8_6/test/xsd/noencoding.xml
new file mode 100644
index 0000000000..614ffa34ad
--- /dev/null
+++ b/ruby_1_8_6/test/xsd/noencoding.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="euc-jp"?>
+<schema xmlns="http://www.w3.org/2001/XMLSchema">
+ <!-- ¤¢¤¤¤¦ -->
+</schema>
diff --git a/ruby_1_8_6/test/xsd/test_noencoding.rb b/ruby_1_8_6/test/xsd/test_noencoding.rb
new file mode 100644
index 0000000000..48119ec1f7
--- /dev/null
+++ b/ruby_1_8_6/test/xsd/test_noencoding.rb
@@ -0,0 +1,32 @@
+require 'test/unit'
+require 'wsdl/xmlSchema/parser'
+
+
+module XSD
+
+
+class TestEmptyCharset < Test::Unit::TestCase
+ def setup
+ @file = File.join(File.dirname(File.expand_path(__FILE__)), 'noencoding.xml')
+ end
+
+ def test_wsdl
+ begin
+ xml = WSDL::XMLSchema::Parser.new.parse(File.open(@file) { |f| f.read })
+ rescue RuntimeError
+ if XSD::XMLParser.const_defined?("REXMLParser")
+ STDERR.puts("rexml cannot handle euc-jp without iconv/uconv.")
+ return
+ end
+ raise
+ rescue Errno::EINVAL
+ # unsupported encoding
+ return
+ end
+ assert_equal(WSDL::XMLSchema::Schema, xml.class)
+ assert_equal(0, xml.collect_elements.size)
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/xsd/test_xmlschemaparser.rb b/ruby_1_8_6/test/xsd/test_xmlschemaparser.rb
new file mode 100644
index 0000000000..10dff43e61
--- /dev/null
+++ b/ruby_1_8_6/test/xsd/test_xmlschemaparser.rb
@@ -0,0 +1,22 @@
+require 'test/unit'
+require 'wsdl/xmlSchema/parser'
+
+
+module XSD
+
+
+class TestXMLSchemaParser < Test::Unit::TestCase
+ def setup
+ @file = File.join(File.dirname(File.expand_path(__FILE__)), 'xmlschema.xml')
+ end
+
+ def test_wsdl
+ @wsdl = WSDL::XMLSchema::Parser.new.parse(File.open(@file) { |f| f.read })
+ assert_equal(WSDL::XMLSchema::Schema, @wsdl.class)
+ assert_equal(1, @wsdl.collect_elements.size)
+ end
+end
+
+
+
+end
diff --git a/ruby_1_8_6/test/xsd/test_xsd.rb b/ruby_1_8_6/test/xsd/test_xsd.rb
new file mode 100644
index 0000000000..6302f3128b
--- /dev/null
+++ b/ruby_1_8_6/test/xsd/test_xsd.rb
@@ -0,0 +1,1511 @@
+require 'test/unit'
+require 'xsd/datatypes'
+
+
+module XSD
+
+
+class TestXSD < Test::Unit::TestCase
+ NegativeZero = (-1.0 / (1.0 / 0.0))
+
+ def setup
+ end
+
+ def teardown
+ end
+
+ def assert_parsed_result(klass, str)
+ o = klass.new(str)
+ assert_equal(str, o.to_s)
+ end
+
+ def test_NSDBase
+ o = XSD::NSDBase.new
+ assert_equal(nil, o.type)
+ end
+
+ def test_XSDBase
+ o = XSD::XSDAnySimpleType.new
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+ assert_equal('', o.to_s)
+ end
+
+ def test_XSDNil
+ o = XSD::XSDNil.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::NilLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ o = XSD::XSDNil.new(nil)
+ assert_equal(true, o.is_nil)
+ assert_equal(nil, o.data)
+ assert_equal("", o.to_s)
+ o = XSD::XSDNil.new('var')
+ assert_equal(false, o.is_nil)
+ assert_equal('var', o.data)
+ assert_equal('var', o.to_s)
+ end
+
+ def test_XSDString_UTF8
+ o = XSD::XSDString.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::StringLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ str = "abc"
+ assert_equal(str, XSD::XSDString.new(str).data)
+ assert_equal(str, XSD::XSDString.new(str).to_s)
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDString.new("\0")
+ end
+ assert_raises(XSD::ValueSpaceError) do
+ p XSD::XSDString.new("\xC0\xC0").to_s
+ end
+ end
+
+ def test_XSDString_NONE
+ XSD::Charset.module_eval { @encoding_backup = @encoding; @encoding = "NONE" }
+ begin
+ o = XSD::XSDString.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::StringLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ str = "abc"
+ assert_equal(str, XSD::XSDString.new(str).data)
+ assert_equal(str, XSD::XSDString.new(str).to_s)
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDString.new("\0")
+ end
+ assert_raises(XSD::ValueSpaceError) do
+ p XSD::XSDString.new("\xC0\xC0").to_s
+ end
+ ensure
+ XSD::Charset.module_eval { @encoding = @encoding_backup }
+ end
+ end
+
+ def test_XSDBoolean
+ o = XSD::XSDBoolean.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::BooleanLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ ["true", true],
+ ["1", true],
+ ["false", false],
+ ["0", false],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDBoolean.new(data).data)
+ assert_equal(expected.to_s, XSD::XSDBoolean.new(data).to_s)
+ end
+
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDBoolean.new("nil").to_s
+ end
+ end
+
+ def test_XSDDecimal
+ o = XSD::XSDDecimal.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DecimalLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ -9999999999,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ -1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789,
+ ]
+ targets.each do |dec|
+ assert_equal(dec.to_s, XSD::XSDDecimal.new(dec).data)
+ end
+
+ targets = [
+ "0",
+ "0.00000001",
+ "1000000000",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123.45678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDDecimal.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["0.0", "0"],
+ ["-0.0", "0"],
+ ["+0.0", "0"],
+ ["0.", "0"],
+ [".0", "0"],
+ [
+ "+0.12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "0.1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
+ ],
+ [
+ ".0000012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "0.000001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
+ ],
+ [
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.",
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
+ ],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDDecimal.new(data).to_s)
+ end
+
+ targets = [
+ "0.000000000000a",
+ "00a.0000000000001",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDDecimal.new(d)
+ end
+ end
+ end
+
+ def test_XSDFloat
+ o = XSD::XSDFloat.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::FloatLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 3.14159265358979,
+ 12.34e36,
+ 1.402e-45,
+ -1.402e-45,
+ ]
+ targets.each do |f|
+ assert_equal(f, XSD::XSDFloat.new(f).data)
+ end
+
+ targets = [
+ "+3.141592654",
+ "+1.234e+37",
+ "+1.402e-45",
+ "-1.402e-45",
+ ]
+ targets.each do |f|
+ assert_equal(f, XSD::XSDFloat.new(f).to_s)
+ end
+
+ targets = [
+ [3, "+3"], # should be 3.0?
+ [-2, "-2"], # ditto
+ [3.14159265358979, "+3.141592654"],
+ [12.34e36, "+1.234e+37"],
+ [1.402e-45, "+1.402e-45"],
+ [-1.402e-45, "-1.402e-45"],
+ ["1.402e", "+1.402"],
+ ["12.34E36", "+1.234e+37"],
+ ["1.402E-45", "+1.402e-45"],
+ ["-1.402E-45", "-1.402e-45"],
+ ["1.402E", "+1.402"],
+ ]
+ targets.each do |f, str|
+ assert_equal(str, XSD::XSDFloat.new(f).to_s)
+ end
+
+ assert_equal("+0", XSD::XSDFloat.new(+0.0).to_s)
+ assert_equal("-0", XSD::XSDFloat.new(NegativeZero).to_s)
+ assert(XSD::XSDFloat.new(0.0/0.0).data.nan?)
+ assert_equal("INF", XSD::XSDFloat.new(1.0/0.0).to_s)
+ assert_equal(1, XSD::XSDFloat.new(1.0/0.0).data.infinite?)
+ assert_equal("-INF", XSD::XSDFloat.new(-1.0/0.0).to_s)
+ assert_equal(-1, XSD::XSDFloat.new(-1.0/0.0).data.infinite?)
+
+ targets = [
+ "0.000000000000a",
+ "00a.0000000000001",
+ "+-5",
+ "5_0",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDFloat.new(d)
+ end
+ end
+ end
+
+ def test_XSDDouble
+ o = XSD::XSDDouble.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DoubleLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 3.14159265358979,
+ 12.34e36,
+ 1.402e-45,
+ -1.402e-45,
+ ]
+ targets.each do |f|
+ assert_equal(f, XSD::XSDDouble.new(f).data)
+ end
+
+ targets = [
+ "+3.14159265358979",
+ "+1.234e+37",
+ "+1.402e-45",
+ "-1.402e-45",
+ ]
+ targets.each do |f|
+ assert_equal(f, XSD::XSDDouble.new(f).to_s)
+ end
+
+ targets = [
+ [3, "+3"], # should be 3.0?
+ [-2, "-2"], # ditto.
+ [3.14159265358979, "+3.14159265358979"],
+ [12.34e36, "+1.234e+37"],
+ [1.402e-45, "+1.402e-45"],
+ [-1.402e-45, "-1.402e-45"],
+ ["1.402e", "+1.402"],
+ ["12.34E36", "+1.234e+37"],
+ ["1.402E-45", "+1.402e-45"],
+ ["-1.402E-45", "-1.402e-45"],
+ ["1.402E", "+1.402"],
+ ]
+ targets.each do |f, str|
+ assert_equal(str, XSD::XSDDouble.new(f).to_s)
+ end
+
+ assert_equal("+0", XSD::XSDFloat.new(+0.0).to_s)
+ assert_equal("-0", XSD::XSDFloat.new(NegativeZero).to_s)
+ assert_equal("NaN", XSD::XSDDouble.new(0.0/0.0).to_s)
+ assert(XSD::XSDDouble.new(0.0/0.0).data.nan?)
+ assert_equal("INF", XSD::XSDDouble.new(1.0/0.0).to_s)
+ assert_equal(1, XSD::XSDDouble.new(1.0/0.0).data.infinite?)
+ assert_equal("-INF", XSD::XSDDouble.new(-1.0/0.0).to_s)
+ assert_equal(-1, XSD::XSDDouble.new(-1.0/0.0).data.infinite?)
+
+ targets = [
+ "0.000000000000a",
+ "00a.0000000000001",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDDouble.new(d)
+ end
+ end
+ end
+
+ def test_XSDDuration
+ o = XSD::XSDDuration.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DurationLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "P1Y2M3DT4H5M6S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S",
+ "P0DT3456H7890M1234.5678S",
+ "P1234Y5678M9012D",
+ "-P1234Y5678M9012DT3456H7890M1234.5678S",
+ "P5678M9012DT3456H7890M1234.5678S",
+ "-P1234Y9012DT3456H7890M1234.5678S",
+ "+P1234Y5678MT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT7890M1234.5678S",
+ "-P1234Y5678M9012DT3456H1234.5678S",
+ "+P1234Y5678M9012DT3456H7890M",
+ "P123400000000000Y",
+ "-P567800000000000M",
+ "+P901200000000000D",
+ "P0DT345600000000000H",
+ "-P0DT789000000000000M",
+ "+P0DT123400000000000.000000000005678S",
+ "P1234YT1234.5678S",
+ "-P5678MT7890M",
+ "+P9012DT3456H",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDDuration, str)
+ end
+
+ targets = [
+ ["P0Y0M0DT0H0M0S",
+ "P0D"],
+ ["-P0DT0S",
+ "-P0D"],
+ ["P01234Y5678M9012DT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y005678M9012DT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M0009012DT3456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M9012DT00003456H7890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M9012DT3456H000007890M1234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ["P1234Y5678M9012DT3456H7890M0000001234.5678S",
+ "P1234Y5678M9012DT3456H7890M1234.5678S"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDDuration.new(data).to_s)
+ end
+ end
+
+ def test_XSDDateTime
+ o = XSD::XSDDateTime.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DateTimeLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002-05-18T16:52:20Z",
+ "0001-01-01T00:00:00Z",
+ "9999-12-31T23:59:59Z",
+ "19999-12-31T23:59:59Z",
+ "2002-12-31T23:59:59.999Z",
+ "2002-12-31T23:59:59.001Z",
+ "2002-12-31T23:59:59.99999999999999999999Z",
+ "2002-12-31T23:59:59.00000000000000000001Z",
+ "2002-12-31T23:59:59+09:00",
+ "2002-12-31T23:59:59+00:01",
+ "2002-12-31T23:59:59-00:01",
+ "2002-12-31T23:59:59-23:59",
+ "2002-12-31T23:59:59.00000000000000000001+13:30",
+ "2002-12-31T23:59:59.5137Z",
+ "2002-12-31T23:59:59.51375Z", # 411/800
+ "2002-12-31T23:59:59.51375+12:34",
+ "-2002-05-18T16:52:20Z",
+ "-4713-01-01T12:00:00Z",
+ "-2002-12-31T23:59:59+00:01",
+ "-0001-12-31T23:59:59.00000000000000000001+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDDateTime, str)
+ end
+
+ targets = [
+ ["2002-12-31T23:59:59.00",
+ "2002-12-31T23:59:59Z"],
+ ["2002-12-31T23:59:59+00:00",
+ "2002-12-31T23:59:59Z"],
+ ["2002-12-31T23:59:59-00:00",
+ "2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59.00",
+ "-2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59+00:00",
+ "-2002-12-31T23:59:59Z"],
+ ["-2002-12-31T23:59:59-00:00",
+ "-2002-12-31T23:59:59Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDDateTime.new(data).to_s)
+ d = DateTime.parse(data)
+ d >>= 12 if d.year < 0 # XSDDateTime.year(-1) == DateTime.year(0)
+ assert_equal(expected, XSD::XSDDateTime.new(d).to_s)
+ end
+
+ targets = [
+ "0000-05-18T16:52:20Z",
+ "05-18T16:52:20Z",
+ "2002-05T16:52:20Z",
+ "2002-05-18T16:52Z",
+ "",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError, d.to_s) do
+ XSD::XSDDateTime.new(d)
+ end
+ end
+ end
+
+ def test_XSDTime
+ o = XSD::XSDTime.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::TimeLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "16:52:20Z",
+ "00:00:00Z",
+ "23:59:59Z",
+ "23:59:59.999Z",
+ "23:59:59.001Z",
+ "23:59:59.99999999999999999999Z",
+ "23:59:59.00000000000000000001Z",
+ "23:59:59+09:00",
+ "23:59:59+00:01",
+ "23:59:59-00:01",
+ "23:59:59-23:59",
+ "23:59:59.00000000000000000001+13:30",
+ "23:59:59.51345Z",
+ "23:59:59.51345+12:34",
+ "23:59:59+00:01",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDTime, str)
+ end
+
+ targets = [
+ ["23:59:59.00",
+ "23:59:59Z"],
+ ["23:59:59+00:00",
+ "23:59:59Z"],
+ ["23:59:59-00:00",
+ "23:59:59Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDTime.new(data).to_s)
+ end
+ end
+
+ def test_XSDDate
+ o = XSD::XSDDate.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::DateLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002-05-18Z",
+ "0001-01-01Z",
+ "9999-12-31Z",
+ "19999-12-31Z",
+ "2002-12-31+09:00",
+ "2002-12-31+00:01",
+ "2002-12-31-00:01",
+ "2002-12-31-23:59",
+ "2002-12-31+13:30",
+ "-2002-05-18Z",
+ "-19999-12-31Z",
+ "-2002-12-31+00:01",
+ "-0001-12-31+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDDate, str)
+ end
+
+ targets = [
+ ["2002-12-31",
+ "2002-12-31Z"],
+ ["2002-12-31+00:00",
+ "2002-12-31Z"],
+ ["2002-12-31-00:00",
+ "2002-12-31Z"],
+ ["-2002-12-31",
+ "-2002-12-31Z"],
+ ["-2002-12-31+00:00",
+ "-2002-12-31Z"],
+ ["-2002-12-31-00:00",
+ "-2002-12-31Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDDate.new(data).to_s)
+ d = Date.parse(data)
+ d >>= 12 if d.year < 0 # XSDDate.year(-1) == Date.year(0)
+ assert_equal(expected, XSD::XSDDate.new(d).to_s)
+ end
+ end
+end
+
+class TestXSD2 < Test::Unit::TestCase
+ def setup
+ # Nothing to do.
+ end
+
+ def teardown
+ # Nothing to do.
+ end
+
+ def assert_parsed_result(klass, str)
+ o = klass.new(str)
+ assert_equal(str, o.to_s)
+ end
+
+ def test_XSDGYearMonth
+ o = XSD::XSDGYearMonth.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GYearMonthLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002-05Z",
+ "0001-01Z",
+ "9999-12Z",
+ "19999-12Z",
+ "2002-12+09:00",
+ "2002-12+00:01",
+ "2002-12-00:01",
+ "2002-12-23:59",
+ "2002-12+13:30",
+ "-2002-05Z",
+ "-19999-12Z",
+ "-2002-12+00:01",
+ "-0001-12+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDGYearMonth, str)
+ end
+
+ targets = [
+ ["2002-12",
+ "2002-12Z"],
+ ["2002-12+00:00",
+ "2002-12Z"],
+ ["2002-12-00:00",
+ "2002-12Z"],
+ ["-2002-12",
+ "-2002-12Z"],
+ ["-2002-12+00:00",
+ "-2002-12Z"],
+ ["-2002-12-00:00",
+ "-2002-12Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDGYearMonth.new(data).to_s)
+ end
+ end
+
+ def test_XSDGYear
+ o = XSD::XSDGYear.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GYearLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "2002Z",
+ "0001Z",
+ "9999Z",
+ "19999Z",
+ "2002+09:00",
+ "2002+00:01",
+ "2002-00:01",
+ "2002-23:59",
+ "2002+13:30",
+ "-2002Z",
+ "-19999Z",
+ "-2002+00:01",
+ "-0001+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDGYear, str)
+ end
+
+ targets = [
+ ["2002",
+ "2002Z"],
+ ["2002+00:00",
+ "2002Z"],
+ ["2002-00:00",
+ "2002Z"],
+ ["-2002",
+ "-2002Z"],
+ ["-2002+00:00",
+ "-2002Z"],
+ ["-2002-00:00",
+ "-2002Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDGYear.new(data).to_s)
+ end
+ end
+
+ def test_XSDGMonthDay
+ o = XSD::XSDGMonthDay.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GMonthDayLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "05-18Z",
+ "01-01Z",
+ "12-31Z",
+ "12-31+09:00",
+ "12-31+00:01",
+ "12-31-00:01",
+ "12-31-23:59",
+ "12-31+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDGMonthDay, str)
+ end
+
+ targets = [
+ ["12-31",
+ "12-31Z"],
+ ["12-31+00:00",
+ "12-31Z"],
+ ["12-31-00:00",
+ "12-31Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDGMonthDay.new(data).to_s)
+ end
+ end
+
+ def test_XSDGDay
+ o = XSD::XSDGDay.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GDayLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "18Z",
+ "01Z",
+ "31Z",
+ "31+09:00",
+ "31+00:01",
+ "31-00:01",
+ "31-23:59",
+ "31+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDGDay, str)
+ end
+
+ targets = [
+ ["31",
+ "31Z"],
+ ["31+00:00",
+ "31Z"],
+ ["31-00:00",
+ "31Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDGDay.new(data).to_s)
+ end
+ end
+
+ def test_XSDGMonth
+ o = XSD::XSDGMonth.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::GMonthLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "05Z",
+ "01Z",
+ "12Z",
+ "12+09:00",
+ "12+00:01",
+ "12-00:01",
+ "12-23:59",
+ "12+13:30",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDGMonth, str)
+ end
+
+ targets = [
+ ["12",
+ "12Z"],
+ ["12+00:00",
+ "12Z"],
+ ["12-00:00",
+ "12Z"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDGMonth.new(data).to_s)
+ end
+ end
+
+ def test_XSDHexBinary
+ o = XSD::XSDHexBinary.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::HexBinaryLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "abcdef",
+ "\xe3\x81\xaa\xe3\x81\xb2",
+ %Q(\0),
+ "",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDHexBinary.new(str).string)
+ assert_equal(str.unpack("H*")[0 ].tr('a-f', 'A-F'),
+ XSD::XSDHexBinary.new(str).data)
+ o = XSD::XSDHexBinary.new
+ o.set_encoded(str.unpack("H*")[0 ].tr('a-f', 'A-F'))
+ assert_equal(str, o.string)
+ o.set_encoded(str.unpack("H*")[0 ].tr('A-F', 'a-f'))
+ assert_equal(str, o.string)
+ end
+
+ targets = [
+ "0FG7",
+ "0fg7",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError, d.to_s) do
+ o = XSD::XSDHexBinary.new
+ o.set_encoded(d)
+ p o.string
+ end
+ end
+ end
+
+ def test_XSDBase64Binary
+ o = XSD::XSDBase64Binary.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::Base64BinaryLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ "abcdef",
+ "\xe3\x81\xaa\xe3\x81\xb2",
+ %Q(\0),
+ "",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDBase64Binary.new(str).string)
+ assert_equal([str ].pack("m").chomp, XSD::XSDBase64Binary.new(str).data)
+ o = XSD::XSDBase64Binary.new
+ o.set_encoded([str ].pack("m").chomp)
+ assert_equal(str, o.string)
+ end
+
+ targets = [
+ "-",
+ "*",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError, d.to_s) do
+ o = XSD::XSDBase64Binary.new
+ o.set_encoded(d)
+ p o.string
+ end
+ end
+ end
+
+ def test_XSDAnyURI
+ o = XSD::XSDAnyURI.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::AnyURILiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ # Too few tests here I know. Believe uri module. :)
+ targets = [
+ "foo",
+ "http://foo",
+ "http://foo/bar/baz",
+ "http://foo/bar#baz",
+ "http://foo/bar%20%20?a+b",
+ "HTTP://FOO/BAR%20%20?A+B",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDAnyURI, str)
+ end
+ end
+
+ def test_XSDQName
+ o = XSD::XSDQName.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::QNameLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ # More strict test is needed but current implementation allows all non-':'
+ # chars like ' ', C0 or C1...
+ targets = [
+ "foo",
+ "foo:bar",
+ "a:b",
+ ]
+ targets.each do |str|
+ assert_parsed_result(XSD::XSDQName, str)
+ end
+ end
+
+
+ ###
+ ## Derived types
+ #
+
+ def test_XSDInteger
+ o = XSD::XSDInteger.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::IntegerLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ -9999999999,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ -1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDInteger.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "1000000000",
+ "-9999999999",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDInteger.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ [
+ "+12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
+ ],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDInteger.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDInteger.new(d)
+ end
+ end
+ end
+
+ def test_XSDNonPositiveInteger
+ o = XSD::XSDNonPositiveInteger.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::NonPositiveIntegerLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ -9999999999,
+ -1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDNonPositiveInteger.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "-9999999999",
+ "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDNonPositiveInteger.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDNonPositiveInteger.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDNonPositiveInteger.new(d)
+ end
+ end
+ end
+
+ def test_XSDNegativeInteger
+ o = XSD::XSDNegativeInteger.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::NegativeIntegerLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ -1,
+ -9999999999,
+ -1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDNegativeInteger.new(int).data)
+ end
+
+ targets = [
+ "-1",
+ "-9999999999",
+ "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDNegativeInteger.new(str).to_s)
+ end
+
+ targets = [
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDNegativeInteger.new(data).to_s)
+ end
+
+ targets = [
+ "-0.0",
+ "-5.2",
+ "-0.000000000000a",
+ "+-5",
+ "-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDNegativeInteger.new(d)
+ end
+ end
+ end
+
+ def test_XSDLong
+ o = XSD::XSDLong.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::LongLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 123,
+ -123,
+ 9223372036854775807,
+ -9223372036854775808,
+ ]
+ targets.each do |lng|
+ assert_equal(lng, XSD::XSDLong.new(lng).data)
+ end
+
+ targets = [
+ "0",
+ "123",
+ "-123",
+ "9223372036854775807",
+ "-9223372036854775808",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDLong.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDLong.new(data).to_s)
+ end
+
+ targets = [
+ 9223372036854775808,
+ -9223372036854775809,
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDLong.new(d)
+ end
+ end
+ end
+
+ def test_XSDInt
+ o = XSD::XSDInt.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::IntLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 123,
+ -123,
+ 2147483647,
+ -2147483648,
+ ]
+ targets.each do |lng|
+ assert_equal(lng, XSD::XSDInt.new(lng).data)
+ end
+
+ targets = [
+ "0",
+ "123",
+ "-123",
+ "2147483647",
+ "-2147483648",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDInt.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDInt.new(data).to_s)
+ end
+
+ targets = [
+ 2147483648,
+ -2147483649,
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDInt.new(d)
+ end
+ end
+ end
+
+ def test_XSDShort
+ o = XSD::XSDShort.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::ShortLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 123,
+ -123,
+ 32767,
+ -32768,
+ ]
+ targets.each do |lng|
+ assert_equal(lng, XSD::XSDShort.new(lng).data)
+ end
+
+ targets = [
+ "0",
+ "123",
+ "-123",
+ "32767",
+ "-32768",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDShort.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDShort.new(data).to_s)
+ end
+
+ targets = [
+ 32768,
+ -32769,
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDShort.new(d)
+ end
+ end
+ end
+
+ def test_XSDByte
+ o = XSD::XSDByte.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::ByteLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 123,
+ -123,
+ 127,
+ -128,
+ ]
+ targets.each do |lng|
+ assert_equal(lng, XSD::XSDByte.new(lng).data)
+ end
+
+ targets = [
+ "0",
+ "123",
+ "-123",
+ "127",
+ "-128",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDByte.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["-000123", "-123"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDByte.new(data).to_s)
+ end
+
+ targets = [
+ 128,
+ -129,
+ "0.0",
+ "-5.2",
+ "0.000000000000a",
+ "+-5",
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDByte.new(d)
+ end
+ end
+ end
+
+ def test_XSDNonNegativeInteger
+ o = XSD::XSDNonNegativeInteger.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::NonNegativeIntegerLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDNonNegativeInteger.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "1000000000",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDNonNegativeInteger.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ [
+ "+12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
+ ],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDNonNegativeInteger.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "0.000000000000a",
+ "+-5",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDNonNegativeInteger.new(d)
+ end
+ end
+ end
+
+ def test_XSDUnsignedLong
+ o = XSD::XSDUnsignedLong.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::UnsignedLongLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ 18446744073709551615,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDUnsignedLong.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "1000000000",
+ "18446744073709551615",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDUnsignedLong.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["+18446744073709551615", "18446744073709551615"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDUnsignedLong.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "0.000000000000a",
+ "+-5",
+ "18446744073709551615."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDUnsignedLong.new(d)
+ end
+ end
+ end
+
+ def test_XSDUnsignedInt
+ o = XSD::XSDUnsignedInt.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::UnsignedIntLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 1000000000,
+ 4294967295,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDUnsignedInt.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "1000000000",
+ "4294967295",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDUnsignedInt.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["+4294967295", "4294967295"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDUnsignedInt.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "0.000000000000a",
+ "+-5",
+ "4294967295."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDUnsignedInt.new(d)
+ end
+ end
+ end
+
+ def test_XSDUnsignedShort
+ o = XSD::XSDUnsignedShort.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::UnsignedShortLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 10000,
+ 65535,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDUnsignedShort.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "1000",
+ "65535",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDUnsignedShort.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["+65535", "65535"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDUnsignedShort.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "0.000000000000a",
+ "+-5",
+ "65535."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDUnsignedShort.new(d)
+ end
+ end
+ end
+
+ def test_XSDUnsignedByte
+ o = XSD::XSDUnsignedByte.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::UnsignedByteLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 0,
+ 10,
+ 255,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDUnsignedByte.new(int).data)
+ end
+
+ targets = [
+ "0",
+ "10",
+ "255",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDUnsignedByte.new(str).to_s)
+ end
+
+ targets = [
+ ["-0", "0"],
+ ["+0", "0"],
+ ["000123", "123"],
+ ["+255", "255"],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDUnsignedByte.new(data).to_s)
+ end
+
+ targets = [
+ "0.0",
+ "0.000000000000a",
+ "+-5",
+ "255."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDUnsignedByte.new(d)
+ end
+ end
+ end
+
+ def test_XSDPositiveInteger
+ o = XSD::XSDPositiveInteger.new
+ assert_equal(XSD::Namespace, o.type.namespace)
+ assert_equal(XSD::PositiveIntegerLiteral, o.type.name)
+ assert_equal(nil, o.data)
+ assert_equal(true, o.is_nil)
+
+ targets = [
+ 1,
+ 1000000000,
+ 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,
+ ]
+ targets.each do |int|
+ assert_equal(int, XSD::XSDPositiveInteger.new(int).data)
+ end
+
+ targets = [
+ "1",
+ "1000000000",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ ]
+ targets.each do |str|
+ assert_equal(str, XSD::XSDPositiveInteger.new(str).to_s)
+ end
+
+ targets = [
+ ["+1", "1"],
+ ["000123", "123"],
+ [
+ "+12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
+ ],
+ ]
+ targets.each do |data, expected|
+ assert_equal(expected, XSD::XSDPositiveInteger.new(data).to_s)
+ end
+
+ targets = [
+ "1.0",
+ "1.000000000000a",
+ "+-5",
+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890."
+ ]
+ targets.each do |d|
+ assert_raises(XSD::ValueSpaceError) do
+ XSD::XSDPositiveInteger.new(d)
+ end
+ end
+ end
+end
+
+
+end
diff --git a/ruby_1_8_6/test/xsd/xmlschema.xml b/ruby_1_8_6/test/xsd/xmlschema.xml
new file mode 100644
index 0000000000..018bd0cc67
--- /dev/null
+++ b/ruby_1_8_6/test/xsd/xmlschema.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xs:schema
+ attributeFormDefault="qualified"
+ elementFormDefault="qualified"
+ targetNamespace="urn:jp.gr.jin.rrr.example.fakeschema"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema">
+ <xs:element name="MessageDataSet">
+ <xs:complexType>
+ <xs:choice maxOccurs="unbounded" />
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
diff --git a/ruby_1_8_6/test/yaml/test_yaml.rb b/ruby_1_8_6/test/yaml/test_yaml.rb
new file mode 100644
index 0000000000..676310e6fc
--- /dev/null
+++ b/ruby_1_8_6/test/yaml/test_yaml.rb
@@ -0,0 +1,1284 @@
+# -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*-
+# vim:sw=4:ts=4
+# $Id$
+#
+require 'test/unit'
+require 'yaml'
+
+# [ruby-core:01946]
+module YAML_Tests
+ StructTest = Struct::new( :c )
+end
+
+class YAML_Unit_Tests < Test::Unit::TestCase
+ #
+ # Convert between YAML and the object to verify correct parsing and
+ # emitting
+ #
+ def assert_to_yaml( obj, yaml )
+ assert_equal( obj, YAML::load( yaml ) )
+ assert_equal( obj, YAML::parse( yaml ).transform )
+ assert_equal( obj, YAML::load( obj.to_yaml ) )
+ assert_equal( obj, YAML::parse( obj.to_yaml ).transform )
+ assert_equal( obj, YAML::load(
+ obj.to_yaml( :UseVersion => true, :UseHeader => true, :SortKeys => true )
+ ) )
+ end
+
+ #
+ # Test parser only
+ #
+ def assert_parse_only( obj, yaml )
+ assert_equal( obj, YAML::load( yaml ) )
+ assert_equal( obj, YAML::parse( yaml ).transform )
+ end
+
+ def assert_cycle( obj )
+ assert_equal( obj, YAML::load( obj.to_yaml ) )
+ end
+
+ def assert_path_segments( path, segments )
+ YAML::YPath.each_path( path ) { |choice|
+ assert_equal( choice.segments, segments.shift )
+ }
+ assert_equal( segments.length, 0, "Some segments leftover: #{ segments.inspect }" )
+ end
+
+ #
+ # Make a time with the time zone
+ #
+ def mktime( year, mon, day, hour, min, sec, usec, zone = "Z" )
+ usec = usec.to_s.to_f * 1000000
+ val = Time::utc( year.to_i, mon.to_i, day.to_i, hour.to_i, min.to_i, sec.to_i, usec )
+ if zone != "Z"
+ hour = zone[0,3].to_i * 3600
+ min = zone[3,2].to_i * 60
+ ofs = (hour + min)
+ val = Time.at( val.to_f - ofs )
+ end
+ return val
+ end
+
+ #
+ # Tests modified from 00basic.t in YAML.pm
+ #
+ def test_basic_map
+ # Simple map
+ assert_parse_only(
+ { 'one' => 'foo', 'three' => 'baz', 'two' => 'bar' }, <<EOY
+one: foo
+two: bar
+three: baz
+EOY
+ )
+ end
+
+ def test_basic_strings
+ # Common string types
+ assert_cycle("x")
+ assert_cycle(":x")
+ assert_cycle(":")
+ assert_parse_only(
+ { 1 => 'simple string', 2 => 42, 3 => '1 Single Quoted String',
+ 4 => 'YAML\'s Double "Quoted" String', 5 => "A block\n with several\n lines.\n",
+ 6 => "A \"chomped\" block", 7 => "A folded\n string\n", 8 => ": started string" },
+ <<EOY
+1: simple string
+2: 42
+3: '1 Single Quoted String'
+4: "YAML's Double \\\"Quoted\\\" String"
+5: |
+ A block
+ with several
+ lines.
+6: |-
+ A "chomped" block
+7: >
+ A
+ folded
+ string
+8: ": started string"
+EOY
+ )
+ end
+
+ #
+ # Test the specification examples
+ # - Many examples have been changes because of whitespace problems that
+ # caused the two to be inequivalent, or keys to be sorted wrong
+ #
+
+ def test_spec_simple_implicit_sequence
+ # Simple implicit sequence
+ assert_to_yaml(
+ [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ], <<EOY
+- Mark McGwire
+- Sammy Sosa
+- Ken Griffey
+EOY
+ )
+ end
+
+ def test_spec_simple_implicit_map
+ # Simple implicit map
+ assert_to_yaml(
+ { 'hr' => 65, 'avg' => 0.278, 'rbi' => 147 }, <<EOY
+avg: 0.278
+hr: 65
+rbi: 147
+EOY
+ )
+ end
+
+ def test_spec_simple_map_with_nested_sequences
+ # Simple mapping with nested sequences
+ assert_to_yaml(
+ { 'american' =>
+ [ 'Boston Red Sox', 'Detroit Tigers', 'New York Yankees' ],
+ 'national' =>
+ [ 'New York Mets', 'Chicago Cubs', 'Atlanta Braves' ] }, <<EOY
+american:
+ - Boston Red Sox
+ - Detroit Tigers
+ - New York Yankees
+national:
+ - New York Mets
+ - Chicago Cubs
+ - Atlanta Braves
+EOY
+ )
+ end
+
+ def test_spec_simple_sequence_with_nested_map
+ # Simple sequence with nested map
+ assert_to_yaml(
+ [
+ {'name' => 'Mark McGwire', 'hr' => 65, 'avg' => 0.278},
+ {'name' => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288}
+ ], <<EOY
+-
+ avg: 0.278
+ hr: 65
+ name: Mark McGwire
+-
+ avg: 0.288
+ hr: 63
+ name: Sammy Sosa
+EOY
+ )
+ end
+
+ def test_spec_sequence_of_sequences
+ # Simple sequence with inline sequences
+ assert_parse_only(
+ [
+ [ 'name', 'hr', 'avg' ],
+ [ 'Mark McGwire', 65, 0.278 ],
+ [ 'Sammy Sosa', 63, 0.288 ]
+ ], <<EOY
+- [ name , hr , avg ]
+- [ Mark McGwire , 65 , 0.278 ]
+- [ Sammy Sosa , 63 , 0.288 ]
+EOY
+ )
+ end
+
+ def test_spec_mapping_of_mappings
+ # Simple map with inline maps
+ assert_parse_only(
+ { 'Mark McGwire' =>
+ { 'hr' => 65, 'avg' => 0.278 },
+ 'Sammy Sosa' =>
+ { 'hr' => 63, 'avg' => 0.288 }
+ }, <<EOY
+Mark McGwire: {hr: 65, avg: 0.278}
+Sammy Sosa: {hr: 63,
+ avg: 0.288}
+EOY
+ )
+ end
+
+ def test_ambiguous_comments
+ # [ruby-talk:88012]
+ assert_to_yaml( "Call the method #dave", <<EOY )
+--- "Call the method #dave"
+EOY
+ end
+
+ def test_spec_nested_comments
+ # Map and sequences with comments
+ assert_parse_only(
+ { 'hr' => [ 'Mark McGwire', 'Sammy Sosa' ],
+ 'rbi' => [ 'Sammy Sosa', 'Ken Griffey' ] }, <<EOY
+hr: # 1998 hr ranking
+ - Mark McGwire
+ - Sammy Sosa
+rbi:
+ # 1998 rbi ranking
+ - Sammy Sosa
+ - Ken Griffey
+EOY
+ )
+ end
+
+ def test_spec_anchors_and_aliases
+ # Anchors and aliases
+ assert_parse_only(
+ { 'hr' =>
+ [ 'Mark McGwire', 'Sammy Sosa' ],
+ 'rbi' =>
+ [ 'Sammy Sosa', 'Ken Griffey' ] }, <<EOY
+hr:
+ - Mark McGwire
+ # Name "Sammy Sosa" scalar SS
+ - &SS Sammy Sosa
+rbi:
+ # So it can be referenced later.
+ - *SS
+ - Ken Griffey
+EOY
+ )
+
+ assert_to_yaml(
+ [{"arrival"=>"EDI", "departure"=>"LAX", "fareref"=>"DOGMA", "currency"=>"GBP"}, {"arrival"=>"MEL", "departure"=>"SYD", "fareref"=>"MADF", "currency"=>"AUD"}, {"arrival"=>"MCO", "departure"=>"JFK", "fareref"=>"DFSF", "currency"=>"USD"}], <<EOY
+ -
+ &F fareref: DOGMA
+ &C currency: GBP
+ &D departure: LAX
+ &A arrival: EDI
+ - { *F: MADF, *C: AUD, *D: SYD, *A: MEL }
+ - { *F: DFSF, *C: USD, *D: JFK, *A: MCO }
+EOY
+ )
+
+ assert_to_yaml(
+ {"ALIASES"=>["fareref", "currency", "departure", "arrival"], "FARES"=>[{"arrival"=>"EDI", "departure"=>"LAX", "fareref"=>"DOGMA", "currency"=>"GBP"}, {"arrival"=>"MEL", "departure"=>"SYD", "fareref"=>"MADF", "currency"=>"AUD"}, {"arrival"=>"MCO", "departure"=>"JFK", "fareref"=>"DFSF", "currency"=>"USD"}]}, <<EOY
+---
+ALIASES: [&f fareref, &c currency, &d departure, &a arrival]
+FARES:
+- *f: DOGMA
+ *c: GBP
+ *d: LAX
+ *a: EDI
+
+- *f: MADF
+ *c: AUD
+ *d: SYD
+ *a: MEL
+
+- *f: DFSF
+ *c: USD
+ *d: JFK
+ *a: MCO
+
+EOY
+ )
+
+ end
+
+ def test_spec_mapping_between_sequences
+ # Complex key #1
+ dj = Date.new( 2001, 7, 23 )
+ assert_parse_only(
+ { [ 'Detroit Tigers', 'Chicago Cubs' ] => [ Date.new( 2001, 7, 23 ) ],
+ [ 'New York Yankees', 'Atlanta Braves' ] => [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ] }, <<EOY
+? # PLAY SCHEDULE
+ - Detroit Tigers
+ - Chicago Cubs
+:
+ - 2001-07-23
+
+? [ New York Yankees,
+ Atlanta Braves ]
+: [ 2001-07-02, 2001-08-12,
+ 2001-08-14 ]
+EOY
+ )
+
+ # Complex key #2
+ assert_parse_only(
+ { [ 'New York Yankees', 'Atlanta Braves' ] =>
+ [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ),
+ Date.new( 2001, 8, 14 ) ],
+ [ 'Detroit Tigers', 'Chicago Cubs' ] =>
+ [ Date.new( 2001, 7, 23 ) ]
+ }, <<EOY
+?
+ - New York Yankees
+ - Atlanta Braves
+:
+ - 2001-07-02
+ - 2001-08-12
+ - 2001-08-14
+?
+ - Detroit Tigers
+ - Chicago Cubs
+:
+ - 2001-07-23
+EOY
+ )
+ end
+
+ def test_spec_sequence_key_shortcut
+ # Shortcut sequence map
+ assert_parse_only(
+ { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ),
+ 'bill-to' => 'Chris Dumars', 'product' =>
+ [ { 'item' => 'Super Hoop', 'quantity' => 1 },
+ { 'item' => 'Basketball', 'quantity' => 4 },
+ { 'item' => 'Big Shoes', 'quantity' => 1 } ] }, <<EOY
+invoice: 34843
+date : 2001-01-23
+bill-to: Chris Dumars
+product:
+ - item : Super Hoop
+ quantity: 1
+ - item : Basketball
+ quantity: 4
+ - item : Big Shoes
+ quantity: 1
+EOY
+ )
+ end
+
+ def test_spec_sequence_in_sequence_shortcut
+ # Seq-in-seq
+ assert_parse_only( [ [ [ 'one', 'two', 'three' ] ] ], <<EOY )
+- - - one
+ - two
+ - three
+EOY
+ end
+
+ def test_spec_sequence_shortcuts
+ # Sequence shortcuts combined
+ assert_parse_only(
+[
+ [
+ [ [ 'one' ] ],
+ [ 'two', 'three' ],
+ { 'four' => nil },
+ [ { 'five' => [ 'six' ] } ],
+ [ 'seven' ]
+ ],
+ [ 'eight', 'nine' ]
+], <<EOY )
+- - - - one
+ - - two
+ - three
+ - four:
+ - - five:
+ - six
+ - - seven
+- - eight
+ - nine
+EOY
+ end
+
+ def test_spec_single_literal
+ # Literal scalar block
+ assert_parse_only( [ "\\/|\\/|\n/ | |_\n" ], <<EOY )
+- |
+ \\/|\\/|
+ / | |_
+EOY
+ end
+
+ def test_spec_single_folded
+ # Folded scalar block
+ assert_parse_only(
+ [ "Mark McGwire's year was crippled by a knee injury.\n" ], <<EOY
+- >
+ Mark McGwire\'s
+ year was crippled
+ by a knee injury.
+EOY
+ )
+ end
+
+ def test_spec_preserve_indent
+ # Preserve indented spaces
+ assert_parse_only(
+ "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n", <<EOY
+--- >
+ Sammy Sosa completed another
+ fine season with great stats.
+
+ 63 Home Runs
+ 0.288 Batting Average
+
+ What a year!
+EOY
+ )
+ end
+
+ def test_spec_indentation_determines_scope
+ assert_parse_only(
+ { 'name' => 'Mark McGwire', 'accomplishment' => "Mark set a major league home run record in 1998.\n",
+ 'stats' => "65 Home Runs\n0.278 Batting Average\n" }, <<EOY
+name: Mark McGwire
+accomplishment: >
+ Mark set a major league
+ home run record in 1998.
+stats: |
+ 65 Home Runs
+ 0.278 Batting Average
+EOY
+ )
+ end
+
+ def test_spec_multiline_scalars
+ # Multiline flow scalars
+ assert_parse_only(
+ { 'plain' => 'This unquoted scalar spans many lines.',
+ 'quoted' => "So does this quoted scalar.\n" }, <<EOY
+plain: This unquoted
+ scalar spans
+ many lines.
+quoted: "\\
+ So does this quoted
+ scalar.\\n"
+EOY
+ )
+ end
+
+ def test_spec_type_int
+ assert_parse_only(
+ { 'canonical' => 12345, 'decimal' => 12345, 'octal' => '014'.oct, 'hexadecimal' => '0xC'.hex }, <<EOY
+canonical: 12345
+decimal: +12,345
+octal: 014
+hexadecimal: 0xC
+EOY
+ )
+ assert_parse_only(
+ { 'canonical' => 685230, 'decimal' => 685230, 'octal' => 02472256, 'hexadecimal' => 0x0A74AE, 'sexagesimal' => 685230 }, <<EOY)
+canonical: 685230
+decimal: +685,230
+octal: 02472256
+hexadecimal: 0x0A,74,AE
+sexagesimal: 190:20:30
+EOY
+ end
+
+ def test_spec_type_float
+ assert_parse_only(
+ { 'canonical' => 1230.15, 'exponential' => 1230.15, 'fixed' => 1230.15,
+ 'negative infinity' => -1.0/0.0 }, <<EOY)
+canonical: 1.23015e+3
+exponential: 12.3015e+02
+fixed: 1,230.15
+negative infinity: -.inf
+EOY
+ nan = YAML::load( <<EOY )
+not a number: .NaN
+EOY
+ assert( nan['not a number'].nan? )
+ end
+
+ def test_spec_type_misc
+ assert_parse_only(
+ { nil => nil, true => true, false => false, 'string' => '12345' }, <<EOY
+null: ~
+true: yes
+false: no
+string: '12345'
+EOY
+ )
+ end
+
+ def test_spec_complex_invoice
+ # Complex invoice type
+ id001 = { 'given' => 'Chris', 'family' => 'Dumars', 'address' =>
+ { 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak',
+ 'state' => 'MI', 'postal' => 48046 } }
+ assert_parse_only(
+ { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ),
+ 'bill-to' => id001, 'ship-to' => id001, 'product' =>
+ [ { 'sku' => 'BL394D', 'quantity' => 4,
+ 'description' => 'Basketball', 'price' => 450.00 },
+ { 'sku' => 'BL4438H', 'quantity' => 1,
+ 'description' => 'Super Hoop', 'price' => 2392.00 } ],
+ 'tax' => 251.42, 'total' => 4443.52,
+ 'comments' => "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" }, <<EOY
+invoice: 34843
+date : 2001-01-23
+bill-to: &id001
+ given : Chris
+ family : !str Dumars
+ address:
+ lines: |
+ 458 Walkman Dr.
+ Suite #292
+ city : Royal Oak
+ state : MI
+ postal : 48046
+ship-to: *id001
+product:
+ - !map
+ sku : BL394D
+ quantity : 4
+ description : Basketball
+ price : 450.00
+ - sku : BL4438H
+ quantity : 1
+ description : Super Hoop
+ price : 2392.00
+tax : 251.42
+total: 4443.52
+comments: >
+ Late afternoon is best.
+ Backup contact is Nancy
+ Billsmer @ 338-4338.
+EOY
+ )
+ end
+
+ def test_spec_log_file
+ doc_ct = 0
+ YAML::load_documents( <<EOY
+---
+Time: 2001-11-23 15:01:42 -05:00
+User: ed
+Warning: >
+ This is an error message
+ for the log file
+---
+Time: 2001-11-23 15:02:31 -05:00
+User: ed
+Warning: >
+ A slightly different error
+ message.
+---
+Date: 2001-11-23 15:03:17 -05:00
+User: ed
+Fatal: >
+ Unknown variable "bar"
+Stack:
+ - file: TopClass.py
+ line: 23
+ code: |
+ x = MoreObject("345\\n")
+ - file: MoreClass.py
+ line: 58
+ code: |-
+ foo = bar
+EOY
+ ) { |doc|
+ case doc_ct
+ when 0
+ assert_equal( doc, { 'Time' => mktime( 2001, 11, 23, 15, 01, 42, 00, "-05:00" ),
+ 'User' => 'ed', 'Warning' => "This is an error message for the log file\n" } )
+ when 1
+ assert_equal( doc, { 'Time' => mktime( 2001, 11, 23, 15, 02, 31, 00, "-05:00" ),
+ 'User' => 'ed', 'Warning' => "A slightly different error message.\n" } )
+ when 2
+ assert_equal( doc, { 'Date' => mktime( 2001, 11, 23, 15, 03, 17, 00, "-05:00" ),
+ 'User' => 'ed', 'Fatal' => "Unknown variable \"bar\"\n",
+ 'Stack' => [
+ { 'file' => 'TopClass.py', 'line' => 23, 'code' => "x = MoreObject(\"345\\n\")\n" },
+ { 'file' => 'MoreClass.py', 'line' => 58, 'code' => "foo = bar" } ] } )
+ end
+ doc_ct += 1
+ }
+ assert_equal( doc_ct, 3 )
+ end
+
+ def test_spec_root_fold
+ y = YAML::load( <<EOY
+--- >
+This YAML stream contains a single text value.
+The next stream is a log file - a sequence of
+log entries. Adding an entry to the log is a
+simple matter of appending it at the end.
+EOY
+ )
+ assert_equal( y, "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n" )
+ end
+
+ def test_spec_root_mapping
+ y = YAML::load( <<EOY
+# This stream is an example of a top-level mapping.
+invoice : 34843
+date : 2001-01-23
+total : 4443.52
+EOY
+ )
+ assert_equal( y, { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ), 'total' => 4443.52 } )
+ end
+
+ def test_spec_oneline_docs
+ doc_ct = 0
+ YAML::load_documents( <<EOY
+# The following is a sequence of three documents.
+# The first contains an empty mapping, the second
+# an empty sequence, and the last an empty string.
+--- {}
+--- [ ]
+--- ''
+EOY
+ ) { |doc|
+ case doc_ct
+ when 0
+ assert_equal( doc, {} )
+ when 1
+ assert_equal( doc, [] )
+ when 2
+ assert_equal( doc, '' )
+ end
+ doc_ct += 1
+ }
+ assert_equal( doc_ct, 3 )
+ end
+
+ def test_spec_domain_prefix
+ customer_proc = proc { |type, val|
+ if Hash === val
+ scheme, domain, type = type.split( ':', 3 )
+ val['type'] = "domain #{type}"
+ val
+ else
+ raise ArgumentError, "Not a Hash in domain.tld,2002/invoice: " + val.inspect
+ end
+ }
+ YAML.add_domain_type( "domain.tld,2002", 'invoice', &customer_proc )
+ YAML.add_domain_type( "domain.tld,2002", 'customer', &customer_proc )
+ assert_parse_only( { "invoice"=> { "customers"=> [ { "given"=>"Chris", "type"=>"domain customer", "family"=>"Dumars" } ], "type"=>"domain invoice" } }, <<EOY
+# 'http://domain.tld,2002/invoice' is some type family.
+invoice: !domain.tld,2002/^invoice
+ # 'seq' is shorthand for 'http://yaml.org/seq'.
+ # This does not effect '^customer' below
+ # because it is does not specify a prefix.
+ customers: !seq
+ # '^customer' is shorthand for the full
+ # notation 'http://domain.tld,2002/customer'.
+ - !^customer
+ given : Chris
+ family : Dumars
+EOY
+ )
+ end
+
+ def test_spec_throwaway
+ assert_parse_only(
+ {"this"=>"contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n"}, <<EOY
+### These are four throwaway comment ###
+
+### lines (the second line is empty). ###
+this: | # Comments may trail lines.
+ contains three lines of text.
+ The third one starts with a
+ # character. This isn't a comment.
+
+# These are three throwaway comment
+# lines (the first line is empty).
+EOY
+ )
+ end
+
+ def test_spec_force_implicit
+ # Force implicit
+ assert_parse_only(
+ { 'integer' => 12, 'also int' => 12, 'string' => '12' }, <<EOY
+integer: 12
+also int: ! "12"
+string: !str 12
+EOY
+ )
+ end
+
+ def test_spec_private_types
+ doc_ct = 0
+ YAML::parse_documents( <<EOY
+# Private types are per-document.
+---
+pool: !!ball
+ number: 8
+ color: black
+---
+bearing: !!ball
+ material: steel
+EOY
+ ) { |doc|
+ case doc_ct
+ when 0
+ assert_equal( doc['pool'].type_id, 'x-private:ball' )
+ assert_equal( doc['pool'].transform.value, { 'number' => 8, 'color' => 'black' } )
+ when 1
+ assert_equal( doc['bearing'].type_id, 'x-private:ball' )
+ assert_equal( doc['bearing'].transform.value, { 'material' => 'steel' } )
+ end
+ doc_ct += 1
+ }
+ assert_equal( doc_ct, 2 )
+ end
+
+ def test_spec_url_escaping
+ YAML.add_domain_type( "domain.tld,2002", "type0" ) { |type, val|
+ "ONE: #{val}"
+ }
+ YAML.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val|
+ "TWO: #{val}"
+ }
+ assert_parse_only(
+ { 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value' ] }, <<EOY
+same:
+ - !domain.tld,2002/type\\x30 value
+ - !domain.tld,2002/type0 value
+different: # As far as the YAML parser is concerned
+ - !domain.tld,2002/type%30 value
+EOY
+ )
+ end
+
+ def test_spec_override_anchor
+ # Override anchor
+ a001 = "The alias node below is a repeated use of this value.\n"
+ assert_parse_only(
+ { 'anchor' => 'This scalar has an anchor.', 'override' => a001, 'alias' => a001 }, <<EOY
+anchor : &A001 This scalar has an anchor.
+override : &A001 >
+ The alias node below is a
+ repeated use of this value.
+alias : *A001
+EOY
+ )
+ end
+
+ def test_spec_explicit_families
+ YAML.add_domain_type( "somewhere.com,2002", 'type' ) { |type, val|
+ "SOMEWHERE: #{val}"
+ }
+ assert_parse_only(
+ { 'not-date' => '2002-04-28', 'picture' => "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236i^\020' \202\n\001\000;", 'hmm' => "SOMEWHERE: family above is short for\nhttp://somewhere.com/type\n" }, <<EOY
+not-date: !str 2002-04-28
+picture: !binary |
+ R0lGODlhDAAMAIQAAP//9/X
+ 17unp5WZmZgAAAOfn515eXv
+ Pz7Y6OjuDg4J+fn5OTk6enp
+ 56enmleECcgggoBADs=
+
+hmm: !somewhere.com,2002/type |
+ family above is short for
+ http://somewhere.com/type
+EOY
+ )
+ end
+
+ def test_spec_application_family
+ # Testing the clarkevans.com graphs
+ YAML.add_domain_type( "clarkevans.com,2002", 'graph/shape' ) { |type, val|
+ if Array === val
+ val << "Shape Container"
+ val
+ else
+ raise ArgumentError, "Invalid graph of type #{val.class}: " + val.inspect
+ end
+ }
+ one_shape_proc = Proc.new { |type, val|
+ if Hash === val
+ type = type.split( /:/ )
+ val['TYPE'] = "Shape: #{type[2]}"
+ val
+ else
+ raise ArgumentError, "Invalid graph of type #{val.class}: " + val.inspect
+ end
+ }
+ YAML.add_domain_type( "clarkevans.com,2002", 'graph/circle', &one_shape_proc )
+ YAML.add_domain_type( "clarkevans.com,2002", 'graph/line', &one_shape_proc )
+ YAML.add_domain_type( "clarkevans.com,2002", 'graph/text', &one_shape_proc )
+ assert_parse_only(
+ [[{"radius"=>7, "center"=>{"x"=>73, "y"=>129}, "TYPE"=>"Shape: graph/circle"}, {"finish"=>{"x"=>89, "y"=>102}, "TYPE"=>"Shape: graph/line", "start"=>{"x"=>73, "y"=>129}}, {"TYPE"=>"Shape: graph/text", "value"=>"Pretty vector drawing.", "start"=>{"x"=>73, "y"=>129}, "color"=>16772795}, "Shape Container"]], <<EOY
+- !clarkevans.com,2002/graph/^shape
+ - !^circle
+ center: &ORIGIN {x: 73, y: 129}
+ radius: 7
+ - !^line # !clarkevans.com,2002/graph/line
+ start: *ORIGIN
+ finish: { x: 89, y: 102 }
+ - !^text
+ start: *ORIGIN
+ color: 0xFFEEBB
+ value: Pretty vector drawing.
+EOY
+ )
+ end
+
+ def test_spec_float_explicit
+ assert_parse_only(
+ [ 10.0, 10.0, 10.0, 10.0 ], <<EOY
+# All entries in the sequence
+# have the same type and value.
+- 10.0
+- !float 10
+- !yaml.org,2002/^float '10'
+- !yaml.org,2002/float "\\
+ 1\\
+ 0"
+EOY
+ )
+ end
+
+ def test_spec_builtin_seq
+ # Assortment of sequences
+ assert_parse_only(
+ { 'empty' => [], 'in-line' => [ 'one', 'two', 'three', 'four', 'five' ],
+ 'nested' => [ 'First item in top sequence', [ 'Subordinate sequence entry' ],
+ "A multi-line sequence entry\n", 'Sixth item in top sequence' ] }, <<EOY
+empty: []
+in-line: [ one, two, three # May span lines,
+ , four, # indentation is
+ five ] # mostly ignored.
+nested:
+ - First item in top sequence
+ -
+ - Subordinate sequence entry
+ - >
+ A multi-line
+ sequence entry
+ - Sixth item in top sequence
+EOY
+ )
+ end
+
+ def test_spec_builtin_map
+ # Assortment of mappings
+ assert_parse_only(
+ { 'empty' => {}, 'in-line' => { 'one' => 1, 'two' => 2 },
+ 'spanning' => { 'one' => 1, 'two' => 2 },
+ 'nested' => { 'first' => 'First entry', 'second' =>
+ { 'key' => 'Subordinate mapping' }, 'third' =>
+ [ 'Subordinate sequence', {}, 'Previous mapping is empty.',
+ { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' },
+ 'The previous entry is equal to the following one.',
+ { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' } ],
+ 12.0 => 'This key is a float.', "?\n" => 'This key had to be protected.',
+ "\a" => 'This key had to be escaped.',
+ "This is a multi-line folded key\n" => "Whose value is also multi-line.\n",
+ [ 'This key', 'is a sequence' ] => [ 'With a sequence value.' ] } }, <<EOY
+
+empty: {}
+in-line: { one: 1, two: 2 }
+spanning: { one: 1,
+ two: 2 }
+nested:
+ first : First entry
+ second:
+ key: Subordinate mapping
+ third:
+ - Subordinate sequence
+ - { }
+ - Previous mapping is empty.
+ - A key: value pair in a sequence.
+ A second: key:value pair.
+ - The previous entry is equal to the following one.
+ -
+ A key: value pair in a sequence.
+ A second: key:value pair.
+ !float 12 : This key is a float.
+ ? >
+ ?
+ : This key had to be protected.
+ "\\a" : This key had to be escaped.
+ ? >
+ This is a
+ multi-line
+ folded key
+ : >
+ Whose value is
+ also multi-line.
+ ?
+ - This key
+ - is a sequence
+ :
+ - With a sequence value.
+# The following parses correctly,
+# but Ruby 1.6.* fails the comparison!
+# ?
+# This: key
+# is a: mapping
+# :
+# with a: mapping value.
+EOY
+ )
+ end
+
+ def test_spec_builtin_literal_blocks
+ # Assortment of literal scalar blocks
+ assert_parse_only(
+ {"both are equal to"=>" This has no newline.", "is equal to"=>"The \\ ' \" characters may be\nfreely used. Leading white\n space is significant.\n\nLine breaks are significant.\nThus this value contains one\nempty line and ends with a\nsingle line break, but does\nnot start with one.\n", "also written as"=>" This has no newline.", "indented and chomped"=>" This has no newline.", "empty"=>"", "literal"=>"The \\ ' \" characters may be\nfreely used. Leading white\n space is significant.\n\nLine breaks are significant.\nThus this value contains one\nempty line and ends with a\nsingle line break, but does\nnot start with one.\n"}, <<EOY
+empty: |
+
+literal: |
+ The \\ ' " characters may be
+ freely used. Leading white
+ space is significant.
+
+ Line breaks are significant.
+ Thus this value contains one
+ empty line and ends with a
+ single line break, but does
+ not start with one.
+
+is equal to: "The \\ ' \\" characters may \\
+ be\\nfreely used. Leading white\\n space \\
+ is significant.\\n\\nLine breaks are \\
+ significant.\\nThus this value contains \\
+ one\\nempty line and ends with a\\nsingle \\
+ line break, but does\\nnot start with one.\\n"
+
+# Comments may follow a nested
+# scalar value. They must be
+# less indented.
+
+# Modifiers may be combined in any order.
+indented and chomped: |2-
+ This has no newline.
+
+also written as: |-2
+ This has no newline.
+
+both are equal to: " This has no newline."
+EOY
+ )
+
+ str1 = "This has one newline.\n"
+ str2 = "This has no newline."
+ str3 = "This has two newlines.\n\n"
+ assert_parse_only(
+ { 'clipped' => str1, 'same as "clipped" above' => str1,
+ 'stripped' => str2, 'same as "stripped" above' => str2,
+ 'kept' => str3, 'same as "kept" above' => str3 }, <<EOY
+clipped: |
+ This has one newline.
+
+same as "clipped" above: "This has one newline.\\n"
+
+stripped: |-
+ This has no newline.
+
+same as "stripped" above: "This has no newline."
+
+kept: |+
+ This has two newlines.
+
+same as "kept" above: "This has two newlines.\\n\\n"
+
+EOY
+ )
+ end
+
+ def test_spec_span_single_quote
+ assert_parse_only( {"third"=>"a single quote ' must be escaped.", "second"=>"! : \\ etc. can be used freely.", "is same as"=>"this contains six spaces\nand one line break", "empty"=>"", "span"=>"this contains six spaces\nand one line break"}, <<EOY
+empty: ''
+second: '! : \\ etc. can be used freely.'
+third: 'a single quote '' must be escaped.'
+span: 'this contains
+ six spaces
+
+ and one
+ line break'
+is same as: "this contains six spaces\\nand one line break"
+EOY
+ )
+ end
+
+ def test_spec_span_double_quote
+ assert_parse_only( {"is equal to"=>"this contains four spaces", "third"=>"a \" or a \\ must be escaped.", "second"=>"! : etc. can be used freely.", "empty"=>"", "fourth"=>"this value ends with an LF.\n", "span"=>"this contains four spaces"}, <<EOY
+empty: ""
+second: "! : etc. can be used freely."
+third: "a \\\" or a \\\\ must be escaped."
+fourth: "this value ends with an LF.\\n"
+span: "this contains
+ four \\
+ spaces"
+is equal to: "this contains four spaces"
+EOY
+ )
+ end
+
+ def test_spec_builtin_time
+ # Time
+ assert_parse_only(
+ { "space separated" => mktime( 2001, 12, 14, 21, 59, 43, ".10", "-05:00" ),
+ "canonical" => mktime( 2001, 12, 15, 2, 59, 43, ".10" ),
+ "date (noon UTC)" => Date.new( 2002, 12, 14),
+ "valid iso8601" => mktime( 2001, 12, 14, 21, 59, 43, ".10", "-05:00" ) }, <<EOY
+canonical: 2001-12-15T02:59:43.1Z
+valid iso8601: 2001-12-14t21:59:43.10-05:00
+space separated: 2001-12-14 21:59:43.10 -05:00
+date (noon UTC): 2002-12-14
+EOY
+ )
+ end
+
+ def test_spec_builtin_binary
+ arrow_gif = "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236iiiccc\243\243\243\204\204\204\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371!\376\016Made with GIMP\000,\000\000\000\000\f\000\f\000\000\005, \216\2010\236\343@\024\350i\020\304\321\212\010\034\317\200M$z\357\3770\205p\270\2601f\r\e\316\001\303\001\036\020' \202\n\001\000;"
+ assert_parse_only(
+ { 'canonical' => arrow_gif, 'base64' => arrow_gif,
+ 'description' => "The binary value above is a tiny arrow encoded as a gif image.\n" }, <<EOY
+canonical: !binary "\\
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOf\\
+ n515eXvPz7Y6OjuDg4J+fn5OTk6enp56enmlpaW\\
+ NjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++\\
+ f/++f/++f/++f/++f/++f/++f/++SH+Dk1hZGUg\\
+ d2l0aCBHSU1QACwAAAAADAAMAAAFLCAgjoEwnuN\\
+ AFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84Bww\\
+ EeECcgggoBADs="
+base64: !binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOf
+ n515eXvPz7Y6OjuDg4J+fn5OTk6enp56enmlpaW
+ NjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++
+ f/++f/++f/++f/++f/++f/++f/++SH+Dk1hZGUg
+ d2l0aCBHSU1QACwAAAAADAAMAAAFLCAgjoEwnuN
+ AFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84Bww
+ EeECcgggoBADs=
+description: >
+ The binary value above is a tiny arrow
+ encoded as a gif image.
+EOY
+ )
+ end
+ def test_ruby_regexp
+ # Test Ruby regular expressions
+ assert_to_yaml(
+ { 'simple' => /a.b/, 'complex' => %r'\A"((?:[^"]|\")+)"',
+ 'case-insensitive' => /George McFly/i }, <<EOY
+case-insensitive: !ruby/regexp "/George McFly/i"
+complex: !ruby/regexp "/\\\\A\\"((?:[^\\"]|\\\\\\")+)\\"/"
+simple: !ruby/regexp "/a.b/"
+EOY
+ )
+ end
+
+ #
+ # Test of Ranges
+ #
+ def test_ranges
+
+ # Simple numeric
+ assert_to_yaml( 1..3, <<EOY )
+--- !ruby/range 1..3
+EOY
+
+ # Simple alphabetic
+ assert_to_yaml( 'a'..'z', <<EOY )
+--- !ruby/range a..z
+EOY
+
+ # Float
+ assert_to_yaml( 10.5...30.3, <<EOY )
+--- !ruby/range 10.5...30.3
+EOY
+
+ end
+
+ def test_ruby_struct
+ # Ruby structures
+ book_struct = Struct::new( "BookStruct", :author, :title, :year, :isbn )
+ assert_to_yaml(
+ [ book_struct.new( "Yukihiro Matsumoto", "Ruby in a Nutshell", 2002, "0-596-00214-9" ),
+ book_struct.new( [ 'Dave Thomas', 'Andy Hunt' ], "The Pickaxe", 2002,
+ book_struct.new( "This should be the ISBN", "but I have another struct here", 2002, "None" )
+ ) ], <<EOY
+- !ruby/struct:BookStruct
+ author: Yukihiro Matsumoto
+ title: Ruby in a Nutshell
+ year: 2002
+ isbn: 0-596-00214-9
+- !ruby/struct:BookStruct
+ author:
+ - Dave Thomas
+ - Andy Hunt
+ title: The Pickaxe
+ year: 2002
+ isbn: !ruby/struct:BookStruct
+ author: This should be the ISBN
+ title: but I have another struct here
+ year: 2002
+ isbn: None
+EOY
+ )
+
+ assert_to_yaml( YAML_Tests::StructTest.new( 123 ), <<EOY )
+--- !ruby/struct:YAML_Tests::StructTest
+c: 123
+EOY
+
+ end
+
+ def test_emitting_indicators
+ assert_to_yaml( "Hi, from Object 1. You passed: please, pretty please", <<EOY
+--- "Hi, from Object 1. You passed: please, pretty please"
+EOY
+ )
+ end
+
+ #
+ # Test the YAML::Stream class -- INACTIVE at the moment
+ #
+ def test_document
+ y = YAML::Stream.new( :Indent => 2, :UseVersion => 0 )
+ y.add(
+ { 'hi' => 'hello', 'map' =>
+ { 'good' => 'two' },
+ 'time' => Time.now,
+ 'try' => /^po(.*)$/,
+ 'bye' => 'goodbye'
+ }
+ )
+ y.add( { 'po' => 'nil', 'oper' => 90 } )
+ y.add( { 'hi' => 'wow!', 'bye' => 'wow!' } )
+ y.add( { [ 'Red Socks', 'Boston' ] => [ 'One', 'Two', 'Three' ] } )
+ y.add( [ true, false, false ] )
+ end
+
+ #
+ # Test YPath choices parsing
+ #
+ def test_ypath_parsing
+ assert_path_segments( "/*/((one|three)/name|place)|//place",
+ [ ["*", "one", "name"],
+ ["*", "three", "name"],
+ ["*", "place"],
+ ["/", "place"] ]
+ )
+ end
+
+ #
+ # Tests from Tanaka Akira on [ruby-core]
+ #
+ def test_akira
+
+ # Commas in plain scalars [ruby-core:1066]
+ assert_to_yaml(
+ {"A"=>"A,","B"=>"B"}, <<EOY
+A: "A,"
+B: B
+EOY
+ )
+
+ # Double-quoted keys [ruby-core:1069]
+ assert_to_yaml(
+ {"1"=>2, "2"=>3}, <<EOY
+'1': 2
+"2": 3
+EOY
+ )
+
+ # Anchored mapping [ruby-core:1071]
+ assert_to_yaml(
+ [{"a"=>"b"}] * 2, <<EOY
+- &id001
+ a: b
+- *id001
+EOY
+ )
+
+ # Stress test [ruby-core:1071]
+ # a = []; 1000.times { a << {"a"=>"b", "c"=>"d"} }
+ # YAML::load( a.to_yaml )
+
+ end
+
+ #
+ # Test Time.now cycle
+ #
+ def test_time_now_cycle
+ #
+ # From Minero Aoki [ruby-core:2305]
+ #
+ require 'yaml'
+ t = Time.now
+ 5.times do
+ assert_cycle(t)
+ end
+ end
+
+ #
+ # Test Range cycle
+ #
+ def test_range_cycle
+ #
+ # From Minero Aoki [ruby-core:02306]
+ #
+ assert_cycle("a".."z")
+
+ #
+ # From Nobu Nakada [ruby-core:02311]
+ #
+ assert_cycle(0..1)
+ assert_cycle(1.0e20 .. 2.0e20)
+ assert_cycle("0".."1")
+ assert_cycle(".."..."...")
+ assert_cycle(".rb"..".pl")
+ assert_cycle(".rb"...".pl")
+ assert_cycle('"'...".")
+ assert_cycle("'"...".")
+ end
+
+ #
+ # Circular references
+ #
+ def test_circular_references
+ a = []; a[0] = a; a[1] = a
+ inspect_str = "[[...], [...]]"
+ assert_equal( inspect_str, YAML::load( a.to_yaml ).inspect )
+ end
+
+ #
+ # Test Symbol cycle
+ #
+ def test_symbol_cycle
+ #
+ # From Aaron Schrab [ruby-Bugs:2535]
+ #
+ assert_cycle(:"^foo")
+ end
+
+ #
+ # Test Numeric cycle
+ #
+ class NumericTest < Numeric
+ def initialize(value)
+ @value = value
+ end
+ def ==(other)
+ @value == other.instance_eval{ @value }
+ end
+ end
+ def test_numeric_cycle
+ assert_cycle(1) # Fixnum
+ assert_cycle(111111111111111111111111111111111) # Bignum
+ assert_cycle(NumericTest.new(3)) # Subclass of Numeric
+ end
+
+ #
+ # Test empty map/seq in map cycle
+ #
+ def test_empty_map_key
+ #
+ # empty seq as key
+ #
+ o = YAML.load({[]=>""}.to_yaml)
+ assert_equal(Hash, o.class)
+ assert_equal([[]], o.keys)
+
+ #
+ # empty map as key
+ #
+ o = YAML.load({{}=>""}.to_yaml)
+ assert_equal(Hash, o.class)
+ assert_equal([{}], o.keys)
+ end
+
+end
+
+if $0 == __FILE__
+ suite = Test::Unit::TestSuite.new('YAML')
+ ObjectSpace.each_object(Class) do |klass|
+ suite << klass.suite if (Test::Unit::TestCase > klass)
+ end
+ require 'test/unit/ui/console/testrunner'
+ Test::Unit::UI::Console::TestRunner.run(suite).passed?
+end
diff --git a/ruby_1_8_6/test/zlib/test_zlib.rb b/ruby_1_8_6/test/zlib/test_zlib.rb
new file mode 100644
index 0000000000..54706099d9
--- /dev/null
+++ b/ruby_1_8_6/test/zlib/test_zlib.rb
@@ -0,0 +1,57 @@
+require 'test/unit/testsuite'
+require 'test/unit/testcase'
+require 'stringio'
+
+begin
+ require 'zlib'
+rescue LoadError
+end
+
+if defined? Zlib
+ class TestZlibGzipReader < Test::Unit::TestCase
+ D0 = "\037\213\010\000S`\017A\000\003\003\000\000\000\000\000\000\000\000\000"
+ def test_read0
+ assert_equal("", Zlib::GzipReader.new(StringIO.new(D0)).read(0))
+ end
+
+ def test_ungetc # [ruby-dev:24060]
+ s = ""
+ w = Zlib::GzipWriter.new(StringIO.new(s))
+ w << (1...1000).to_a.inspect
+ w.close
+ r = Zlib::GzipReader.new(StringIO.new(s))
+ r.read(100)
+ r.ungetc ?a
+ assert_nothing_raised {
+ r.read(100)
+ r.read
+ r.close
+ }
+ end
+
+ def test_ungetc_paragraph # [ruby-dev:24065]
+ s = ""
+ w = Zlib::GzipWriter.new(StringIO.new(s))
+ w << "abc"
+ w.close
+ r = Zlib::GzipReader.new(StringIO.new(s))
+ r.ungetc ?\n
+ assert_equal("abc", r.gets(""))
+ assert_nothing_raised {
+ r.read
+ r.close
+ }
+ end
+ end
+
+ class TestZlibGzipWriter < Test::Unit::TestCase
+ def test_invalid_new
+ # [ruby-dev:23228]
+ assert_raise(NoMethodError) { Zlib::GzipWriter.new(nil).close }
+ # [ruby-dev:23344]
+ assert_raise(NoMethodError) { Zlib::GzipWriter.new(true).close }
+ assert_raise(NoMethodError) { Zlib::GzipWriter.new(0).close }
+ assert_raise(NoMethodError) { Zlib::GzipWriter.new(:hoge).close }
+ end
+ end
+end