Merge: model: is_accessor
authorJean Privat <jean@pryen.org>
Tue, 10 Oct 2017 16:52:03 +0000 (12:52 -0400)
committerJean Privat <jean@pryen.org>
Tue, 10 Oct 2017 16:52:03 +0000 (12:52 -0400)
Add a way to associate attributes and their getters/setters.

This will be useful for filtering things and groupings properties together.

Pull-Request: #2559

115 files changed:
.gitignore
contrib/nitrpg/src/test_achievements.nit
contrib/nitrpg/src/test_events.nit
contrib/nitrpg/src/test_game.nit
contrib/nitrpg/src/test_helper.nit
contrib/nitrpg/src/test_listener.nit
contrib/nitrpg/src/test_statistics.nit
lib/bitmap/test_bitmap.nit
lib/core/core.nit
lib/core/text/test_abstract_text.nit
lib/fca/fca.nit [new file with mode: 0644]
lib/github/test_github_curl.nit
lib/gmp/test_native_gmp.nit
lib/markdown/test_markdown.nit
lib/markdown/test_wikilinks.nit
lib/nlp/README.md
lib/nlp/nlp.nit
lib/nlp/vsm.nit [deleted file]
lib/popcorn/examples/angular/tests/test_example_angular.nit
lib/popcorn/examples/handlers/tests/test_example_post_handler.nit
lib/popcorn/examples/handlers/tests/test_example_query_string.nit
lib/popcorn/examples/hello_world/tests/test_example_hello.nit
lib/popcorn/examples/middlewares/tests/test_example_advanced_logger.nit
lib/popcorn/examples/middlewares/tests/test_example_html_error_handler.nit
lib/popcorn/examples/middlewares/tests/test_example_simple_error_handler.nit
lib/popcorn/examples/middlewares/tests/test_example_simple_logger.nit
lib/popcorn/examples/routing/tests/test_example_glob_route.nit
lib/popcorn/examples/routing/tests/test_example_param_route.nit
lib/popcorn/examples/routing/tests/test_example_router.nit
lib/popcorn/examples/sessions/tests/test_example_session.nit
lib/popcorn/examples/static_files/tests/test_example_static.nit
lib/popcorn/examples/static_files/tests/test_example_static_default.nit
lib/popcorn/examples/static_files/tests/test_example_static_multiple.nit
lib/popcorn/examples/templates/tests/test_example_templates.nit
lib/popcorn/pop_tests.nit
lib/popcorn/tests/test_pop_routes.nit
lib/popcorn/tests/test_popcorn.nit
lib/sax/helpers/test_attributes_impl.nit
lib/sax/helpers/test_namespace_support.nit
lib/saxophonit/test_saxophonit.nit
lib/saxophonit/test_testing.nit
lib/saxophonit/testing.nit
lib/template/test_macro.nit
lib/test_suite.ini [deleted file]
lib/test_suite.nit [deleted file]
lib/vsm/README.md [new file with mode: 0644]
lib/vsm/examples/example_vsm.nit [new file with mode: 0644]
lib/vsm/vsm.nit [new file with mode: 0644]
share/man/nitunit.md
share/nitweb/directives/contributor-list.html [deleted file]
share/nitweb/directives/entity/card.html
share/nitweb/directives/search/card.html [deleted file]
share/nitweb/directives/search/field.html [deleted file]
share/nitweb/directives/ui/pagination.html [new file with mode: 0644]
share/nitweb/directives/ui/search-field.html
share/nitweb/index.html
share/nitweb/javascripts/catalog.js [new file with mode: 0644]
share/nitweb/javascripts/entities.js
share/nitweb/javascripts/grades.js
share/nitweb/javascripts/index.js [deleted file]
share/nitweb/javascripts/nitweb.js
share/nitweb/javascripts/ui.js
share/nitweb/stylesheets/cards.css
share/nitweb/stylesheets/nitweb.css
share/nitweb/stylesheets/search.css
share/nitweb/views/catalog/by_tags.html [deleted file]
share/nitweb/views/catalog/highlighted.html [deleted file]
share/nitweb/views/catalog/index.html
share/nitweb/views/catalog/most_required.html [deleted file]
share/nitweb/views/catalog/person.html [new file with mode: 0644]
share/nitweb/views/catalog/tag.html [new file with mode: 0644]
share/nitweb/views/doc/doc.html
share/nitweb/views/doc/entity.html
share/nitweb/views/doc/grades.html [new file with mode: 0644]
share/nitweb/views/search.html [new file with mode: 0644]
src/catalog.nit
src/compiler/test_coloring.nit
src/doc/doc_commands.nit
src/doc/doc_down.nit
src/doc/doc_phases/doc_console.nit
src/doc/doc_phases/doc_readme.nit
src/doc/test_doc_commands.nit [new file with mode: 0644]
src/frontend/no_warning.nit
src/frontend/parse_annotations.nit
src/loader.nit
src/model/mmodule.nit
src/model/model.nit
src/model/model_base.nit
src/model/model_views.nit
src/model/model_visitor.nit
src/model/test_model_json.nit
src/nitcatalog.nit
src/testing/README.md
src/testing/testing_gen.nit
src/testing/testing_suite.nit
src/web/api_catalog.nit
src/web/api_docdown.nit
src/web/api_model.nit
src/web/web_base.nit
tests/sav/example_vsm.res [new file with mode: 0644]
tests/sav/nitunit_args1.res
tests/sav/nitunit_args11.res
tests/sav/nitunit_args12.res
tests/sav/nitunit_args2.res
tests/sav/nitunit_args3.res
tests/sav/nitunit_args9.res
tests/sav/syntax_annotations3.res
tests/test_nitunit4/test_bad_comp.nit
tests/test_nitunit4/test_bad_comp2.nit
tests/test_nitunit4/test_nitunit4.nit
tests/test_nitunit4/test_nitunit4_base.nit
tests/test_nitunit5.nit
tests/test_nitunit6.nit
tests/test_nitunit7.nit
tests/test_test_nitunit.nit

index a739d3f..a37d586 100644 (file)
@@ -1,6 +1,8 @@
 *.bak
 *.swp
 *.swo
+*.swn
+*.swm
 *~
 .project
 EIFGENs
index c210c60..41d9dd1 100644 (file)
 # limitations under the License.
 
 # Test module for `achievements.nit`
-module test_achievements is test_suite
+module test_achievements is test
 
 import test_helper
 import achievements
 
 class TestGame
        super NitrpgTestHelper
+       test
 
-       fun test_add_achievement do
+       fun test_add_achievement is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var a1 = new Achievement(game, "test_id1", "test_name", "test_desc", 15)
@@ -33,7 +34,7 @@ class TestGame
                assert game.load_achievements.length == 2
        end
 
-       fun test_load_achievement do
+       fun test_load_achievement is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var a1 = new Achievement(game, "test_id1", "test_name", "test_desc", 15)
@@ -43,7 +44,7 @@ class TestGame
                assert game.load_achievement(a2.id) == null
        end
 
-       fun test_load_achievements do
+       fun test_load_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var a1 = new Achievement(game, "test_id1", "test_name", "test_desc", 15)
@@ -61,8 +62,9 @@ end
 
 class TestPlayer
        super NitrpgTestHelper
+       test
 
-       fun test_add_achievement do
+       fun test_add_achievement is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var player1 = new Player(game, "Morriar")
@@ -73,7 +75,7 @@ class TestPlayer
                assert player1.load_achievements.length == 2
        end
 
-       fun test_load_achievement do
+       fun test_load_achievement is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var player1 = new Player(game, "Morriar")
@@ -88,7 +90,7 @@ class TestPlayer
                assert player2.load_achievement(a1.id) == null
        end
 
-       fun test_load_achievements do
+       fun test_load_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var player1 = new Player(game, "Morriar")
@@ -108,8 +110,9 @@ end
 
 class TestAchievement
        super NitrpgTestHelper
+       test
 
-       fun test_init do
+       fun test_init is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var a = new Achievement(game, "test_id", "test_name", "test_desc", 15)
@@ -119,7 +122,7 @@ class TestAchievement
                assert a.reward == 15
        end
 
-       fun test_init_from_json do
+       fun test_init_from_json is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var json = """{
index 640e8dc..efe24cf 100644 (file)
 # limitations under the License.
 
 # Test module for `events.nit`
-module test_events is test_suite
+module test_events is test
 
 import test_helper
 import events
 
 class TestGame
        super NitrpgTestHelper
+       test
 
-       fun test_add_event do
+       fun test_add_event is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var event1 = new GameEvent(game, "test_kind", new JsonObject)
@@ -33,7 +34,7 @@ class TestGame
                assert game.load_events.length == 2
        end
 
-       fun test_load_event do
+       fun test_load_event is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var event1 = new GameEvent(game, "test_kind", new JsonObject)
@@ -43,7 +44,7 @@ class TestGame
                assert game.load_event(event2.internal_id) == null
        end
 
-       fun test_load_events do
+       fun test_load_events is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var event1 = new GameEvent(game, "test_kind", new JsonObject)
@@ -61,8 +62,9 @@ end
 
 class TestPlayer
        super NitrpgTestHelper
+       test
 
-       fun test_add_event do
+       fun test_add_event is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var player1 = new Player(game, "Morriar")
@@ -75,7 +77,7 @@ class TestPlayer
                assert player2.load_events.length == 0
        end
 
-       fun test_load_event do
+       fun test_load_event is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var player1 = new Player(game, "Morriar")
@@ -90,7 +92,7 @@ class TestPlayer
                assert player2.load_event(event1.internal_id) == null
        end
 
-       fun test_load_events do
+       fun test_load_events is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var player1 = new Player(game, "Morriar")
@@ -110,15 +112,16 @@ end
 
 class TestGameEvent
        super NitrpgTestHelper
+       test
 
-       fun test_init do
+       fun test_init is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var event = new GameEvent(game, "test_kind", new JsonObject)
                assert event.to_json_object["kind"] == "test_kind"
        end
 
-       fun test_init_from_json do
+       fun test_init_from_json is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var json = """{
index 25ddcad..c2aa677 100644 (file)
 # limitations under the License.
 
 # Test module for `game.nit`.
-module test_game is test_suite
+module test_game is test
 
 import test_helper
 
 class TestGame
        super NitrpgTestHelper
+       test
 
-       fun test_add_player do
+       fun test_add_player is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var users = ["Morriar", "xymus"]
@@ -36,7 +37,7 @@ class TestGame
                end
        end
 
-       fun test_load_player do
+       fun test_load_player is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var ogame = load_game("Morriar/nit", db)
@@ -52,7 +53,7 @@ class TestGame
                assert ogame.load_player("Morriar") == null
        end
 
-       fun test_load_players do
+       fun test_load_players is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var ogame = load_game("Morriar/nit", db)
@@ -72,8 +73,9 @@ end
 
 class TestPlayer
        super NitrpgTestHelper
+       test
 
-       fun test_init do
+       fun test_init is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var player = new Player(game, "Morriar")
@@ -82,7 +84,7 @@ class TestPlayer
                assert player.nitcoins == 0
        end
 
-       fun test_init_from_json do
+       fun test_init_from_json is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var json = """{"name": "Morriar", "nitcoins": 10}""".parse_json
@@ -92,7 +94,7 @@ class TestPlayer
                assert player.nitcoins == 10
        end
 
-       fun test_save do
+       fun test_save is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var json = """{"name": "Morriar", "nitcoins": 10}""".parse_json.as(JsonObject)
@@ -101,7 +103,7 @@ class TestPlayer
                assert game.db.collection("players").find(json) != null
        end
 
-       fun test_game_add_player do
+       fun test_game_add_player is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                game.add_player(game.api.load_user("Morriar").as(not null))
@@ -109,7 +111,7 @@ class TestPlayer
                assert game.db.collection("players").find(json) != null
        end
 
-       fun test_game_load_player do
+       fun test_game_load_player is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var json = """{"name": "Morriar", "nitcoins": 10}""".parse_json.as(JsonObject)
@@ -123,8 +125,9 @@ end
 
 class TestUser
        super NitrpgTestHelper
+       test
 
-       fun test_player do
+       fun test_player is test do
                var db = gen_test_db
                var api = new GithubAPI(get_github_oauth)
                var game = load_game("privat/nit", db)
index ecdc358..919ccfc 100644 (file)
 # Test tools for NitRPG.
 module test_helper
 
-import test_suite
 import game
 import github::cache
 
 # Used to factorize test treatments.
 abstract class NitrpgTestHelper
-       super TestSuite
 
        # Github API client
        var api: GithubAPI do
@@ -70,5 +68,6 @@ abstract class NitrpgTestHelper
                db.drop
        end
 
-       redef fun after_test do drop_test_db
+       # Drop the databse after each test
+       fun after_test is after do drop_test_db
 end
index 9cfa059..d70f3aa 100644 (file)
@@ -15,7 +15,7 @@
 # limitations under the License.
 
 # Test module for `listener.nit`
-module test_listener is test_suite
+module test_listener is test
 
 import test_helper
 import reactors
@@ -24,6 +24,7 @@ import events_generator
 
 private class DummyListener
        super NitrpgTestHelper
+       test
 
        var reactors = new Array[GameReactor]
 
@@ -39,12 +40,13 @@ end
 
 class TestListener
        super NitrpgTestHelper
+       test
 
        var generator = new EventsGenerator(api)
 
        var repo: Repo is lazy do return load_repo("Morriar/nit")
 
-       fun test_game_issue_stats do
+       fun test_game_issue_stats is test do
                var db = gen_test_db
                var l = new DummyListener
                l.add_reactor(new StatisticsReactor)
@@ -66,7 +68,7 @@ class TestListener
                assert game.stats.overall["issues_open"] == 1
        end
 
-       fun test_player_issue_stats do
+       fun test_player_issue_stats is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -89,7 +91,7 @@ class TestListener
                assert player.stats.overall["issues_open"] == 1
        end
 
-       fun test_game_pr_stats do
+       fun test_game_pr_stats is test do
                var db = gen_test_db
                var l = new DummyListener
                l.add_reactor(new StatisticsReactor)
@@ -121,7 +123,7 @@ class TestListener
                assert game.stats.overall["commits"] == 2
        end
 
-       fun test_game_issue_comment_stats do
+       fun test_game_issue_comment_stats is test do
                var db = gen_test_db
                var l = new DummyListener
                l.add_reactor(new StatisticsReactor)
@@ -143,7 +145,7 @@ class TestListener
                assert game.stats.overall["reviews"] == 1
        end
 
-       fun test_player_pull_reactor do
+       fun test_player_pull_reactor is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -168,7 +170,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 12
        end
 
-       fun test_player_review_reactor do
+       fun test_player_review_reactor is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -211,7 +213,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 4
        end
 
-       fun test_X_issues_achievements do
+       fun test_X_issues_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -234,7 +236,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 1110
        end
 
-       fun test_X_pulls_achievements do
+       fun test_X_pulls_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -257,7 +259,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 1110
        end
 
-       fun test_X_commits_achievements do
+       fun test_X_commits_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -283,7 +285,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 11110
        end
 
-       fun test_X_comments_achievements do
+       fun test_X_comments_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -308,7 +310,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 1110
        end
 
-    fun test_issues_achievements do
+    fun test_issues_achievements is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
@@ -325,7 +327,7 @@ class TestListener
                assert player.stats.overall["nitcoins"] == 20
        end
 
-       fun test_comments_reactor do
+       fun test_comments_reactor is test do
                var db = gen_test_db
                var game = load_game("Morriar/nit", db)
                var l = new DummyListener
index 766726c..9bdf8fa 100644 (file)
 # limitations under the License.
 
 # Test module for `stats.nit`
-module test_statistics is test_suite
+module test_statistics is test
 
 import test_helper
 import statistics
 
 class TestGame
        super NitrpgTestHelper
+       test
 
-       fun test_game_stats do
+       fun test_game_stats is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var stats = game.stats
@@ -40,8 +41,9 @@ end
 
 class TestPlayer
        super NitrpgTestHelper
+       test
 
-       fun test_player_stats do
+       fun test_player_stats is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var player = new Player(game, "Morriar")
@@ -59,8 +61,9 @@ end
 
 class TestGameStats
        super NitrpgTestHelper
+       test
 
-       fun test_init_from_json do
+       fun test_init_from_json is test do
                var db = gen_test_db
                var game = load_game("privat/nit", db)
                var owner = new Player(game, "Morriar")
index 4475689..2f76da6 100644 (file)
 #
 #
 # A module for testing the classes in the bitmap module
-module test_bitmap is test_suite
+module test_bitmap is test
 
 import bitmap
-import test_suite
 
 class TestBitmap
-       super TestSuite
+       test
 
-       fun test_grayscale do
+       fun test_grayscale is test do
                var bitmap = new Bitmap.with_size(400, 300)
                for y in [0..300] do
                        for x in [0..200] do bitmap.set_pixel(x, y, 0x0077AAAA)
index 97a4271..6eaff6e 100644 (file)
 
 # Standard classes and methods used by default by Nit programs and libraries.
 # This module is implicitly imported by every module.
-module core
+module core is
+       new_annotation test
+       new_annotation before
+       new_annotation before_all
+       new_annotation after
+       new_annotation after_all
+end
 
 import posix
 import environ
index af7dc00..ec9bda6 100644 (file)
@@ -8,21 +8,20 @@
 # You  are  allowed  to  redistribute it and sell it, alone or is a part of
 # another product.
 
-module test_abstract_text is test_suite
+module test_abstract_text is test
 
-import test_suite
 import text
 intrude import ropes
 
 class TestText
-       super TestSuite
+       test
 
        private var factories: Collection[TextFactory] = [
                new ConcatFactory,
                new FlatBufferFactory
        : TextFactory]
 
-       fun test_escape_to_c do
+       fun test_escape_to_c is test do
                for f in factories do
                        assert f.create("abAB12<>&").escape_to_c       == "abAB12<>&"
                        assert f.create("\n\"'\\").escape_to_c         == "\\n\\\"\\'\\\\"
diff --git a/lib/fca/fca.nit b/lib/fca/fca.nit
new file mode 100644 (file)
index 0000000..b3b487a
--- /dev/null
@@ -0,0 +1,253 @@
+# This file is part of NIT (http://www.nitlanguage.org).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Formal Concept Analysis
+#
+# Formal concept analysis (FCA) is a principled way of deriving a concept hierarchy
+# or formal ontology from a collection of objects and their properties.
+# This means deriving implicit relationships between objects regarding their
+# attributes.
+#
+# Each concept in the hierarchy represents the set of objects sharing the same
+# values for a certain set of properties; and each sub-concept in the hierarchy
+# contains a subset of the objects in the concepts above it.
+#
+# Formal concept analysis finds practical application in fields including data
+# mining, text mining, machine learning or semantic web.
+#
+# ## Building a FormalContext
+#
+# We use the example from https://en.wikipedia.org/wiki/Formal_concept_analysis:
+#
+# ~~~
+# var fc = new FormalContext[Int, String]
+# fc.set_object_attributes(1, ["odd", "square"])
+# fc.set_object_attributes(2, ["even", "prime"])
+# fc.set_object_attributes(3, ["odd", "prime"])
+# fc.set_object_attributes(4, ["even", "composite", "square"])
+# fc.set_object_attributes(5, ["odd", "prime"])
+# fc.set_object_attributes(6, ["even", "composite"])
+# fc.set_object_attributes(7, ["odd", "prime"])
+# fc.set_object_attributes(8, ["even", "composite"])
+# fc.set_object_attributes(9, ["odd", "square", "composite"])
+# fc.set_object_attributes(10, ["even", "composite"])
+# ~~~
+#
+# ## Computing the set of FormalConcept
+#
+# ~~~
+# var concepts = fc.formal_concepts
+# for concept in concepts do
+#      print concept
+# end
+# ~~~
+#
+# ## Visualizing formal concept with ConceptLattice
+#
+# ~~~nitish
+# var cl = new ConceptLattice[Int, String].from_concepts(concepts)
+# cl.show_dot
+# ~~~
+module fca
+
+import poset
+
+# Formal Context
+#
+# A formal context is a triple *K = (G, M, I)*, where *G* is a set of `objects`,
+# *M* is a set of `attributes`, and *I âŠ† G Ã— M* is a binary relation called incidence
+# that expresses which objects have which attributes (`objects_attributes`).
+#
+# Predicate *gIm* designates object *g*'s having attribute *m*.
+# For a subset *A âŠ† G* of objects and a subset *B âŠ† M* of attributes, one defines
+# two derivation operators as follows:
+#
+# * *A' = {m âˆˆ M | âˆ€ g âˆˆ A, gIm}*, and dually
+# * *B' = {g âˆˆ G | âˆ€ m âˆˆ B, gIm}*.
+class FormalContext[O: Object, A: Object]
+
+       # Objects in the context
+       var objects = new HashSet[O]
+
+       # Attributes considered to build concepts
+       var attributes = new HashSet[A]
+
+       # Association between objects and attributes
+       var objects_attributes = new HashMap[O, Set[A]]
+
+       # Associate a set of `attributes` to `object`
+       fun set_object_attributes(object: O, attributes: Collection[A]) do
+               for attribute in attributes do
+                       set_object_attribute(object, attribute)
+               end
+       end
+
+       # Associate an `attribute` to `object`
+       fun set_object_attribute(object: O, attribute: A) do
+               attributes.add attribute
+               objects.add object
+               if not objects_attributes.has_key(object) then
+                       objects_attributes[object] = new HashSet[A]
+               end
+               objects_attributes[object].add attribute
+       end
+
+       # Derive the set of formal concepts from the objects and attributes
+       fun formal_concepts: Set[FormalConcept[O, A]] do
+               # black magic!
+
+               var concepts = new HashSet[FormalConcept[O, A]]
+
+               var extentsByAttr = new HashMap[Set[A], Set[O]]
+               for attribute in attributes do
+                       var ka = new HashSet[A].from([attribute])
+                       extentsByAttr[ka] = new HashSet[O]
+                       for object in objects do
+                               if not objects_attributes[object].has(attribute) then continue
+                               extentsByAttr[ka].add(object)
+                       end
+               end
+
+               var nextents = new HashMap[Set[A], Set[O]]
+               for k1, v1 in extentsByAttr do
+                       for k2, v2 in extentsByAttr do
+                               if k1 == k2 then continue
+                               var n = v1.intersection(v2)
+                               if extentsByAttr.values.has(n) then continue
+                               var ka = k1.union(k2)
+                               nextents[ka] = n
+                       end
+               end
+               extentsByAttr.add_all nextents
+
+               var contained = true
+               for k1, v1 in extentsByAttr do
+                       if not contained then break
+                       for k2, v2 in extentsByAttr do
+                               if k1 == k2 then continue
+                               var n = v1.intersection(v2)
+                               if extentsByAttr.values.has(n) then continue
+                               contained = false
+                               break
+                       end
+               end
+
+               if contained then
+                       extentsByAttr[new HashSet[A]] = new HashSet[O].from(objects)
+               end
+
+               var extents = new HashSet[Set[O]]
+               for objects in extentsByAttr.values do
+                       extents.add objects
+               end
+
+               for extent in extents do
+                       var intents: Set[A] = new HashSet[A]
+                       var count = 0
+                       var cl = new FormalConcept[O, A]
+                       if extent.is_empty then
+                               intents.add_all(attributes)
+                       else
+                               for object in objects do
+                                       if not extent.has(object) then continue
+                                       var prev = objects_attributes[object]
+                                       if count > 0 then
+                                               intents = prev.intersection(intents)
+                                       else
+                                               intents = prev
+                                       end
+                                       count += 1
+                                       cl.objects.add(object)
+                               end
+                       end
+                       cl.attributes.add_all intents
+                       concepts.add cl
+               end
+
+               return concepts
+       end
+end
+
+# Formal Concept
+#
+# A pair *(A,B)* is a formal concept of a FormalContext *(G, M, I)* provided that:
+#
+# * *A âŠ† G*,
+# * *B âŠ† M*,
+# * *A′ = B*, and
+# * *B′ = A*.
+#
+# Equivalently and more intuitively, *(A,B)* is a formal concept precisely when:
+#
+# * every object in *A* has every attribute in *B*,
+# * for every object in *G* that is not in *A*, there is some attribute in *B* that
+#   the object does not have,
+# * for every attribute in *M* that is not in *B*, there is some object in *A*
+#   that does not have that attribute.
+class FormalConcept[O: Object, A: Object]
+
+       # Concept attributes
+       var attributes = new HashSet[A]
+
+       # Concept objects
+       var objects = new HashSet[O]
+
+       # Is `self` a subconcept of `super_concept`?
+       #
+       # A concept C1 is a subconcept of C2 if C2 has all the objects of C1.
+       fun is_subconcept(super_concept: FormalConcept[O, A]): Bool do
+               if self == super_concept then return false
+               if objects.length > super_concept.objects.length then return false
+               return super_concept.objects.has_all(objects)
+       end
+
+       redef fun to_s do return "{attributes}\n{objects}"
+end
+
+# Concept Lattice
+#
+# Formal concepts are partially ordered with regard to inclusion of their extents
+# or (which is equivalent) inverse inclusion of their intent.
+class ConceptLattice[O: Object, A: Object]
+       super POSet[FormalConcept[O, A]]
+
+       # Build `self` from a set of formal `concepts`.
+       init from_concepts(concepts: Set[FormalConcept[O, A]]) do
+               for c in concepts do
+                       add_node c
+               end
+               for c1 in concepts do
+                       for c2 in concepts do
+                               if c1 == c2 then continue
+                               if not is_lower_neighbour(c1, c2, concepts) then continue
+                               add_edge(c2, c1)
+                       end
+               end
+       end
+
+       # Is `sub` the greatest lower bound of `sup` considering all `concepts`?
+       fun is_lower_neighbour(sub, sup: FormalConcept[O, A], concepts: Set[FormalConcept[O, A]]): Bool
+       do
+               if sub == sup then return false
+               if not sub.is_subconcept(sup) then return false
+               for concept in concepts do
+                       if sub == concept then continue
+                       if sup == concept then continue
+                       if not sub.is_subconcept(concept) then continue
+                       if not concept.is_subconcept(sup) then continue
+                       return false
+               end
+               return true
+       end
+end
index e0369ed..25ce970 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_github_curl is test_suite
+module test_github_curl is test
 
 import github::github_curl
-import test_suite
 
 class TestGithubCurl
-       super TestSuite
+       test
 
        var auth: String = get_github_oauth
        var user_agent: String = "nit"
        var testee: GithubCurl is noinit
 
-       redef fun before_test do
+       fun before_test is before do
                testee = new GithubCurl(auth, user_agent)
        end
 
-       fun test_get_repo do
+       fun test_get_repo is test do
                var uri = "https://api.github.com/repos/nitlang/nit"
                var res = testee.get_and_check(uri)
 
@@ -37,7 +36,7 @@ class TestGithubCurl
                assert res["owner"] isa JsonObject
        end
 
-       fun test_get_user do
+       fun test_get_user is test do
                var uri = "https://api.github.com/users/Morriar"
                var res = testee.get_and_check(uri)
 
index b27a3c0..fc00782 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_native_gmp is test_suite
+module test_native_gmp is test
 
-import test_suite
 import native_gmp
 
 class TestNativeMPZ
-    super TestSuite
+       test
 
     var op1: NativeMPZ
     var op2: NativeMPZ
@@ -26,9 +25,7 @@ class TestNativeMPZ
     var r: NativeMPQ
     var res: NativeMPZ
 
-    init do end
-
-    redef fun before_test do
+    fun before_test is before do
         op1 = new NativeMPZ
         op2 = new NativeMPZ
         ui = new UInt64
@@ -36,7 +33,7 @@ class TestNativeMPZ
         res = new NativeMPZ
     end
 
-    redef fun after_test do
+    fun after_test is after do
         op1.finalize
         op2.finalize
         ui.free
@@ -212,23 +209,21 @@ class TestNativeMPZ
 end
 
 class TestNativeMPQ
-    super TestSuite
+       test
 
     var op1: NativeMPQ
     var op2: NativeMPQ
     var l: NativeMPZ
     var res: NativeMPQ
 
-    init do end
-
-    redef fun before_test do
+    fun before_test is before do
         op1 = new NativeMPQ
         op2 = new NativeMPQ
         l = new NativeMPZ
         res = new NativeMPQ
     end
 
-    redef fun after_test do
+    fun after_test is after do
         op1.finalize
         op2.finalize
         l.finalize
index 8a2c7a0..ad58649 100644 (file)
 # limitations under the License.
 
 # Test suites for module `markdown`
-module test_markdown is test_suite
+module test_markdown is test
 
-import test_suite
 intrude import markdown
 
 class TestMarkdownProcessor
-       super TestSuite
+       test
 
-       fun test_process_empty do
+       fun test_process_empty is test do
                var test = ""
                var exp = ""
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_tabs do
+       fun test_process_tabs is test do
                var test = """
        some code
 """
@@ -40,14 +39,14 @@ class TestMarkdownProcessor
        end
 
 
-       fun test_process_par1 do
+       fun test_process_par1 is test do
                var test = "test"
                var exp = "<p>test</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_par2 do
+       fun test_process_par2 is test do
                var test = """
 line1
 line2
@@ -65,7 +64,7 @@ line2</p>
                assert res == exp
        end
 
-       fun test_process_par3 do
+       fun test_process_par3 is test do
                var test = """
 Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
 Aliquam hendrerit mi posuere lectus.
@@ -85,7 +84,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_headings_1 do
+       fun test_process_headings_1 is test do
                var test = """
 This is a H1
 =============
@@ -101,7 +100,7 @@ This is a H2
                assert res == exp
        end
 
-       fun test_process_headings_2 do
+       fun test_process_headings_2 is test do
                var test = """
 # This is a H1
 
@@ -117,7 +116,7 @@ This is a H2
                assert res == exp
        end
 
-       fun test_process_headings_3 do
+       fun test_process_headings_3 is test do
                var test = """
 # This is a H1 #
 
@@ -134,7 +133,7 @@ This is a H2
                assert res == exp
        end
 
-       fun test_process_hr do
+       fun test_process_hr is test do
                var test = """
 * * *
 
@@ -151,7 +150,7 @@ This is a H2
                assert res == exp
        end
 
-       fun test_process_bquote1 do
+       fun test_process_bquote1 is test do
                var test = """
 > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
 > consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
@@ -172,7 +171,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_bquote2 do
+       fun test_process_bquote2 is test do
                var test = """
 > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
 consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
@@ -193,7 +192,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_bquote3 do
+       fun test_process_bquote3 is test do
                var test = """
 > This is the first level of quoting.
 >
@@ -213,7 +212,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_list1 do
+       fun test_process_list1 is test do
                var test = """
 *   Red
 *   Green
@@ -229,7 +228,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_list2 do
+       fun test_process_list2 is test do
                var test = """
 +   Red
 +   Green
@@ -245,7 +244,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_list3 do
+       fun test_process_list3 is test do
                var test = """
 -   Red
 -   Green
@@ -261,7 +260,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_list4 do
+       fun test_process_list4 is test do
                var test = """
 1.  Bird
 2.  McHale
@@ -277,7 +276,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_list5 do
+       fun test_process_list5 is test do
                var test = """
 3. Bird
 1. McHale
@@ -293,7 +292,7 @@ id sem consectetuer libero luctus adipiscing.</p>
                assert res == exp
        end
 
-       fun test_process_list6 do
+       fun test_process_list6 is test do
                var test = """
 *   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
     Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
@@ -314,7 +313,7 @@ Suspendisse id sem consectetuer libero luctus adipiscing.</li>
                assert res == exp
        end
 
-       fun test_process_list7 do
+       fun test_process_list7 is test do
                var test = """
 *   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
 Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
@@ -335,7 +334,7 @@ Suspendisse id sem consectetuer libero luctus adipiscing.</li>
                assert res == exp
        end
 
-       fun test_process_list8 do
+       fun test_process_list8 is test do
                var test = """
 *   Bird
 
@@ -353,7 +352,7 @@ Suspendisse id sem consectetuer libero luctus adipiscing.</li>
                assert res == exp
        end
 
-       fun test_process_list9 do
+       fun test_process_list9 is test do
                var test = """
 1.  This is a list item with two paragraphs. Lorem ipsum dolor
     sit amet, consectetuer adipiscing elit. Aliquam hendrerit
@@ -382,7 +381,7 @@ sit amet velit.</p>
                assert res == exp
        end
 
-       fun test_process_list10 do
+       fun test_process_list10 is test do
                var test = """
 *   This is a list item with two paragraphs.
 
@@ -407,7 +406,7 @@ sit amet, consectetuer adipiscing elit.</p>
                assert res == exp
        end
 
-       fun test_process_list11 do
+       fun test_process_list11 is test do
                var test = """
 This is a paragraph
 * and this is not a list
@@ -422,7 +421,7 @@ This is a paragraph
                assert res == exp
        end
 
-       fun test_process_list_ext do
+       fun test_process_list_ext is test do
                var test = """
 This is a paragraph
 * and this is not a list
@@ -437,7 +436,7 @@ This is a paragraph
                assert res == exp
        end
 
-       fun test_process_code1 do
+       fun test_process_code1 is test do
                var test = """
 This is a normal paragraph:
 
@@ -451,7 +450,7 @@ This is a normal paragraph:
                assert res == exp
        end
 
-       fun test_process_code2 do
+       fun test_process_code2 is test do
                var test = """
 Here is an example of AppleScript:
 
@@ -478,7 +477,7 @@ end tell
                assert res == exp
        end
 
-       fun test_process_code_ext1 do
+       fun test_process_code_ext1 is test do
                var test = """
 Here is an example of AppleScript:
 ~~~
@@ -506,7 +505,7 @@ end tell
                assert res == exp
        end
 
-       fun test_process_code_ext2 do
+       fun test_process_code_ext2 is test do
                var test = """
 Here is an example of AppleScript:
 ```
@@ -534,7 +533,7 @@ end tell
                assert res == exp
        end
 
-       fun test_process_code_ext3 do
+       fun test_process_code_ext3 is test do
                var proc = new MarkdownProcessor
                proc.ext_mode = false
 
@@ -550,7 +549,7 @@ beep</p>
                assert res == exp
        end
 
-       fun test_process_code_ext4 do
+       fun test_process_code_ext4 is test do
                var test = """
 Here is an example of AppleScript:
     beep
@@ -564,7 +563,7 @@ Here is an example of AppleScript:
                assert res == exp
        end
 
-       fun test_process_code_ext5 do
+       fun test_process_code_ext5 is test do
                var test = """
 ```nit
 print "Hello World!"
@@ -578,7 +577,7 @@ print "Hello World!"
                assert res == exp
        end
 
-       fun test_process_code_ext6 do
+       fun test_process_code_ext6 is test do
                var test = """
 ~~~
 print "Hello"
@@ -597,7 +596,7 @@ print "World"
                assert res == exp
        end
 
-       fun test_process_code_ext7 do
+       fun test_process_code_ext7 is test do
                var test = """
 ~~~
 print "Hello"
@@ -616,7 +615,7 @@ print "World"
                assert res == exp
        end
 
-       fun test_process_nesting1 do
+       fun test_process_nesting1 is test do
                var test = """
 > ## This is a header.
 >
@@ -643,7 +642,7 @@ print "World"
                assert res == exp
        end
 
-       fun test_process_nesting2 do
+       fun test_process_nesting2 is test do
                var test = """
 *   A list item with a blockquote:
 
@@ -664,7 +663,7 @@ inside a list item.</p>
                assert res == exp
        end
 
-       fun test_process_nesting3 do
+       fun test_process_nesting3 is test do
                var test = """
 *   A list item with a code block:
 
@@ -682,7 +681,7 @@ inside a list item.</p>
                assert res == exp
        end
 
-       fun test_process_nesting4 do
+       fun test_process_nesting4 is test do
                var test = """
 *      Tab
        *       Tab
@@ -704,7 +703,7 @@ inside a list item.</p>
        end
 
        # TODO
-       #       fun test_process_nesting5 do
+       #       fun test_process_nesting5 is test do
        #               var test = """
        # *     this
        #
@@ -726,7 +725,7 @@ inside a list item.</p>
        #               assert res == exp
        #       end
 
-       fun test_process_emph1 do
+       fun test_process_emph1 is test do
                var test = """
 *single asterisks*
 
@@ -745,14 +744,14 @@ __double underscores__
                assert res == exp
        end
 
-       fun test_process_emph2 do
+       fun test_process_emph2 is test do
                var test = "un*frigging*believable"
                var exp = "<p>un<em>frigging</em>believable</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_emph3 do
+       fun test_process_emph3 is test do
                var proc = new MarkdownProcessor
                proc.ext_mode = false
                var test = "Con_cat_this"
@@ -761,14 +760,14 @@ __double underscores__
                assert res == exp
        end
 
-       fun test_process_emph_ext do
+       fun test_process_emph_ext is test do
                var test = "Con_cat_this"
                var exp = "<p>Con_cat_this</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_xml1 do
+       fun test_process_xml1 is test do
                var test = """
 This is a regular paragraph.
 
@@ -793,7 +792,7 @@ This is another regular paragraph.
                assert res == exp
        end
 
-       fun test_process_xml2 do
+       fun test_process_xml2 is test do
                var test = """
 This is an image <img src="foo/bar" alt="baz"/> in a regular paragraph.
 """
@@ -803,7 +802,7 @@ This is an image <img src="foo/bar" alt="baz"/> in a regular paragraph.
                assert res == exp
        end
 
-       fun test_process_xml3 do
+       fun test_process_xml3 is test do
                var test = """
 <div style=">"/>
 """
@@ -814,7 +813,7 @@ This is an image <img src="foo/bar" alt="baz"/> in a regular paragraph.
                assert res == exp
        end
 
-       fun test_process_xml4 do
+       fun test_process_xml4 is test do
                var test = """
 <p>This is an example of a block element that should be escaped.</p>
 <p>Idem for the second paragraph.</p>
@@ -824,7 +823,7 @@ This is an image <img src="foo/bar" alt="baz"/> in a regular paragraph.
                assert res == exp
        end
 
-       fun test_process_xml5 do
+       fun test_process_xml5 is test do
                var test = """
 # Some more XML tests
 
@@ -844,21 +843,21 @@ With a *md paragraph*!
                assert res == exp
        end
 
-       fun test_process_span_code1 do
+       fun test_process_span_code1 is test do
                var test = "Use the `printf()` function."
                var exp = "<p>Use the <code>printf()</code> function.</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_span_code2 do
+       fun test_process_span_code2 is test do
                var test = "``There is a literal backtick (`) here.``"
                var exp = "<p><code>There is a literal backtick (`) here.</code></p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_span_code3 do
+       fun test_process_span_code3 is test do
                var test = """
 A single backtick in a code span: `` ` ``
 
@@ -872,42 +871,42 @@ A backtick-delimited string in a code span: `` `foo` ``
                assert res == exp
        end
 
-       fun test_process_span_code4 do
+       fun test_process_span_code4 is test do
                var test = "Please don't use any `<blink>` tags."
                var exp = "<p>Please don't use any <code>&lt;blink&gt;</code> tags.</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_span_code5 do
+       fun test_process_span_code5 is test do
                var test = "`&#8212;` is the decimal-encoded equivalent of `&mdash;`."
                var exp = "<p><code>&amp;#8212;</code> is the decimal-encoded equivalent of <code>&amp;mdash;</code>.</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_escape1 do
+       fun test_process_escape1 is test do
                var test = "\\*this text is surrounded by literal asterisks\\*"
                var exp = "<p>*this text is surrounded by literal asterisks*</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_escape2 do
+       fun test_process_escape2 is test do
                var test = "1986\\. What a great season."
                var exp = "<p>1986. What a great season.</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_escape3 do
+       fun test_process_escape3 is test do
                var test = "Ben & Lux"
                var exp = "<p>Ben &amp; Lux</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_link1 do
+       fun test_process_link1 is test do
                var test = """
 This is [an example](http://example.com/ "Title") inline link.
 
@@ -920,14 +919,14 @@ This is [an example](http://example.com/ "Title") inline link.
                assert res == exp
        end
 
-       fun test_process_link2 do
+       fun test_process_link2 is test do
                var test = "See my [About](/about/) page for details."
                var exp = "<p>See my <a href=\"/about/\">About</a> page for details.</p>\n"
                var res = test.md_to_html.write_to_string
                assert res == exp
        end
 
-       fun test_process_link3 do
+       fun test_process_link3 is test do
                var test = """
 This is [an example][id] reference-style link.
 
@@ -949,7 +948,7 @@ Some other lipsum
                assert res == exp
        end
 
-       fun test_process_link4 do
+       fun test_process_link4 is test do
                var test = """
 This is multiple examples: [foo][1], [bar][2], [baz][3].
 
@@ -964,7 +963,7 @@ This is multiple examples: [foo][1], [bar][2], [baz][3].
                assert res == exp
        end
 
-       fun test_process_link5 do
+       fun test_process_link5 is test do
                var test = """
 This is multiple examples: [foo][a], [bar][A], [a].
 
@@ -976,7 +975,7 @@ This is multiple examples: [foo][a], [bar][A], [a].
                assert res == exp
        end
 
-       fun test_process_link6 do
+       fun test_process_link6 is test do
                var test = """
 I get 10 times more traffic from [Google][] than from [Yahoo][] or [MSN][].
 
@@ -990,7 +989,7 @@ I get 10 times more traffic from [Google][] than from [Yahoo][] or [MSN][].
                assert res == exp
        end
 
-       fun test_process_link7 do
+       fun test_process_link7 is test do
                var test = """
 Visit [Daring Fireball][] for more information.
 
@@ -1002,7 +1001,7 @@ Visit [Daring Fireball][] for more information.
                assert res == exp
        end
 
-       fun test_process_link8 do
+       fun test_process_link8 is test do
                var test = """
 This one has a [line
 break].
@@ -1023,7 +1022,7 @@ break</a> with a line-ending space.</p>
        end
 
        # FIXME unignore test once escape strings fixed
-       #       fun test_process_link9 do
+       #       fun test_process_link9 is test do
        #               var test = """
        # Foo [bar][].
        #
@@ -1040,7 +1039,7 @@ break</a> with a line-ending space.</p>
        #               assert res == exp
        #       end
 
-       fun test_process_img1 do
+       fun test_process_img1 is test do
                var test = """
 ![Alt text](/path/to/img.jpg)
 
@@ -1053,7 +1052,7 @@ break</a> with a line-ending space.</p>
                assert res == exp
        end
 
-       fun test_process_img2 do
+       fun test_process_img2 is test do
                var test = """
 ![Alt text][id]
 
@@ -1065,7 +1064,7 @@ break</a> with a line-ending space.</p>
                assert res == exp
        end
 
-       fun test_process_strike do
+       fun test_process_strike is test do
                var proc = new MarkdownProcessor
                proc.ext_mode = false
                var test = "This is how you ~~strike text~~"
@@ -1074,21 +1073,21 @@ break</a> with a line-ending space.</p>
                assert exp == res
        end
 
-       fun test_process_strike_ext do
+       fun test_process_strike_ext is test do
                var test = "This is how you ~~strike text~~"
                var exp = "<p>This is how you <del>strike text</del></p>\n"
                var res = test.md_to_html.write_to_string
                assert exp == res
        end
 
-       fun test_escape_bad_html do
+       fun test_escape_bad_html is test do
                        var test = "-1 if < , +1 if > and 0 otherwise"
                        var exp = "<p>-1 if &lt; , +1 if > and 0 otherwise</p>\n"
                var res = test.md_to_html.write_to_string
                assert exp == res
        end
 
-       fun test_daring_encoding do
+       fun test_daring_encoding is test do
                var test = """
 AT&T has an ampersand in their name.
 
@@ -1129,7 +1128,7 @@ Here's an inline [link](</script?foo=1&bar=2>).
 
        end
 
-       fun test_daring_autolinks do
+       fun test_daring_autolinks is test do
                var test = """
 Link: <http://example.com/>.
 
@@ -1165,7 +1164,7 @@ Auto-links should not occur here: `<http://example.com/>`
                assert res == exp
        end
 
-       fun test_daring_escape do
+       fun test_daring_escape is test do
                var test = """
 These should all get escaped:
 
@@ -1367,7 +1366,7 @@ other Markdown constructs:</p>
                assert res == exp
        end
 
-       fun test_daring_blockquotes do
+       fun test_daring_blockquotes is test do
                var test = """
 > Example:
 >
@@ -1400,7 +1399,7 @@ other Markdown constructs:</p>
                assert res == exp
        end
 
-       fun test_daring_code_blocks do
+       fun test_daring_code_blocks is test do
                var test = """
        code block on the first line
 
@@ -1436,7 +1435,7 @@ all contain trailing spaces
                assert res == exp
        end
 
-       fun test_daring_code_spans do
+       fun test_daring_code_spans is test do
                var test = """
 `<test a="` content of attribute `">`
 
@@ -1454,7 +1453,7 @@ Here's how you put `` `backticks` `` in a code span.
                assert res == exp
        end
 
-       fun test_daring_pars do
+       fun test_daring_pars is test do
                var proc = new MarkdownProcessor
                proc.ext_mode = false
 
@@ -1482,7 +1481,7 @@ list item.</p>
                assert res == exp
        end
 
-       fun test_daring_rules do
+       fun test_daring_rules is test do
                var test = """
 Dashes:
 
@@ -1598,7 +1597,7 @@ _ _ _
                assert res == exp
        end
 
-       fun test_daring_images do
+       fun test_daring_images is test do
                var test = """
 ![Alt text](/path/to/img.jpg)
 
@@ -1645,7 +1644,7 @@ Inline within a paragraph: [alt text](/url/).
                assert res == exp
        end
 
-       fun test_daring_inline_html1 do
+       fun test_daring_inline_html1 is test do
                var test = """
 Here's a simple block:
 
@@ -1768,7 +1767,7 @@ Blah
                assert res == exp
        end
 
-       fun test_daring_inline_html2 do
+       fun test_daring_inline_html2 is test do
                var test = """
 Simple block on one line:
 
@@ -1831,7 +1830,7 @@ foo
                assert res == exp
        end
 
-       fun test_daring_inline_html3 do
+       fun test_daring_inline_html3 is test do
                var test = """
 Paragraph one.
 
@@ -1862,7 +1861,7 @@ The end.
                assert res == exp
        end
 
-       fun test_daring_links1 do
+       fun test_daring_links1 is test do
                var test = """
 Just a [URL](/url/).
 
@@ -1908,7 +1907,7 @@ Just a [URL](/url/).
                assert res == exp
        end
 
-       fun test_daring_links2 do
+       fun test_daring_links2 is test do
                var test = """
 Foo [bar] [1].
 
@@ -2017,7 +2016,7 @@ breaks</a> across lines, but with a line-ending space.</p>
                assert res == exp
        end
 
-       fun test_daring_links3 do
+       fun test_daring_links3 is test do
                var test = """
 This is the [simple case].
 
@@ -2053,7 +2052,7 @@ break</a> with a line-ending space.</p>
                assert res == exp
        end
 
-       fun test_daring_nested do
+       fun test_daring_nested is test do
                var test = """
 > foo
 >
@@ -2075,7 +2074,7 @@ break</a> with a line-ending space.</p>
                assert res == exp
        end
 
-       fun test_daring_list do
+       fun test_daring_list is test do
                var test = """
 ## Unordered
 
@@ -2332,7 +2331,7 @@ back.</p>
                assert res == exp
        end
 
-       fun test_daring_strong_em do
+       fun test_daring_strong_em is test do
                var test = """
 ***This is strong and em.***
 
@@ -2353,7 +2352,7 @@ So is ___this___ word.
                assert res == exp
        end
 
-       fun test_daring_tabs do
+       fun test_daring_tabs is test do
                var test = """
 +      this is a list item
        indented with tabs
@@ -2405,7 +2404,7 @@ indented with spaces</p>
                assert res == exp
        end
 
-       fun test_daring_tidyness do
+       fun test_daring_tidyness is test do
                var test = """
 > A list within a blockquote:
 >
@@ -2432,19 +2431,19 @@ indented with spaces</p>
 end
 
 class TestBlock
-       super TestSuite
+       test
 
        # A dummy location for testing purposes.
        var loc = new MDLocation(0, 0, 0, 0)
 
-       fun test_has_blocks do
+       fun test_has_blocks is test do
                var subject = new MDBlock(loc)
                assert not subject.has_blocks
                subject.first_block = new MDBlock(loc)
                assert subject.has_blocks
        end
 
-       fun test_count_blocks do
+       fun test_count_blocks is test do
                var subject = new MDBlock(loc)
                assert subject.count_blocks == 0
                subject.first_block = new MDBlock(loc)
@@ -2453,14 +2452,14 @@ class TestBlock
                assert subject.count_blocks == 2
        end
 
-       fun test_has_lines do
+       fun test_has_lines is test do
                var subject = new MDBlock(loc)
                assert not subject.has_lines
                subject.first_line = new MDLine(loc, "")
                assert subject.has_lines
        end
 
-       fun test_count_lines do
+       fun test_count_lines is test do
                var subject = new MDBlock(loc)
                assert subject.count_lines == 0
                subject.first_line = new MDLine(loc, "")
@@ -2469,7 +2468,7 @@ class TestBlock
                assert subject.count_lines == 2
        end
 
-       fun test_split do
+       fun test_split is test do
                var line1 = new MDLine(loc, "line1")
                var line2 = new MDLine(loc, "line2")
                var line3 = new MDLine(loc, "line3")
@@ -2487,7 +2486,7 @@ class TestBlock
                assert block.last_line == line2
        end
 
-       fun test_add_line do
+       fun test_add_line is test do
                var subject = new MDBlock(loc)
                assert subject.count_lines == 0
                subject.add_line new MDLine(loc, "")
@@ -2496,7 +2495,7 @@ class TestBlock
                assert subject.count_lines == 2
        end
 
-       fun test_remove_line do
+       fun test_remove_line is test do
                var line1 = new MDLine(loc, "line1")
                var line2 = new MDLine(loc, "line2")
                var line3 = new MDLine(loc, "line3")
@@ -2512,7 +2511,7 @@ class TestBlock
                assert subject.last_line == line3
        end
 
-       fun test_transform_headline1 do
+       fun test_transform_headline1 is test do
                var subject = new MDBlock(loc)
                var kind = new BlockHeadline(subject)
                subject.add_line new MDLine(loc, " #   Title 1   ")
@@ -2521,7 +2520,7 @@ class TestBlock
                assert subject.first_line.value == "Title 1"
        end
 
-       fun test_transform_headline2 do
+       fun test_transform_headline2 is test do
                var subject = new MDBlock(loc)
                var kind = new BlockHeadline(subject)
                subject.add_line new MDLine(loc, " #####Title 5   ")
@@ -2530,7 +2529,7 @@ class TestBlock
                assert subject.first_line.value == "Title 5"
        end
 
-       fun test_remove_quote_prefix do
+       fun test_remove_quote_prefix is test do
                var subject = new MDBlock(loc)
                var kind = new BlockQuote(subject)
                subject.add_line new MDLine(loc, " > line 1")
@@ -2542,7 +2541,7 @@ class TestBlock
                assert subject.first_line.next.next.value == "line 3"
        end
 
-       fun test_remove_leading_empty_lines_1 do
+       fun test_remove_leading_empty_lines_1 is test do
                var block = new MDBlock(loc)
                block.add_line new MDLine(loc, "")
                block.add_line new MDLine(loc, "")
@@ -2554,14 +2553,14 @@ class TestBlock
                assert block.first_line.value == "   text"
        end
 
-       fun test_remove_leading_empty_lines_2 do
+       fun test_remove_leading_empty_lines_2 is test do
                var block = new MDBlock(loc)
                block.add_line new MDLine(loc, "   text")
                block.remove_leading_empty_lines
                assert block.first_line.value == "   text"
        end
 
-       fun test_remove_trailing_empty_lines_1 do
+       fun test_remove_trailing_empty_lines_1 is test do
                var block = new MDBlock(loc)
                block.add_line new MDLine(loc, "")
                block.add_line new MDLine(loc, "text")
@@ -2573,14 +2572,14 @@ class TestBlock
                assert block.last_line.value == "text"
        end
 
-       fun test_remove_trailing_empty_lines_2 do
+       fun test_remove_trailing_empty_lines_2 is test do
                var block = new MDBlock(loc)
                block.add_line new MDLine(loc, "text  ")
                assert not block.remove_trailing_empty_lines
                assert block.last_line.value == "text  "
        end
 
-       fun test_remove_surrounding_empty_lines do
+       fun test_remove_surrounding_empty_lines is test do
                var block = new MDBlock(loc)
                block.add_line new MDLine(loc, "")
                block.add_line new MDLine(loc, "text")
@@ -2595,14 +2594,14 @@ class TestBlock
 end
 
 class TestLine
-       super TestSuite
+       test
 
        # A dummy location for testing purposes.
        var loc = new MDLocation(0, 0, 0, 0)
 
        var subject: MDLine
 
-       fun test_is_empty do
+       fun test_is_empty is test do
                subject = new MDLine(loc, "")
                assert subject.is_empty
                subject = new MDLine(loc, "    ")
@@ -2613,7 +2612,7 @@ class TestLine
                assert not subject.is_empty
        end
 
-       fun test_leading do
+       fun test_leading is test do
                subject = new MDLine(loc, "")
                assert subject.leading == 0
                subject = new MDLine(loc, "    ")
@@ -2624,7 +2623,7 @@ class TestLine
                assert subject.leading == 4
        end
 
-       fun test_trailing do
+       fun test_trailing is test do
                subject = new MDLine(loc, "")
                assert subject.trailing == 0
                subject = new MDLine(loc, "    ")
@@ -2635,7 +2634,7 @@ class TestLine
                assert subject.trailing == 1
        end
 
-       fun test_line_type do
+       fun test_line_type is test do
                var v = new MarkdownProcessor
                subject = new MDLine(loc, "")
                assert v.line_kind(subject) isa LineEmpty
@@ -2681,7 +2680,7 @@ class TestLine
                assert v.line_kind(subject) isa LineOList
        end
 
-       fun test_line_type_ext do
+       fun test_line_type_ext is test do
                var v = new MarkdownProcessor
                subject = new MDLine(loc, "  ~~~")
                assert v.line_kind(subject) isa LineFence
@@ -2691,7 +2690,7 @@ class TestLine
                assert v.line_kind(subject) isa LineFence
        end
 
-       fun test_count_chars do
+       fun test_count_chars is test do
                subject = new MDLine(loc, "")
                assert subject.count_chars('*') == 0
                subject = new MDLine(loc, "* ")
@@ -2704,7 +2703,7 @@ class TestLine
                assert subject.count_chars('*') == 0
        end
 
-       fun test_count_chars_start do
+       fun test_count_chars_start is test do
                subject = new MDLine(loc, "")
                assert subject.count_chars_start('*') == 0
                subject = new MDLine(loc, "* ")
@@ -2719,9 +2718,9 @@ class TestLine
 end
 
 class TestHTMLDecorator
-       super TestSuite
+       test
 
-       fun test_headlines do
+       fun test_headlines is test do
                var test = """
 # **a**
 ## a.a
@@ -2760,9 +2759,9 @@ c:c
 end
 
 class TestTokenLocation
-       super TestSuite
+       test
 
-       fun test_token_location1 do
+       fun test_token_location1 is test do
                var string = "**Hello** `World`"
                var stack =  [
                        "TokenStrongStar at 1,1--1,1",
@@ -2772,7 +2771,7 @@ class TestTokenLocation
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location2 do
+       fun test_token_location2 is test do
                var string = "**Hello**\n`World`\n*Bonjour*\n[le monde]()"
                var stack =  [
                        "TokenStrongStar at 1,1--1,1",
@@ -2785,7 +2784,7 @@ class TestTokenLocation
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location3 do
+       fun test_token_location3 is test do
                var string = """**Hello**
                `World`
                *Bonjour*
@@ -2801,7 +2800,7 @@ class TestTokenLocation
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location4 do
+       fun test_token_location4 is test do
                var string = "**Hello**\n\n`World`"
                var stack =  [
                        "TokenStrongStar at 1,1--1,1",
@@ -2811,7 +2810,7 @@ class TestTokenLocation
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location5 do
+       fun test_token_location5 is test do
                var string = "# *Title1*\n\n# *Title2*"
                var stack =  [
                        "TokenEmStar at 1,3--1,3",
@@ -2841,11 +2840,11 @@ class TestTokenProcessor
 end
 
 class TestBlockLocation
-       super TestSuite
+       test
 
        var proc = new MarkdownProcessor
 
-       fun test_block_location1 do
+       fun test_block_location1 is test do
                var stack = [
                        "BlockHeadline: 1,1--1,8",
                        "BlockListItem: 2,1--2,6",
@@ -2857,7 +2856,7 @@ class TestBlockLocation
                proc.process(string)
        end
 
-       fun test_block_location2 do
+       fun test_block_location2 is test do
                var stack = [
                        "BlockHeadline: 1,1--1,11",
                        "BlockFence: 3,1--5,4",
@@ -2875,7 +2874,7 @@ some code
                proc.process(string)
        end
 
-       fun test_block_location3 do
+       fun test_block_location3 is test do
                var stack = [
                        "BlockHeadline: 1,1--1,8",
                        "BlockHeadline: 3,1--3,10"]
index 5c4fb7e..133493d 100644 (file)
 # limitations under the License.
 
 # Test suites for module `markdown`
-module test_wikilinks is test_suite
+module test_wikilinks is test
 
 import test_markdown
 import wikilinks
 
 class TestTokenWikilink
-       super TestSuite
+       test
 
-       fun test_token_location1 do
+       fun test_token_location1 is test do
                var string = "[[wikilink]]"
                var stack =  ["TokenWikiLink at 1,1--1,1"]
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location2 do
+       fun test_token_location2 is test do
                var string = "Hello [[World]]"
                var stack =  ["TokenWikiLink at 1,7--1,7"]
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location3 do
+       fun test_token_location3 is test do
                var string = "\nHello\nworld [[wikilink]] !"
                var stack =  ["TokenWikiLink at 3,7--3,7"]
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location4 do
+       fun test_token_location4 is test do
                var string = "[[link1]]\n\n[[link2]]"
                var stack =  [
                        "TokenWikiLink at 1,1--1,1",
@@ -47,7 +47,7 @@ class TestTokenWikilink
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location5 do
+       fun test_token_location5 is test do
                var string = "[[link1]]\n[[link2]]"
                var stack =  [
                        "TokenWikiLink at 1,1--1,1",
@@ -55,7 +55,7 @@ class TestTokenWikilink
                (new TestTokenProcessor(stack)).process(string)
        end
 
-       fun test_token_location6 do
+       fun test_token_location6 is test do
                var string = """
 [[doc: github]]
 
index c7196c4..9c718a9 100644 (file)
@@ -61,14 +61,6 @@ For ease of use, this wrapper introduce a Nit model to handle CoreNLP XML result
 [[doc: nlp::NLPProcessor::process_file]]
 [[doc: nlp::NLPProcessor::process_files]]
 
-## Vector Space Model
-
-[[doc: NLPVector]]
-
-[[doc: vector]]
-
-[[doc: nlp::NLPVector::cosine_similarity]]
-
 ## NitNLP binary
 
 The `nitnlp` binary is given as an example of NitNLP client.
index 4dd7cc9..0e4dba3 100644 (file)
@@ -23,17 +23,17 @@ import vsm
 redef class NLPDocument
 
        # `NLPVector` representing `self`.
-       var vector: NLPVector is lazy do
-               var vector = new NLPVector
+       var vector: Vector is lazy do
+               var vector = new Vector
                for sentence in sentences do
                        for token in sentence.tokens do
                                if not keep_pos_token(token) then continue
                                var lemma = token.lemma
                                if lemma_black_list.has(lemma) then continue
                                if not vector.has_key(lemma) then
-                                       vector[lemma] = 1
+                                       vector[lemma] = 1.0
                                else
-                                       vector[lemma] += 1
+                                       vector[lemma] += 1.0
                                end
                        end
                end
diff --git a/lib/nlp/vsm.nit b/lib/nlp/vsm.nit
deleted file mode 100644 (file)
index 7fe0a84..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-# This file is part of NIT ( http://www.nitlanguage.org ).
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# NLPVector Space Model.
-#
-# The Vector Space Model (VSM) is used to compare natural language texts.
-# Texts are translated to multidimensionnal vectors then compared by cosine
-# similarity.
-module vsm
-
-import counter
-
-# A multi-dimensional vector.
-class NLPVector
-       super Counter[String]
-
-       # Cosine similarity of `self` and `other`.
-       #
-       # Gives the proximity in the range `[0.0 .. 1.0]` where 0.0 means that the
-       # two vectors are orthogonal and 1.0 means that they are identical.
-       #
-       # ~~~
-       # var v1 = new NLPVector
-       # v1["x"] = 1
-       # v1["y"] = 2
-       # v1["z"] = 3
-       #
-       # var v2 = new NLPVector
-       # v2["x"] = 1
-       # v2["y"] = 2
-       # v2["z"] = 3
-       #
-       # var v3 = new NLPVector
-       # v3["a"] = 1
-       # v3["b"] = 2
-       # v3["c"] = 3
-       #
-       # print v1.cosine_similarity(v2)
-       # #assert v1.cosine_similarity(v2) == 1.0
-       # print v1.cosine_similarity(v3)
-       # assert v1.cosine_similarity(v3) == 0.0
-       # ~~~
-       fun cosine_similarity(other: SELF): Float do
-               # Collect terms
-               var terms = new HashSet[String]
-               for k in self.keys do terms.add k
-               for k in other.keys do terms.add k
-
-               # Get dot product of two verctors
-               var dot = 0
-               for term in terms do
-                       dot += self.get_or_default(term, 0) * other.get_or_default(term, 0)
-               end
-
-               return dot.to_f / (self.norm * other.norm)
-       end
-
-       # The norm of the vector.
-       #
-       # `||x|| = (x1 ** 2 ... + xn ** 2).sqrt`
-       #
-       # ~~~
-       # var v = new NLPVector
-       # v["x"] = 1
-       # v["y"] = 1
-       # v["z"] = 1
-       # v["t"] = 1
-       # assert v.norm.is_approx(2.0, 0.001)
-       #
-       # v["x"] = 1
-       # v["y"] = 2
-       # v["z"] = 3
-       # v["t"] = 0
-       # assert v.norm.is_approx(3.742, 0.001)
-       # ~~~
-       fun norm: Float do
-               var sum = 0
-               for v in self.values do sum += v ** 2
-               return sum.to_f.sqrt
-       end
-end
index 7c6fa1d..7ca4802 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_angular is test_suite
+module test_example_angular is test
 
 import pop_tests
 import example_angular
 
 class TestExampleAngular
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/counter"
@@ -29,7 +30,7 @@ class TestExampleAngular
                system "curl -s {host}:{port}/not_found" # handled by angular controller
        end
 
-       fun test_example_angular do
+       fun test_example_angular is test do
                var app = new App
                app.use("/counter", new CounterAPI)
                app.use("/*", new StaticHandler(test_path / "../www/", "index.html"))
index a1cbb13..a0dc10f 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_post_handler is test_suite
+module test_example_post_handler is test
 
 import pop_tests
 import example_post_handler
 
 class TestExamplePostHandler
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/ -X POST"
@@ -31,7 +32,7 @@ class TestExamplePostHandler
                system "curl -s {host}:{port}/"
        end
 
-       fun test_example_post_handler do
+       fun test_example_post_handler is test do
                var app = new App
                app.use("/", new PostHandler)
                run_test(app)
index db326ea..8909f91 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_query_string is test_suite
+module test_example_query_string is test
 
 import pop_tests
 import example_query_string
 
 class TestExampleQueryString
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
@@ -30,7 +31,7 @@ class TestExampleQueryString
                system "curl -s {host}:{port}/?items=10\\&order=asc"
        end
 
-       fun test_example_query_string do
+       fun test_example_query_string is test do
                var app = new App
                app.use("/", new QueryStringHandler)
                run_test(app)
index 163e624..e206456 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_hello is test_suite
+module test_example_hello is test
 
 import pop_tests
 import example_hello
 
 class TestExampleHello
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}"
@@ -30,7 +31,7 @@ class TestExampleHello
                system "curl -s {host}:{port}/not_found/not_found"
        end
 
-       fun test_example_hello do
+       fun test_example_hello is test do
                var app = new App
                app.use("/", new HelloHandler)
                run_test(app)
index f870136..adfe426 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_advanced_logger is test_suite
+module test_example_advanced_logger is test
 
 import pop_tests
 import example_advanced_logger
 
 class TestExampleAdvancedLogger
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
                system "curl -s {host}:{port}/about"
        end
 
-       fun test_example_advanced_logger do
+       fun test_example_advanced_logger is test do
                var app = new App
                app.use_before("/*", new RequestTimeHandler)
                app.use("/", new AnotherHandler)
index 93912ca..5322bbc 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_html_error_handler is test_suite
+module test_example_html_error_handler is test
 
 import pop_tests
 import example_html_error_handler
 
 class TestExampleHtmlErrorHandler
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
                system "curl -s {host}:{port}/about"
        end
 
-       fun test_example_html_error_handler do
+       fun test_example_html_error_handler is test do
                var app = new App
                app.use("/*", new HtmlErrorHandler)
                run_test(app)
index e45acad..7016f1a 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_simple_error_handler is test_suite
+module test_example_simple_error_handler is test
 
 import pop_tests
 import example_simple_error_handler
 
 class TestExampleSimpleErrorHandler
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
                system "curl -s {host}:{port}/about"
        end
 
-       fun test_example_simple_error_handler do
+       fun test_example_simple_error_handler is test do
                var app = new App
                app.use("/", new SomeHandler)
                app.use("/*", new SimpleErrorHandler)
index b0c41f8..25db274 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_simple_logger is test_suite
+module test_example_simple_logger is test
 
 import pop_tests
 import example_simple_logger
 
 class TestExampleSimpleLogger
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
                system "curl -s {host}:{port}/about"
        end
 
-       fun test_example_simple_logger do
+       fun test_example_simple_logger is test do
                var app = new App
                app.use_before("/*", new SimpleLoggerHandler)
                app.use("/", new MyOtherHandler)
index c258260..e44be2a 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_glob_route is test_suite
+module test_example_glob_route is test
 
 import pop_tests
 import example_glob_route
 
 class TestExampleGlobRoute
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/user/Morriar/item/10"
@@ -32,7 +33,7 @@ class TestExampleGlobRoute
                system "curl -s {host}:{port}/not_found/not_found"
        end
 
-       fun test_example_glob_route do
+       fun test_example_glob_route is test do
                var app = new App
                app.use("/user/:user/item/:item/*", new UserItem)
                run_test(app)
index 52f818a..813eda4 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_param_route is test_suite
+module test_example_param_route is test
 
 import pop_tests
 import example_param_route
 
 class TestExampleParamRoute
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/Morriar"
@@ -30,7 +31,7 @@ class TestExampleParamRoute
                system "curl -s {host}:{port}/not_found/not_found"
        end
 
-       fun test_example_param_route do
+       fun test_example_param_route is test do
                var app = new App
                app.use("/:user", new UserHome)
                run_test(app)
index 55d5ed9..e0c3082 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_router is test_suite
+module test_example_router is test
 
 import pop_tests
 import example_router
 
 class TestExampleRouter
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}"
@@ -33,7 +34,7 @@ class TestExampleRouter
                system "curl -s {host}:{port}/products/not_found"
        end
 
-       fun test_example_router do
+       fun test_example_router is test do
                var user_router = new Router
                user_router.use("/*", new UserLogger)
                user_router.use("/", new UserHomepage)
index 6310171..91a6e8f 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_session is test_suite
+module test_example_session is test
 
 import pop_tests
 import example_session
 
 class TestExampleSession
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
@@ -30,7 +31,7 @@ class TestExampleSession
                system "curl -s {host}:{port}/products/not_found"
        end
 
-       fun test_example_session do
+       fun test_example_session is test do
                var app = new App
                app.use("/*", new SessionInit)
                app.use("/", new AppLogin)
index a1c26a9..b65bcd6 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_static is test_suite
+module test_example_static is test
 
 import pop_tests
 import example_static
 
 class TestExampleStatic
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/css/style.css"
@@ -32,7 +33,7 @@ class TestExampleStatic
                system "curl -s {host}:{port}/not_found.nit"
        end
 
-       fun test_example_static do
+       fun test_example_static is test do
                var app = new App
                app.use("/", new StaticHandler(test_path / "../public/"))
                run_test(app)
index 30ef93e..3f9ce22 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_static_default is test_suite
+module test_example_static_default is test
 
 import pop_tests
 import example_static_default
 
 class TestExampleStaticDefault
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/css/style.css"
@@ -32,7 +33,7 @@ class TestExampleStaticDefault
                system "curl -s {host}:{port}/not_found.nit"
        end
 
-       fun test_example_static_default do
+       fun test_example_static_default is test do
                var app = new App
                app.use("/", new StaticHandler(test_path / "../public/", "default.html"))
                run_test(app)
index 42fc7df..3d4d2d9 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_static_multiple is test_suite
+module test_example_static_multiple is test
 
 import pop_tests
 import example_static_multiple
 
 class TestExampleStaticMultiple
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/css/style.css"
@@ -36,7 +37,7 @@ class TestExampleStaticMultiple
                system "curl -s {host}:{port}/not_found.nit"
        end
 
-       fun test_example_static_multiple do
+       fun test_example_static_multiple is test do
                var app = new App
                app.use("/", new StaticHandler(test_path / "../public/"))
                app.use("/", new StaticHandler(test_path / "../files/"))
index 3334320..fb88bf1 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_example_templates is test_suite
+module test_example_templates is test
 
 import pop_tests
 intrude import example_templates
 
 class TestExampleTemplate
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
        end
 
-       fun test_example_template do
+       fun test_example_template is test do
                var app = new App
                app.use("/", new MyTemplateHandler)
                run_test(app)
@@ -35,12 +36,13 @@ end
 
 class TestExampleTemplateString
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
        end
 
-       fun test_example_template_string do
+       fun test_example_template_string is test do
                var app = new App
                app.use("/", new MyTemplateStringHandler)
                run_test(app)
@@ -49,12 +51,13 @@ end
 
 class TestExampleTemplateFile
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
        end
 
-       fun test_example_template_file do
+       fun test_example_template_file is test do
                var app = new App
                var handler = new MyTemplateFileHandler
                handler.tpl_file = test_path / "../example_template.tpl"
@@ -65,12 +68,13 @@ end
 
 class TestExampleTemplatePug
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
        end
 
-       fun test_example_template_pug do
+       fun test_example_template_pug is test do
                var app = new App
                app.use("/", new MyTemplatePugHandler)
                run_test(app)
@@ -79,12 +83,13 @@ end
 
 class TestExampleTemplatePugFile
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}/"
        end
 
-       fun test_example_template_pug_file do
+       fun test_example_template_pug_file is test do
                var app = new App
                var handler = new MyTemplatePugFileHandler
                handler.pug_file = test_path / "../example_template.pug"
index 6c5985d..5d89e59 100644 (file)
 # Here we use `curl` to access some URI on the app.
 #
 # ~~~nitish
-# module test_example_hello is test_suite
+# module test_example_hello is test
 #
 # import pop_tests
 # import example_hello
 #
 # class TestExampleHello
 #      super TestPopcorn
+#      test
 #
-#      fun test_example_hello do
+#      fun example_hello is test do
 #              var app = new App
 #              app.use("/", new HelloHandler)
 #              run_test(app)
@@ -68,7 +69,6 @@
 # See `examples/hello_world` for the complete example.
 module pop_tests
 
-import test_suite
 import popcorn
 import pthreads
 
@@ -123,7 +123,6 @@ end
 
 # TestSuite for Popcorn blackbox testing.
 class TestPopcorn
-       super TestSuite
 
        # Host used to run App.
        var host: String = test_host
index 9ad37a5..9c81cce 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_pop_routes is test_suite
+module test_pop_routes is test
 
 import pop_routes
-import test_suite
 
 class TestAppRoute
-       super TestSuite
+       test
 
-       fun test_root_match_only_one_uri do
+       fun test_root_match_only_one_uri is test do
                var r = new AppRoute("/")
                assert r.match("")
                assert r.match("/")
                assert not r.match("/user")
        end
 
-       fun test_strict_route_match_only_one_uri do
+       fun test_strict_route_match_only_one_uri is test do
                var r = new AppRoute("/user")
                assert not r.match("/")
                assert r.match("/user")
@@ -40,9 +39,9 @@ class TestAppRoute
 end
 
 class TestAppParamRoute
-       super TestSuite
+       test
 
-       fun test_param_route_match_good_uri_params_1 do
+       fun test_param_route_match_good_uri_params_1 is test do
                var r = new AppParamRoute("/:id")
                assert not r.match("/")
                assert r.match("/user")
@@ -50,7 +49,7 @@ class TestAppParamRoute
                assert not r.match("/user/10")
        end
 
-       fun test_param_route_match_good_uri_params_2 do
+       fun test_param_route_match_good_uri_params_2 is test do
                var r = new AppParamRoute("/user/:id")
                assert not r.match("/")
                assert not r.match("/user")
@@ -60,7 +59,7 @@ class TestAppParamRoute
                assert not r.match("/user/10/profile")
        end
 
-       fun test_param_route_match_good_uri_params_3 do
+       fun test_param_route_match_good_uri_params_3 is test do
                var r = new AppParamRoute("/user/:id/profile")
                assert not r.match("/")
                assert not r.match("/user")
@@ -73,7 +72,7 @@ class TestAppParamRoute
                assert not r.match("/user/10/foo")
        end
 
-       fun test_param_route_match_good_uri_params_4 do
+       fun test_param_route_match_good_uri_params_4 is test do
                var r = new AppParamRoute("/:id/:foo")
                assert not r.match("/")
                assert not r.match("/user")
@@ -83,7 +82,7 @@ class TestAppParamRoute
                assert not r.match("/user/10/10")
        end
 
-       fun test_param_route_match_good_uri_params_5 do
+       fun test_param_route_match_good_uri_params_5 is test do
                var r = new AppParamRoute("/user/:id/:foo")
                assert not r.match("/")
                assert not r.match("/user")
@@ -94,7 +93,7 @@ class TestAppParamRoute
                assert not r.match("/user/10/10/profile")
        end
 
-       fun test_param_route_match_good_uri_params_6 do
+       fun test_param_route_match_good_uri_params_6 is test do
                var r = new AppParamRoute("/user/:id/settings/:foo")
                assert not r.match("/")
                assert not r.match("/user")
@@ -110,30 +109,30 @@ class TestAppParamRoute
 end
 
 class TestRouteMatching
-       super TestSuite
+       test
 
-       fun test_glob_route_match_good_uri_prefix1 do
+       fun test_glob_route_match_good_uri_prefix1 is test do
                var r = new AppGlobRoute("/*")
                assert r.match("/")
                assert r.match("/user")
                assert r.match("/user/10")
        end
 
-       fun test_glob_route_match_good_uri_prefix2 do
+       fun test_glob_route_match_good_uri_prefix2 is test do
                var r = new AppGlobRoute("/user/*")
                assert not r.match("/")
                assert r.match("/user")
                assert r.match("/user/10")
        end
 
-       fun test_glob_route_match_good_uri_prefix3 do
+       fun test_glob_route_match_good_uri_prefix3 is test do
                var r = new AppGlobRoute("/user*")
                assert not r.match("/")
                assert r.match("/user")
                assert r.match("/user/10")
        end
 
-       fun test_glob_route_work_with_parameters_1 do
+       fun test_glob_route_work_with_parameters_1 is test do
                var r = new AppGlobRoute("/:id/*")
                assert not r.match("/")
                assert r.match("/user")
@@ -141,14 +140,14 @@ class TestRouteMatching
                assert r.match("/user/10/profile")
        end
 
-       fun test_glob_route_work_with_parameters_2 do
+       fun test_glob_route_work_with_parameters_2 is test do
                var r = new AppGlobRoute("/:id*")
                assert not r.match("/")
                assert r.match("/user")
                assert r.match("/user/10")
        end
 
-       fun test_glob_route_work_with_parameters_3 do
+       fun test_glob_route_work_with_parameters_3 is test do
                var r = new AppGlobRoute("/user/:id/*")
                assert not r.match("/")
                assert not r.match("/user")
@@ -156,7 +155,7 @@ class TestRouteMatching
                assert r.match("/user/10/profile")
        end
 
-       fun test_glob_route_work_with_parameters_4 do
+       fun test_glob_route_work_with_parameters_4 is test do
                var r = new AppGlobRoute("/user/:id*")
                assert not r.match("/")
                assert not r.match("/user")
index 108eb7a..d2daed4 100644 (file)
@@ -14,7 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_popcorn is test_suite
+module test_popcorn is test
 
 import pop_tests
 import popcorn
@@ -29,6 +29,7 @@ end
 
 class TestPopcornRouter
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}"
@@ -44,7 +45,7 @@ class TestPopcornRouter
                system "curl -s {host}:{port}/products/not_found"
        end
 
-       fun test_router do
+       fun test_router is test do
                var app = new App
                app.use("/", new TestHandler("/"))
                app.use("/about", new TestHandler("/about"))
@@ -65,6 +66,7 @@ end
 
 class TestPopcornRoutes
        super TestPopcorn
+       test
 
        redef fun client_test do
                system "curl -s {host}:{port}"
@@ -84,7 +86,7 @@ class TestPopcornRoutes
                system "curl -s {host}:{port}/user/id/not_found"
        end
 
-       fun test_routes do
+       fun test_routes is test do
                var app = new App
                app.use("/", new TestHandler("/"))
                app.use("/user", new TestHandler("/user"))
index 27c98c4..12c7b57 100644 (file)
@@ -9,13 +9,12 @@
 # another product.
 
 # Test suite for `attributes_impl`.
-module test_attributes_impl is test_suite
+module test_attributes_impl is test
 
-import test_suite
 import sax::helpers::attributes_impl
 
 class TestAttributesImpl
-       super TestSuite
+       test
 
        private fun sample: AttributesImpl do
                var subject = new AttributesImpl
@@ -32,7 +31,7 @@ class TestAttributesImpl
                return subject
        end
 
-       fun test_length do
+       fun test_length is test do
                var subject = new AttributesImpl
 
                assert 0 == subject.length
@@ -47,7 +46,7 @@ class TestAttributesImpl
                assert 0 == subject.length
        end
 
-       fun test_uri do
+       fun test_uri is test do
                var subject = sample
 
                assert "http://example.com/" == subject.uri(0)
@@ -60,7 +59,7 @@ class TestAttributesImpl
                assert subject.uri(0) == null
        end
 
-       fun test_local_name do
+       fun test_local_name is test do
                var subject = sample
 
                assert "bar" == subject.local_name(0)
@@ -73,7 +72,7 @@ class TestAttributesImpl
                assert subject.local_name(0) == null
        end
 
-       fun test_qname do
+       fun test_qname is test do
                var subject = sample
 
                assert "foo:bar" == subject.qname(0)
@@ -86,7 +85,7 @@ class TestAttributesImpl
                assert subject.qname(0) == null
        end
 
-       fun test_type_of do
+       fun test_type_of is test do
                var subject = sample
 
                assert "CDATA" == subject.type_of(0)
@@ -99,7 +98,7 @@ class TestAttributesImpl
                assert subject.type_of(0) == null
        end
 
-       fun test_type_of_qname do
+       fun test_type_of_qname is test do
                var subject = sample
 
                assert "CDATA" == subject.type_of("foo:bar")
@@ -111,7 +110,7 @@ class TestAttributesImpl
                assert subject.type_of("xml:lang") == null
        end
 
-       fun test_value_of do
+       fun test_value_of is test do
                var subject = sample
 
                assert "baz" == subject.value_of(0)
@@ -124,7 +123,7 @@ class TestAttributesImpl
                assert subject.value_of(0) == null
        end
 
-       fun test_value_of_qname do
+       fun test_value_of_qname is test do
                var subject = sample
 
                assert "baz" == subject.value_of("foo:bar")
@@ -136,7 +135,7 @@ class TestAttributesImpl
                assert subject.value_of("xml:lang") == null
        end
 
-       fun test_index_ns do
+       fun test_index_ns is test do
                var subject = sample
 
                assert 0 == subject.index_ns("http://example.com/", "bar")
@@ -148,7 +147,7 @@ class TestAttributesImpl
                assert -1 == subject.index_ns("http://example.com/", "bar")
        end
 
-       fun test_index_of do
+       fun test_index_of is test do
                var subject = sample
 
                assert 0 == subject.index_of("foo:bar")
@@ -160,7 +159,7 @@ class TestAttributesImpl
                assert -1 == subject.index_of("foo:bar")
        end
 
-       fun test_type_ns do
+       fun test_type_ns is test do
                var subject = sample
 
                assert "CDATA" == subject.type_ns("http://example.com/", "bar")
@@ -172,7 +171,7 @@ class TestAttributesImpl
                assert subject.type_ns("http://example.com/", "bar") == null
        end
 
-       fun test_value_ns do
+       fun test_value_ns is test do
                var subject = sample
 
                assert "baz" == subject.value_ns("http://example.com/", "bar")
@@ -184,7 +183,7 @@ class TestAttributesImpl
                assert subject.value_ns("http://example.com/", "bar") == null
        end
 
-       fun test_attributes_set do
+       fun test_attributes_set is test do
                var subject = sample
                var subject2 = new AttributesImpl
 
@@ -195,7 +194,7 @@ class TestAttributesImpl
                assert subject.length == 4
        end
 
-       fun test_set do
+       fun test_set is test do
                var subject = sample
 
                subject.set(1, "urn:is:not:often:used", "i-am_ME", "i-am_ME", "ID",
@@ -205,7 +204,7 @@ class TestAttributesImpl
                assert "NMTOKENS" == subject.type_of(0)
        end
 
-       fun test_remove_at do
+       fun test_remove_at is test do
                var subject = sample
 
                subject.remove_at(1)
@@ -213,7 +212,7 @@ class TestAttributesImpl
                assert "xml:lang" == subject.qname(1)
        end
 
-       fun test_uri_set do
+       fun test_uri_set is test do
                var subject = sample
 
                subject.uri(0) = "https://example.org/serious"
@@ -222,7 +221,7 @@ class TestAttributesImpl
                assert "https://example.org/serious" == subject.uri(0)
        end
 
-       fun test_local_name_set do
+       fun test_local_name_set is test do
                var subject = sample
 
                subject.local_name(0) = "trololol"
@@ -231,7 +230,7 @@ class TestAttributesImpl
                assert "ImYou42" == subject.local_name(1)
        end
 
-       fun test_qname_set do
+       fun test_qname_set is test do
                var subject = sample
 
                subject.qname(0) = "go-to:bar"
@@ -240,7 +239,7 @@ class TestAttributesImpl
                assert "yo:i-am_ME" == subject.qname(1)
        end
 
-       fun test_type_of_set do
+       fun test_type_of_set is test do
                var subject = sample
 
                subject.type_of(0) = "NMTOKENS"
@@ -249,7 +248,7 @@ class TestAttributesImpl
                assert "ENTITY" == subject.type_of(1)
        end
 
-       fun test_value_of_set do
+       fun test_value_of_set is test do
                var subject = sample
 
                subject.value_of(0) = "buz"
index 3892e12..ed25c75 100644 (file)
@@ -9,13 +9,12 @@
 # another product.
 
 # Test suite for `namespace_support`.
-module test_namespace_support is test_suite
+module test_namespace_support is test
 
-import test_suite
 import sax::helpers::namespace_support
 
 class TestNamespaceSupport
-       super TestSuite
+       test
 
        private fun sample: NamespaceSupport do
                var subject = new NamespaceSupport
@@ -26,7 +25,7 @@ class TestNamespaceSupport
                return subject
        end
 
-       fun test_reset do
+       fun test_reset is test do
                var subject = sample
 
                subject.reset
@@ -37,7 +36,7 @@ class TestNamespaceSupport
                assert 2 == subject.prefixes.length
        end
 
-       fun test_push_context_override_default do
+       fun test_push_context_override_default is test do
                var subject = sample
 
                subject.push_context
@@ -51,7 +50,7 @@ class TestNamespaceSupport
                assert 3 == subject.prefixes.length
        end
 
-       fun test_push_context_override_dc do
+       fun test_push_context_override_dc is test do
                var subject = sample
 
                subject.push_context
@@ -64,7 +63,7 @@ class TestNamespaceSupport
                assert 3 == subject.prefixes.length
        end
 
-       fun test_push_context_undeclare do
+       fun test_push_context_undeclare is test do
                var subject = sample
 
                subject.push_context
@@ -74,7 +73,7 @@ class TestNamespaceSupport
                assert 2 == subject.prefixes.length
        end
 
-       fun test_pop_context do
+       fun test_pop_context is test do
                var subject = sample
 
                subject.pop_context
@@ -86,7 +85,7 @@ class TestNamespaceSupport
 
        #fun test_declare_prefix # SEE: test_push_context_*
 
-       fun test_process_name do
+       fun test_process_name is test do
                var subject = sample
                var parts = new Array[String]
 
@@ -104,7 +103,7 @@ class TestNamespaceSupport
                assert ["", "p", "p"] == subject.process_name("p", parts, true)
        end
 
-       fun test_process_name_xmlns do
+       fun test_process_name_xmlns is test do
                var subject = sample
                var parts = new Array[String].with_capacity(3)
 
@@ -112,7 +111,7 @@ class TestNamespaceSupport
                assert ["http://www.w3.org/1999/xhtml", "xmlns", "xmlns"] == subject.process_name("xmlns", parts, false)
        end
 
-       fun test_declare_prefix_illegal do
+       fun test_declare_prefix_illegal is test do
                var subject = sample
 
                assert not subject.declare_prefix("xml", "http://example.org")
@@ -122,7 +121,7 @@ class TestNamespaceSupport
                assert 2 == subject.declared_prefixes.length
        end
 
-       fun test_uri do
+       fun test_uri is test do
                var subject = sample
 
                assert "http://www.w3.org/1999/xhtml" == subject.uri("")
@@ -131,7 +130,7 @@ class TestNamespaceSupport
                assert subject.uri("foo") == null
        end
 
-       fun test_prefixes do
+       fun test_prefixes is test do
                var res = sample.prefixes
 
                assert 3 == res.length else
@@ -142,7 +141,7 @@ class TestNamespaceSupport
                assert res.has("xmlns")
        end
 
-       fun test_prefix do
+       fun test_prefix is test do
                var subject = sample
 
                assert subject.prefix("http://www.w3.org/1999/xhtml") == null
@@ -151,7 +150,7 @@ class TestNamespaceSupport
                assert subject.prefix("https://example.org/serious") == null
        end
 
-       fun test_prefixes_of do
+       fun test_prefixes_of is test do
                var subject = sample
                var res: Collection[String]
 
@@ -169,7 +168,7 @@ class TestNamespaceSupport
                assert res.has_all(["dc", "dc2"])
        end
 
-       fun test_declared_prefixes do
+       fun test_declared_prefixes is test do
                var res = sample.declared_prefixes
 
                assert 2 == res.length else
index c4afbbf..98ddc26 100644 (file)
@@ -9,7 +9,7 @@
 # another product.
 
 # Tests for SAXophoNit
-module test_saxophonit is test_suite
+module test_saxophonit is test
 
 import sax::helpers::sax_locator_impl
 import sax::helpers::attributes_impl
@@ -18,10 +18,11 @@ import saxophonit::testing
 
 class TestSaxophonit
        super SAXTestSuite
+       test
 
        redef fun create_reader do return new XophonReader
 
-       fun test_empty do
+       fun test_empty is test do
                before_test
                parse_string("<foo />")
                expected.document_locator = new SAXLocatorImpl
@@ -32,7 +33,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_simple_element do
+       fun test_simple_element is test do
                before_test
                parse_string("<foo>bar</foo>")
                expected.document_locator = new SAXLocatorImpl
@@ -44,7 +45,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_type_mismatch do
+       fun test_type_mismatch is test do
                before_test
                parse_string("<a></b>")
                expected.document_locator = new SAXLocatorImpl
@@ -57,7 +58,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_attributes do
+       fun test_attributes is test do
                var atts = new AttributesImpl
 
                before_test
@@ -72,7 +73,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_nested do
+       fun test_nested is test do
                var atts = new AttributesImpl
 
                before_test
@@ -90,7 +91,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_xmldecl do
+       fun test_xmldecl is test do
                before_test
                parse_string("<?xml version='1.0'?><foo />")
                expected.document_locator = new SAXLocatorImpl
@@ -101,7 +102,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_xmldecl_encoding do
+       fun test_xmldecl_encoding is test do
                before_test
                parse_string("<?xml version=\"1.0\" encoding='utf-8'?><foo />")
                expected.document_locator = new SAXLocatorImpl
@@ -112,7 +113,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_xmldecl_standalone do
+       fun test_xmldecl_standalone is test do
                before_test
                parse_string("<?xml version='1.0' standalone=\"yes\"?><foo />")
                expected.document_locator = new SAXLocatorImpl
@@ -123,7 +124,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_xmldecl_both do
+       fun test_xmldecl_both is test do
                before_test
                parse_string("<?xml version='1.0' encoding='utf-8' standalone=\"yes\"?><foo />")
                expected.document_locator = new SAXLocatorImpl
@@ -134,7 +135,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_reference_builtin do
+       fun test_reference_builtin is test do
                before_test
                parse_string("<foo>&amp;&quot;&apos;&lt;&gt;&#48;&#x30;&#x03A;</foo>")
                expected.document_locator = new SAXLocatorImpl
@@ -153,7 +154,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_comments do
+       fun test_comments is test do
                # TODO For the moment, comments are simply ignored.
                before_test
                parse_string("<!-- I--><foo>bar<!--l-i-k-e--></foo><!--comments    -->")
@@ -166,7 +167,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_ns_simple do
+       fun test_ns_simple is test do
                before_test
                parse_string("<foo:bar xmlns:foo='https://s.exemple.org' />")
                expected.document_locator = new SAXLocatorImpl
@@ -178,7 +179,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_ns_prefix do
+       fun test_ns_prefix is test do
                var atts = new AttributesImpl
 
                before_test
@@ -194,7 +195,7 @@ class TestSaxophonit
                assert_equals
        end
 
-       fun test_mixed do
+       fun test_mixed is test do
                var atts = new AttributesImpl
 
                # TODO For the moment, ignorable white space is not detected.
index c2ace75..c9c7fc1 100644 (file)
@@ -9,13 +9,12 @@
 # another product.
 
 # Test suite for `testing`.
-module test_testing is test_suite
+module test_testing is test
 
 import saxophonit::testing
-import test_suite
 
 class TestSaxEventLogger
-       super TestSuite
+       test
 
        # Constants for diff formatting.
 
@@ -40,8 +39,7 @@ class TestSaxEventLogger
 
        private var init_done: Bool = false
 
-       redef fun before_test do
-               super
+       fun before_test is before do
                if not init_done then
                        default = a.term_default
                        ins = a.term_insertion
@@ -64,19 +62,19 @@ class TestSaxEventLogger
                end
        end
 
-       fun test_diff_empty do
+       fun test_diff_empty is test do
                assert "" == a.diff(b).to_s
                assert "" == b.diff(a).to_s
        end
 
-       fun test_diff_equal1 do
+       fun test_diff_equal1 is test do
                b.start_document
                a.start_document
                assert "" == a.diff(b).to_s
                assert "" == b.diff(a).to_s
        end
 
-       fun test_diff_equal2 do
+       fun test_diff_equal2 is test do
                b.start_document
                b.end_document
                a.start_document
@@ -85,7 +83,7 @@ class TestSaxEventLogger
                assert "" == b.diff(a).to_s
        end
 
-       fun test_diff_insertion do
+       fun test_diff_insertion is test do
                var exp: String
                var test: String
 
@@ -115,7 +113,7 @@ class TestSaxEventLogger
                assert_equals(2, exp, test)
        end
 
-       fun test_diff_edition do
+       fun test_diff_edition is test do
                var exp: String
                var test: String
 
index cc69c83..a5af113 100644 (file)
@@ -17,7 +17,6 @@ import sax::helpers::xml_filter_impl
 import sax::ext::decl_handler
 import sax::ext::lexical_handler
 import console
-import test_suite
 
 # A filter that internally log events it recieves.
 #
@@ -532,7 +531,6 @@ end
 
 # Base class for test suites on a SAX reader.
 abstract class SAXTestSuite
-       super TestSuite
 
        # Logger of the expected event sequence.
        var expected = new SAXEventLogger
@@ -545,8 +543,7 @@ abstract class SAXTestSuite
 
        private var init_done: Bool = false
 
-       redef fun before_test do
-               super
+       fun before_test is before do
                if not init_done then
                        reader = create_reader
                        actual.parent = reader
index b2854e6..c6cd512 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_macro is test_suite
+module test_macro is test
 
-import test_suite
 import macro
 
 class TestTemplateString
-       super TestSuite
+       test
 
-       fun test_tpl_parse_1 do
+       fun test_tpl_parse_1 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -37,7 +36,7 @@ class TestTemplateString
                assert res == tpl
        end
 
-       fun test_tpl_parse_2 do
+       fun test_tpl_parse_2 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -54,7 +53,7 @@ class TestTemplateString
                assert res == tpl
        end
 
-       fun test_tpl_parse_3 do
+       fun test_tpl_parse_3 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -67,7 +66,7 @@ class TestTemplateString
                assert res == tpl
        end
 
-       fun test_tpl_parse_4 do
+       fun test_tpl_parse_4 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -83,7 +82,7 @@ class TestTemplateString
                assert res == tpl
        end
 
-       fun test_tpl_parse_5 do
+       fun test_tpl_parse_5 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -100,7 +99,7 @@ class TestTemplateString
                assert res == tpl
        end
 
-       fun test_tpl_parse_6 do
+       fun test_tpl_parse_6 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -116,7 +115,7 @@ class TestTemplateString
                assert res == tpl
        end
 
-       fun test_tpl_replace_1 do
+       fun test_tpl_replace_1 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -145,7 +144,7 @@ class TestTemplateString
                assert res == exp
        end
 
-       fun test_tpl_replace_2 do
+       fun test_tpl_replace_2 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
@@ -175,7 +174,7 @@ class TestTemplateString
                assert res == exp
        end
 
-       fun test_tpl_replace_3 do
+       fun test_tpl_replace_3 is test do
                var tpl = """
 <!DOCTYPE html>
 <html lang="en">
diff --git a/lib/test_suite.ini b/lib/test_suite.ini
deleted file mode 100644 (file)
index a32a29c..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-[package]
-name=test_suite
-tags=devel,lib
-maintainer=Alexandre Terrasa <alexandre@moz-code.org>
-license=Apache-2.0
-[upstream]
-browse=https://github.com/nitlang/nit/tree/master/lib/test_suite.nit
-git=https://github.com/nitlang/nit.git
-git.directory=lib/test_suite.nit
-homepage=http://nitlanguage.org
-issues=https://github.com/nitlang/nit/issues
diff --git a/lib/test_suite.nit b/lib/test_suite.nit
deleted file mode 100644 (file)
index e7b6f3a..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-# This file is part of NIT ( http://www.nitlanguage.org ).
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Common interface for `nitunit` test-suites.
-module test_suite is
-       # Annotation used by test-suite modules.
-       new_annotation test_suite
-end
-
-# A test-suite that can be executed by `nitunit`.
-#
-# All test-suite classes must implement `TestSuite`.
-class TestSuite
-       # Internal empty init.
-       private init nitunit do end
-
-       # Method called before each test-case.
-       #
-       # Redefine this method to factorize code that have to be
-       # executed before every test.
-       fun before_test do end
-
-       # Method called after each test-case.
-       #
-       # Redefine this method to factorize code that have to be
-       # executed after every test.
-       fun after_test do end
-end
-
-redef class Sys
-       # Internal empty init.
-       private init nitunit do end
-
-       # No before test for the module
-       private fun before_test do end
-
-       # No after test for the module
-       private fun after_test do end
-
-       # Method called before each test-suite.
-       #
-       # Redefine this method to factorize code that have to be
-       # executed before every test suite.
-       fun before_module do end
-
-       # Method called after each test-suite.
-       #
-       # Redefine this method to factorize code that have to be
-       # executed after every test suite.
-       fun after_module do end
-end
diff --git a/lib/vsm/README.md b/lib/vsm/README.md
new file mode 100644 (file)
index 0000000..ea50132
--- /dev/null
@@ -0,0 +1,103 @@
+# Vector Space Model
+
+Vector Space Model (VSM) is an algebraic model for representing text documents
+(and any objects, in general) as vectors of identifiers, such as, for example,
+index terms.
+
+It is used in information filtering, information retrieval, indexing and
+relevancy rankings.
+
+The `vsm` package provides the following features:
+* Vector comparison with cosine similarity.
+* Vector indexing and matching with tf * idf.
+* File indexing and matching to free text queries.
+
+## Vectors
+
+With VSM, documents are represented by a n-dimensions vector.
+Each dimension represent an attribute of the document or object.
+
+For text document, the count of each term found in the document if often used to
+build vectors.
+
+### Creating a vector
+
+~~~
+var vector = new Vector
+vector["term1"] = 2.0
+vector["term2"] = 1.0
+assert vector["term1"] == 2.0
+assert vector["term2"] == 1.0
+assert vector.norm.is_approx(2.236, 0.001)
+~~~
+
+### Comparing vectors
+
+~~~
+var v1 = new Vector
+v1["term1"] = 1.0
+v1["term2"] = 2.0
+
+var v2 = new Vector
+v2["term2"] = 1.0
+v2["term3"] = 3.0
+
+var query = new Vector
+query["term2"] = 1.0
+
+var s1 = query.cosine_similarity(v1)
+var s2 = query.cosine_similarity(v2)
+assert s1 > s2
+~~~
+
+## VSMIndex
+
+VSMIndex is a Document index based on VSM.
+
+Using VSMIndex you can index documents associated with their vector.
+Documents can then be matched to query vectors.
+
+This represents a minimalistic search engine.
+
+~~~
+var index = new VSMIndex
+
+var d1 = new Document("Doc 1", "/uri/1", v1)
+index.index_document(d1)
+
+var d2 = new Document("Doc 2", "/uri/2", v2)
+index.index_document(d2)
+
+assert index.documents.length == 2
+
+query = new Vector
+query["term1"] = 1.0
+
+var matches = index.match_vector(query)
+assert matches.first.document == d1
+~~~
+
+## StringIndex
+
+The StringIndex provides usefull services to index and match strings.
+
+~~~
+index = new StringIndex
+
+d1 = index.index_string("Doc 1", "/uri/1", "this is a sample")
+d2 = index.index_string("Doc 2", "/uri/2", "this and this is another example")
+assert index.documents.length == 2
+
+matches = index.match_string("this sample")
+assert matches.first.document == d1
+~~~
+
+## FileIndex
+
+The FileIndex is a StringIndex able to index and retrieve files.
+
+~~~nit
+index = new FileIndex
+
+index.index_files(["/path/to/doc/1", "/path/to/doc/2"])
+~~~
diff --git a/lib/vsm/examples/example_vsm.nit b/lib/vsm/examples/example_vsm.nit
new file mode 100644 (file)
index 0000000..5f1192b
--- /dev/null
@@ -0,0 +1,65 @@
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Example using a `FileIndex`
+#
+# This example shows of to index files from the system and retrieve them
+# with text queries.
+module example_vsm
+
+import vsm
+import config
+
+redef class Config
+
+       # --whitelist-exts
+       var opt_white_exts = new OptionArray("Allowed file extensions (default is [])",
+               "-w", "--whitelist-exts")
+
+       # --blacklist-exts
+       var opt_black_exts = new OptionArray("Allowed file extensions (default is [])",
+               "-b", "--blacklist-exts")
+
+       redef init do
+               opts.add_option(opt_white_exts, opt_black_exts)
+       end
+end
+
+var config = new Config
+config.tool_description = "usage: example_vsm <files>"
+config.parse_options(args)
+
+if args.length < 1 then
+       config.usage
+       exit 1
+end
+
+var index = new FileIndex
+index.whitelist_exts = config.opt_white_exts.value
+index.blacklist_exts = config.opt_black_exts.value
+
+print "Building index..."
+index.index_files(args, true)
+print "Indexed {index.documents.length} documents"
+
+loop
+       print "\nEnter query:"
+       printn "> "
+       var input = sys.stdin.read_line
+       var matches = index.match_string(input)
+       printn ""
+       for match in matches do
+               print match
+       end
+end
diff --git a/lib/vsm/vsm.nit b/lib/vsm/vsm.nit
new file mode 100644 (file)
index 0000000..41d5152
--- /dev/null
@@ -0,0 +1,374 @@
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Vector Space Model
+#
+# Vector Space Model (VSM) is an algebraic model for representing text documents
+# (and any objects, in general) as vectors of identifiers, such as, for example,
+# index terms.
+#
+# It is used in information filtering, information retrieval, indexing and
+# relevancy rankings.
+module vsm
+
+import counter
+
+# A n-dimensions vector
+#
+# *n-dimensions* vectors are used to represent a text document or an object.
+class Vector
+       super HashMap[nullable Object, Float]
+
+       # Cosine similarity of `self` and `other`.
+       #
+       # Gives the proximity in the range `[0.0 .. 1.0]` where 0.0 means that the
+       # two vectors are orthogonal and 1.0 means that they are identical.
+       #
+       # ~~~
+       # var v1 = new Vector
+       # v1["x"] = 1.0
+       # v1["y"] = 2.0
+       # v1["z"] = 3.0
+       #
+       # var v2 = new Vector
+       # v2["x"] = 1.0
+       # v2["y"] = 2.0
+       # v2["z"] = 3.0
+       #
+       # var v3 = new Vector
+       # v3["a"] = 1.0
+       # v3["b"] = 2.0
+       # v3["c"] = 3.0
+       #
+       # print v1.cosine_similarity(v2)
+       # assert v1.cosine_similarity(v2) == 1.0
+       # print v1.cosine_similarity(v3)
+       # assert v1.cosine_similarity(v3) == 0.0
+       # ~~~
+       fun cosine_similarity(other: SELF): Float do
+               # Collect terms
+               var terms = new HashSet[nullable Object]
+               for k in self.keys do terms.add k
+               for k in other.keys do terms.add k
+
+               # Get dot product of two vectors
+               var dot = 0.0
+               for term in terms do
+                       dot += self.get_or_default(term, 0.0) * other.get_or_default(term, 0.0)
+               end
+               var cos = dot.to_f / (self.norm * other.norm)
+               if cos.is_nan then return 0.0
+               return cos
+       end
+
+       # The norm of the vector.
+       #
+       # `||x|| = (x1 ** 2 ... + xn ** 2).sqrt`
+       #
+       # ~~~
+       # var v = new Vector
+       # v["x"] = 1.0
+       # v["y"] = 1.0
+       # v["z"] = 1.0
+       # v["t"] = 1.0
+       # assert v.norm.is_approx(2.0, 0.001)
+       #
+       # v["x"] = 1.0
+       # v["y"] = 2.0
+       # v["z"] = 3.0
+       # v["t"] = 0.0
+       # assert v.norm.is_approx(3.742, 0.001)
+       # ~~~
+       fun norm: Float do
+               var sum = 0.0
+               for v in self.values do sum += v.pow(2.0)
+               return sum.to_f.sqrt
+       end
+
+       redef fun to_s do
+               return "[{join(", ", ":")}]"
+       end
+end
+
+# A Document index based on VSM
+#
+# Using VSMIndex you can index documents associated with their vector.
+# Documents can then be matched to query vectors.
+class VSMIndex
+
+       # Documents index
+       #
+       # TODO use a more efficient representation.
+       var documents = new HashSet[Document]
+
+       # Count for all terms in all indexed documents
+       #
+       # Used to compute the `inverse_doc_frequency`.
+       var terms_doc_count = new Vector
+
+       # Inverse document frequency
+       #
+       # The inverse document frequency is a measure of how much information a term
+       # provides, that is, whether the term is common or rare across all documents.
+       var inverse_doc_frequency = new Vector
+
+       # Used to sort matches
+       #
+       # See `IndexMatch`.
+       var sorter = new IndexMatchSorter
+
+       # Match `query` vector to all index document vectors
+       #
+       # Returns an `IndexMatch` for each indexed document.
+       # Results are ordered by descending similarity.
+       fun match_vector(query: Vector): Array[IndexMatch] do
+               var matches = new Array[IndexMatch]
+               for doc in documents do
+                       var sim = query.cosine_similarity(doc.tfidf)
+                       if sim == 0.0 then continue
+                       matches.add new IndexMatch(doc, sim)
+               end
+               sorter.sort(matches)
+               return matches
+       end
+
+       # Index a document
+       #
+       # With each new document, the `inverse_doc_frequency` must be updated.
+       # By default, the method `update_index` is called after each call to
+       # `index_document`.
+       #
+       # When processing batch documents, use `auto_update = false` to disable
+       # the auto update of the index.
+       fun index_document(doc: Document, auto_update: nullable Bool) do
+               for term, count in doc.terms_count do
+                       if not terms_doc_count.has_key(term) then
+                               terms_doc_count[term] = 1.0
+                       else
+                               terms_doc_count[term] += 1.0
+                       end
+               end
+               documents.add doc
+               if auto_update == null or auto_update then update_index
+       end
+
+       # Update the index
+       #
+       # Recompute the `inverse_doc_frequency` values.
+       # Must be called manually after indexing new document with the option
+       # `auto_update = false`.
+       fun update_index do
+               for doc in documents do
+                       for term, ccount in doc.terms_count do
+                               inverse_doc_frequency[term] = (documents.length.to_f / terms_doc_count[term]).log
+                       end
+               end
+               for doc in documents do
+                       for term, freq in doc.terms_frequency do
+                               doc.tfidf[term] = freq * inverse_doc_frequency[term]
+                       end
+               end
+       end
+end
+
+# A VSM index to store strings
+class StringIndex
+       super VSMIndex
+
+       # Index a new Document from `title`, `uri` and string `string`.
+       #
+       # Return the Document created.
+       #
+       # See `index_document`.
+       fun index_string(title, uri, string: String, auto_update: nullable Bool): Document do
+               var vector = parse_string(string)
+               var doc = new Document(title, uri, vector)
+               index_document(doc, auto_update)
+               return doc
+       end
+
+       # Match the `query` string against all indexed documents
+       #
+       # See `match_vector`.
+       fun match_string(query: String): Array[IndexMatch] do
+               var vector = parse_string(query)
+               return match_vector(vector)
+       end
+
+       # Parse the `string` as a Vector
+       #
+       # Returns a vector containing the terms of `string`.
+       fun parse_string(string: String): Vector do
+               var reader = new StringReader(string)
+               var vector = new Vector
+               loop
+                       var token = reader.read_word
+                       if token == "" then break
+
+                       if not vector.has_key(token) then
+                               vector[token] = 1.0
+                       else
+                               vector[token] += 1.0
+                       end
+               end
+               return vector
+       end
+end
+
+# A VSMIndex to index files
+class FileIndex
+       super StringIndex
+
+       # Index a file from its `path`.
+       #
+       # Return the created document or null if `path` is not accepted by `accept_file`.
+       #
+       # See `index_document`.
+       fun index_file(path: String, auto_update: nullable Bool): nullable Document do
+               if not accept_file(path) then return null
+               var vector = parse_file(path)
+               var doc = new Document(path, path, vector)
+               index_document(doc, auto_update)
+               return doc
+       end
+
+       # Index multiple files
+       #
+       # The recursive method `index_dir` will be called for each directory found
+       # in `paths`.
+       #
+       # See `index_file`
+       fun index_files(paths: Collection[String], auto_update: nullable Bool) do
+               for path in paths do
+                       if path.to_path.is_dir then
+                               index_dir(path, false)
+                       else
+                               index_file(path, false)
+                       end
+               end
+               if auto_update != null and auto_update then update_index
+       end
+
+       # Index all files in `dir` recursively
+       #
+       # See `index_file`.
+       fun index_dir(dir: String, auto_update: nullable Bool) do
+               if not dir.to_path.is_dir then return
+               for file in dir.files do
+                       var path = dir / file
+                       if path.to_path.is_dir then
+                               index_dir(path, false)
+                       else
+                               index_file(path, false)
+                       end
+               end
+               if auto_update != null and auto_update then update_index
+       end
+
+       # Is `path` accepted depending on `whitelist_exts` and `blacklist_exts`?
+       fun accept_file(path: String): Bool do
+               var ext = path.file_extension
+               if ext != null then
+                       ext = ext.to_lower
+                       if blacklist_exts.has(ext) then return false
+                       if whitelist_exts.not_empty and not whitelist_exts.has(ext) then return false
+               end
+               return whitelist_exts.is_empty
+       end
+
+       # Parse the `file` content as a Vector
+       #
+       # See `parse_string`.
+       fun parse_file(file: String): Vector do
+               return parse_string(file.to_path.read_all)
+       end
+
+       # File extensions white list
+       #
+       # If not empty, only files with these extensions will be indexed.
+       #
+       # If an extension is in both `whitelist_exts` and `blacklist_exts`, the
+       # blacklist will prevail and the file will be ignored.
+       var whitelist_exts = new Array[String] is writable
+
+       # File extensions black list
+       #
+       # Files with these extensions will not be indexed.
+       var blacklist_exts = new Array[String] is writable
+end
+
+# A Document to add in a VSMIndex
+class Document
+
+       # Document title
+       var title: String
+
+       # Document URI
+       var uri: String
+
+       # Count of all terms found in the document
+       #
+       # Used to compute the document `terms_frequency`.
+       var terms_count: Vector
+
+       # Frequency of each term found in the document
+       #
+       # Used to match the document against the `VSMIndex::inverse_doc_frequency`.
+       var terms_frequency: Vector is lazy do
+               var all_terms = 0.0
+               for t, c in terms_count do all_terms += c
+
+               var vector = new Vector
+               for t, c in terms_count do
+                       vector[t] = c / all_terms
+               end
+               return vector
+       end
+
+       # Term frequency–Inverse document frequency for each term
+       #
+       # A high weight in tf–idf is reached by a high term frequency
+       # (in the given document) and a low document frequency of the term in the
+       # whole collection of documents
+       var tfidf = new Vector
+
+       redef fun to_s do return "{title}"
+end
+
+# A match to a `request` in an `Index`
+class IndexMatch
+       super Comparable
+
+       # Document matching the `request_vector`
+       var document: Document
+
+       # Similarity between the `request` and the `doc`.
+       #
+       # Result is in the range 0.0 .. 1.1 where 0.0 means no similarity and 1.0
+       # means perfect similarity.
+       var similarity: Float
+
+       redef fun to_s do return "{document} ({similarity})"
+end
+
+# Sort matches by similarity
+class IndexMatchSorter
+       super DefaultComparator
+
+       redef type COMPARED: IndexMatch
+
+       redef fun compare(a, b) do
+               return b.similarity <=> a.similarity
+       end
+end
index 0ab13a5..2263bd3 100644 (file)
@@ -131,25 +131,24 @@ This flag can be used by libraries and program to prevent (or limit) the executi
 
 TestSuites are Nit modules that define a set of TestCases.
 
-A test suite is a module that uses the annotation `is test_suite`.
+A test suite is a module that uses the annotation `is test`.
 
 It is common that a test suite focuses on testing a single module.
-In this case, the name of the test_suite is often `test_foo.nit` where `foo.nit` is the tested module.
+In this case, the name of the test suite is often `test_foo.nit` where `foo.nit` is the tested module.
 
 The structure of a test suite is the following:
 
 ~~~~
 # test suite for module `foo`
-module test_foo is test_suite
+module test_foo is test
 
-import test_suite
 import foo # can be intrude to test private things
 
 class TestFoo
-       super TestSuite
+    test
 
     # test case for `foo::Foo::baz`
-    fun test_baz do
+    fun baz is test do
         var subject = new Foo
         assert subject.baz(1, 2) == 3
     end
@@ -160,18 +159,18 @@ Test suite can be executed using the same `nitunit` command:
 
     $ nitunit foo.nit
 
-`nitunit` will execute a test for each method named `test_*` in a class
-subclassing `TestSuite` so multiple tests can be executed for a single method:
+`nitunit` will execute a test for each method with the `test` annotation in a class
+also annotated with `test` so multiple tests can be executed for a single method:
 
 ~~~~
 class TestFoo
-       super TestSuite
+    test
 
-    fun test_baz_1 do
+    fun baz_1 is test do
         var subject = new Foo
         assert subject.baz(1, 2) == 3
     end
-    fun test_baz_2 do
+    fun baz_2 is test do
         var subject = new Foo
         assert subject.baz(1, -2) == -1
     end
@@ -204,12 +203,12 @@ The `diff(1)` command is used to perform the comparison.
 The test is failed if non-zero is returned by `diff`.
 
 ~~~
-module test_mod is test_suite
+module test_mod is test
 
 class TestFoo
-       super TestSuite
+       test
 
-       fun test_bar do
+       fun bar is test do
                print "Hello!"
        end
 end
@@ -228,25 +227,27 @@ To helps the management of the expected results, the option `--autosav` can be u
 
 ## Configuring TestSuites
 
-`TestSuite`s also provide methods to configure the test run:
-
-`before_test` and `after_test`: methods called before/after each test case.
+`TestSuite`s also provide annotations to configure the test run:
+`before` and `after` annotations can be applied to methods that must be called before/after each test case.
 They can be used to factorize repetitive tasks:
 
 ~~~~
 class TestFoo
-       super TestSuite
+    test
+
     var subject: Foo
+
     # Mandatory empty init
     init do end
+
     # Method executed before each test
-    fun before_test do
+    fun set_up is before do
         subject = new Foo
     end
-    fun test_baz_1 do
+    fun baz_1 is test do
         assert subject.baz(1, 2) == 3
     end
-    fun test_baz_2 do
+    fun baz_2 is test do
         assert subject.baz(1, -2) == -1
     end
 end
@@ -254,7 +255,7 @@ end
 
 When using custom test attributes, an empty `init` must be declared to allow automatic test running.
 
-`before_module` and `after_module`: methods called before/after each test suite.
+`before_all` and `after_all` annotations can be applied to methods that must be called before/after each test suite.
 They have to be declared at top level:
 
 ~~~~
@@ -279,11 +280,11 @@ end
 The `NIT_TESTING_PATH` environment variable contains the current test suite
 file path.
 Nitunit define this variable before the execution of each test suite.
-It can be used to access files based on the current test_suite location:
+It can be used to access files based on the current test suite location:
 
 ~~~
 class TestWithPath
-       super TestSuite
+    test
 
     fun test_suite_path do
         assert "NIT_TESTING_PATH".environ != ""
diff --git a/share/nitweb/directives/contributor-list.html b/share/nitweb/directives/contributor-list.html
deleted file mode 100644 (file)
index a46cce9..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<div ng-if='listContributors.length > 0'>
-       <h3 id={{listId}}>
-               <span>{{listTitle}}</span>
-       </h3>
-       <ul class='list-unstyled user-list'>
-               <li ng-repeat='contributor in listContributors'>
-                       <img class='avatar' src="https://secure.gravatar.com/avatar/{{contributor.hash}}?size=20&amp;default=retro">
-                       {{contributor.name}}
-               </li>
-       </ul>
-</div>
index 0b48c22..18675a0 100644 (file)
@@ -1,35 +1,35 @@
 <div class='card'>
-       <div class='card-left text-center' ng-if='!noSynopsis'>
+       <div class='card-left text-center'>
                <entity-tag mentity='mentity' />
        </div>
-       <div class='card-body'>
-               <h5 class='card-heading' ng-if='!noSynopsis'>
-                       <entity-signature mentity='mentity'/>
+       <div class='card-body' ng-if='mentity.class_name == "MPackage"' style='width: 75%'>
+               <h5 class='card-heading'>
+                       <entity-signature mentity='mentity' />
+                       <small ng-if='mentity.class_name == "MPackage"'>
+                               <span ng-repeat='tag in mentity.metadata.tags'>
+                                       <a ui-sref='tag({id: tag})' class='text-muted'>{{tag}}</a>
+                                       <span ng-if='!$last'>,</span>
+                               </span>
+                       </small>
                </h5>
-               <div class='tab-content'>
-                       <div id='{{mentity.html_id}}-signature' class='tab-pane' ng-if='!noSynopsis'
-                         ng-class='currentTab == "signature" ? "active" : ""'>
-                               <span class='synopsis' ng-bind-html='mentity.mdoc.html_synopsis' />
-                       </div>
-                       <div id='{{mentity.html_id}}-grade' class='tab-pane'
-                         ng-class='currentTab == "grade" ? "active" : ""'>
-                               <entity-rating mentity='mentity' ratings='ratings'>
-                       </div>
-               </div>
+               <span class='synopsis' ng-bind-html='mentity.mdoc.html_synopsis' />
        </div>
-       <div class='card-right'>
-               <div class='dropdown'>
-                       <button class='btn btn-link dropdown-toggle' type='button' data-toggle='dropdown'>
-                               <span class='glyphicon glyphicon-chevron-down'></span>
-                       </button>
-                       <ul class='dropdown-menu dropdown-menu-right'>
-                               <li ng-class='currentTab == "signature" ? "active" : ""' ng-if='!noSynopsis'>
-                                       <a ng-click='currentTab = "signature"'>Signature</a>
-                               </li>
-                               <li ng-class='currentTab == "grade" ? "active" : ""'>
-                                       <a ng-click='loadEntityStars(); currentTab = "grade"'>Grade</a>
-                               </li>
-                       </ul>
-               </div>
+       <div class='card-body' ng-if='mentity.class_name != "MPackage"'>
+               <h5 class='card-heading'>
+                       <entity-signature mentity='mentity' />
+               </h5>
+               <span class='synopsis' ng-bind-html='mentity.mdoc.html_synopsis' />
+       </div>
+       <div class='card-right' ng-if='mentity.class_name == "MPackage"' style='width: 25%'>
+               <span ng-repeat='maintainer in mentity.metadata.maintainers'>
+                       <img class='avatar' src='https://secure.gravatar.com/avatar/{{maintainer.gravatar}}?size=14&amp;default=retro' />
+                       <a ui-sref='person({id: maintainer.name})'>{{maintainer.name}}</a>
+               </span>
+               <br>
+               <span ng-if='mentity.metadata.license'>
+                       <span class='text-muted'>
+                               <a href='http://opensource.org/licenses/{{mentity.license}}' class='text-muted'>{{mentity.metadata.license}}</a>
+                       </span>
+               </span>
        </div>
 </div>
diff --git a/share/nitweb/directives/search/card.html b/share/nitweb/directives/search/card.html
deleted file mode 100644 (file)
index 7052c60..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<div class='card card-search'>
-       <div class='card-left text-center'>
-               <entity-tag mentity='mentity' />
-       </div>
-       <div class='card-body'>
-               <h5 class='card-heading'>
-                       <entity-signature mentity='mentity'/>
-                       <br>
-                       <small><entity-namespace namespace='mentity.namespace' /></small>
-               </h5>
-               <span class='synopsis' ng-bind-html='mentity.mdoc.html_synopsis' />
-       </div>
-</div>
diff --git a/share/nitweb/directives/search/field.html b/share/nitweb/directives/search/field.html
deleted file mode 100644 (file)
index d9ee5f1..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<form>
-       <div class='form-group has-icon'>
-               <input placeholder='Search...' type='text' class='form-control search-input'
-                       ng-model-options='{ debounce: 300 }' ng-model='query'
-                       ng-keydown='update($event)' ng-change='search()'>
-               <span class='glyphicon glyphicon-search form-control-icon text-muted'></span>
-       </div>
-       <div ng-if='results.length > 0' class='search-results'>
-               <div class='card-list'>
-                       <search-card ng-click='selectEnter()' ng-class='{active: activeItem == $index}' ng-mouseover='setActive($index)' mentity='mentity' ng-repeat='mentity in results' />
-               </div>
-       </div>
-</form>
diff --git a/share/nitweb/directives/ui/pagination.html b/share/nitweb/directives/ui/pagination.html
new file mode 100644 (file)
index 0000000..4af87d2
--- /dev/null
@@ -0,0 +1,14 @@
+<nav>
+       <ul class='pagination' ng-if='pagination.pagination.max > 1'>
+               <li ng-class='{disabled: pagination.pagination.page <= 1}'>
+                       <a ng-click='pagination.changePage(pagination.pagination.page - 1, pagination.pagination.limit)'><span>&laquo;</span></a>
+               </li>
+               <li ng-repeat='page in pagination.pages'
+                       ng-class='{disabled: pagination.pagination.page == page}'>
+                       <a ng-click='pagination.changePage(page, pagination.pagination.limit)'>{{page}}</a>
+               </li>
+               <li ng-class='{disabled: pagination.pagination.page >= pagination.pagination.max}'>
+                       <a ng-click='pagination.changePage(pagination.pagination.page + 1, pagination.pagination.limit)'><span>&raquo;</span></a>
+               </li>
+       </ul>
+</nav>
index e0bd4fd..a4d06a6 100644 (file)
@@ -2,7 +2,15 @@
        <div class='form-group has-icon'>
                <input placeholder='Search...' type='text' class='form-control search-input'
                        ng-model-options='{ debounce: 300 }' ng-model='vm.query'
-                       ng-keydown='update($event)' ng-change='vm.search()'>
+                       ng-keydown='vm.update($event)' ng-change='vm.search()'>
                <span class='glyphicon glyphicon-search form-control-icon text-muted'></span>
        </div>
+       <div ng-if='vm.results.results.length > 0' class='card-list search-results'>
+               <entity-card ng-click='vm.selectEnter()' ng-class='{active: vm.activeItem == $index}' ng-mouseover='vm.setActive($index)' mentity='mentity' ng-repeat='mentity in vm.results.results' />
+               <div class='card' ng-click='vm.selectEnter()' ng-mouseover='vm.setActive(vm.results.results.length)' ng-class='{active: vm.activeItem == vm.results.results.length}'>
+                       <div class='card-body'>
+                               Show all {{vm.results.total}} results for <a>"{{vm.query}}"</a>
+                       </div>
+               </div>
+       </div>
 </form>
index 2812b99..92eb64e 100644 (file)
@@ -47,7 +47,7 @@
                                        </div>
                                </div>
                                <div class='col-xs-7'>
-                                       <search-field />
+                                       <ui-search-field />
                                </div>
                                <div class='col-xs-2'>
                                        <user-menu />
@@ -73,7 +73,7 @@
                <script src='/javascripts/nitweb.js'></script>
                <script src='/javascripts/entities.js'></script>
                <script src='/javascripts/ui.js'></script>
-               <script src='/javascripts/index.js'></script>
+               <script src='/javascripts/catalog.js'></script>
                <script src='/javascripts/docdown.js'></script>
                <script src='/javascripts/metrics.js'></script>
                <script src='/javascripts/users.js'></script>
diff --git a/share/nitweb/javascripts/catalog.js b/share/nitweb/javascripts/catalog.js
new file mode 100644 (file)
index 0000000..2667db3
--- /dev/null
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2016 Alexandre Terrasa <alexandre@moz-code.org>.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+(function() {
+       angular.module('catalog', [])
+
+       /* Router */
+
+       .config(function($stateProvider, $locationProvider) {
+               $stateProvider
+                       .state('catalog', {
+                               url: '/?p&n',
+                               controller: 'CatalogCtrl',
+                               controllerAs: 'vm',
+                               templateUrl: 'views/catalog/index.html',
+                               resolve: {
+                                       packages: function(Catalog, $q, $stateParams, $state) {
+                                               var d = $q.defer();
+                                               var page = $stateParams.p ? $stateParams.p : 1;
+                                               var limit = $stateParams.n ? $stateParams.n : 10;
+                                               Catalog.packages(page, limit, d.resolve,
+                                                       function(err) {
+                                                               $state.go('404', null, { location: false })
+                                                       });
+                                               return d.promise;
+                                       },
+                                       tags: function(Catalog, $q, $state) {
+                                               var d = $q.defer();
+                                               Catalog.tags(d.resolve,
+                                                       function(err) {
+                                                               $state.go('404', null, { location: false })
+                                                       });
+                                               return d.promise;
+                                       },
+                                       stats: function(Catalog, $q, $state) {
+                                               var d = $q.defer();
+                                               Catalog.stats(d.resolve,
+                                                       function(err) {
+                                                               $state.go('404', null, { location: false })
+                                                       });
+                                               return d.promise;
+
+                                       }
+                               }
+                       })
+                       .state('person', {
+                               url: '/person/:id?p1&n1&p2&n2',
+                               controller: 'PersonCtrl',
+                               controllerAs: 'vm',
+                               templateUrl: 'views/catalog/person.html',
+                               resolve: {
+                                       person: function(Catalog, $q, $stateParams, $state) {
+                                               var d = $q.defer();
+                                               Catalog.person($stateParams.id, d.resolve,
+                                               function(err) {
+                                                       $state.go('404', null, { location: false })
+                                               });
+                                               return d.promise;
+                                       },
+                                       maintaining: function(Catalog, $q, $stateParams, $state) {
+                                               var d = $q.defer();
+                                               var p1 = $stateParams.p2 ? $stateParams.p1 : 1;
+                                               var n1 = $stateParams.n2 ? $stateParams.n1 : 10;
+                                               Catalog.personMaintaining($stateParams.id, p1, n1, d.resolve,
+                                                       function(err) {
+                                                               $state.go('404', null, { location: false })
+                                                       });
+                                               return d.promise;
+                                       },
+                                       contributing: function(Catalog, $q, $stateParams, $state) {
+                                               var d = $q.defer();
+                                               var p2 = $stateParams.p2 ? $stateParams.p2 : 1;
+                                               var n2 = $stateParams.n2 ? $stateParams.n2 : 10;
+                                               Catalog.personContributing($stateParams.id, p2, n2, d.resolve,
+                                                       function(err) {
+                                                               $state.go('404', null, { location: false })
+                                                       });
+                                               return d.promise;
+
+                                       }
+                               }
+                       })
+                       .state('tag', {
+                               url: '/tag/:id?p&n',
+                               controller: 'TagCtrl',
+                               controllerAs: 'vm',
+                               templateUrl: 'views/catalog/tag.html',
+                               resolve: {
+                                       tag: function(Catalog, $q, $stateParams, $state) {
+                                               var d = $q.defer();
+                                               var page = $stateParams.p ? $stateParams.p : 1;
+                                               var limit = $stateParams.l ? $stateParams.l : 10;
+                                               Catalog.tag($stateParams.id, page, limit, d.resolve,
+                                                       function() {
+                                                               $state.go('404', null, { location: false })
+                                                       });
+                                               return d.promise;
+                                       }
+                               }
+                       })
+       })
+
+       /* Factories */
+
+       .factory('Catalog', [ '$http', function($http) {
+               return {
+                       stats: function(cb, cbErr) {
+                               $http.get('/api/catalog/stats')
+                                       .success(cb)
+                                       .error(cbErr);
+                       },
+                       packages: function(p, n, cb, cbErr) {
+                               $http.get('/api/catalog/packages?p=' + p + '&n=' + n)
+                                       .success(cb)
+                                       .error(cbErr);
+                       },
+                       tags: function(cb, cbErr) {
+                               $http.get('/api/catalog/tags')
+                                       .success(cb)
+                                       .error(cbErr);
+                       },
+                       person: function(id, cb, cbErr) {
+                               $http.get('/api/catalog/person/' + id)
+                                       .success(cb)
+                                       .error(cbErr);
+                       },
+                       personMaintaining: function(id, p, n, cb, cbErr) {
+                               $http.get('/api/catalog/person/' + id + '/maintaining?p=' + p + '&n=' + n)
+                                       .success(cb)
+                                       .error(cbErr);
+                       },
+                       personContributing: function(id, p, n, cb, cbErr) {
+                               $http.get('/api/catalog/person/' + id + '/contributing?p=' + p + '&n=' + n)
+                                       .success(cb)
+                                       .error(cbErr);
+                       },
+                       tag: function(id, p, n, cb, cbErr) {
+                               $http.get('/api/catalog/tag/' + id + '?p=' + p + '&n=' + n)
+                                       .success(cb)
+                                       .error(cbErr);
+                       }
+               };
+       }])
+
+       /* Controllers */
+
+       .controller('CatalogCtrl', function($scope, $state, packages, tags, stats) {
+               var vm = this;
+               vm.packages = packages;
+               vm.tags = tags;
+               vm.stats = stats;
+
+               $scope.$on('change-page', function(e, page, limit) {
+                       $state.go('catalog', {p: page, l: limit});
+               })
+       })
+
+       .controller('PersonCtrl', function($scope, $state, $stateParams, person, maintaining, contributing) {
+               var vm = this;
+               vm.person = person;
+               vm.maintaining = maintaining;
+               vm.contributing = contributing;
+
+               var p1 = $stateParams.p1 ? $stateParams.p1 : 1;
+               var n1 = $stateParams.n1 ? $stateParams.n1 : 10;
+               var p2 = $stateParams.p2 ? $stateParams.p2 : 1;
+               var n2 = $stateParams.n2 ? $stateParams.n2 : 10;
+
+               $scope.$on('change-page1', function(e, page, limit) {
+                       $state.go('person', {id: $stateParams.id, p1: page, n1: limit, p2: p2, n2: n2});
+               })
+
+               $scope.$on('change-page2', function(e, page, limit) {
+                       $state.go('person', {id: $stateParams.id, p1: p1, n1: n1, p2: page, n2: limit});
+               })
+       })
+
+       .controller('TagCtrl', function($state, $scope, tag) {
+               var vm = this;
+               vm.tag = tag;
+
+               $scope.$on('change-page', function(e, page, limit) {
+                       $state.go('tag', {id: vm.tag.tag, p: page, l: limit});
+               })
+       })
+})();
index c5deb0a..545e487 100644 (file)
                                        controller: function(mentity, doc) {
                                                this.mentity = mentity;
                                                this.doc = doc;
+
+                                               this.date = function(date) {
+                                                       return new Date(date);
+                                               }
                                        },
                                        controllerAs: 'vm',
                                })
                                                .success(cb)
                                                .error(cbErr);
                                },
-
-                               search: function(q, n, cb, cbErr) {
-                                       $http.get('/api/search?q=' + q + '&n=' + n)
+                               search: function(q, p, n, cb, cbErr) {
+                                       $http.get('/api/search?q=' + q + '&p=' + p + '&n=' + n)
                                                .success(cb)
                                                .error(cbErr);
                                }
                        return {
                                restrict: 'E',
                                scope: {
-                                       mentity: '=',
-                                       defaultTab: '@',
-                                       noSynopsis: '='
+                                       mentity: '='
                                },
                                replace: true,
-                               templateUrl: '/directives/entity/card.html',
-                               link: function ($scope, element, attrs) {
-                                       $scope.currentTab = $scope.defaultTab ? $scope.defaultTab : 'signature';
-
-                                       $scope.loadEntityStars = function() {
-                                               Feedback.loadEntityStars($scope.mentity.full_name,
-                                                       function(data) {
-                                                               $scope.ratings = data;
-                                                       }, function(message, status) {
-                                                               $scope.error = {message: message, status: status};
-                                                       });
-                                       };
-                               }
+                               templateUrl: '/directives/entity/card.html'
                        };
                }])
 
index 72eadbc..96ede05 100644 (file)
 
                .config(function($stateProvider, $locationProvider) {
                        $stateProvider
+                               .state('doc.entity.grades', {
+                                       url: '/grades',
+                                       templateUrl: 'views/doc/grades.html',
+                                       resolve: {
+                                               metrics: function(Feedback, $q, $stateParams, $state) {
+                                                       var d = $q.defer();
+                                                       Feedback.loadEntityStars($stateParams.id, d.resolve,
+                                                               function() {
+                                                                       $state.go('404', null, { location: false })
+                                                               });
+                                                       return d.promise;
+                                               }
+                                       },
+                                       controller: function(mentity, metrics) {
+                                               this.mentity = mentity;
+                                               this.metrics = metrics;
+                                       },
+                                       controllerAs: 'vm',
+                               })
                                .state('grades', {
                                        url: '/grades',
                                        templateUrl: 'views/grades.html',
diff --git a/share/nitweb/javascripts/index.js b/share/nitweb/javascripts/index.js
deleted file mode 100644 (file)
index 104d627..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2016 Alexandre Terrasa <alexandre@moz-code.org>.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-(function() {
-       angular
-               .module('index', [])
-
-               .config(function($stateProvider, $locationProvider) {
-                       $stateProvider
-                               .state('catalog', {
-                                       url: '/',
-                                       templateUrl: 'views/catalog/index.html',
-                                       controller: 'CatalogCtrl',
-                                       controllerAs: 'vm',
-                                       abstract: true
-                               })
-                               .state('catalog.highlighted', {
-                                       url: '',
-                                       templateUrl: 'views/catalog/highlighted.html',
-                                       controller: 'CatalogHighlightedCtrl',
-                                       controllerAs: 'vm'
-                               })
-                               .state('catalog.required', {
-                                       url: 'required',
-                                       templateUrl: 'views/catalog/most_required.html',
-                                       controller: 'CatalogRequiredCtrl',
-                                       controllerAs: 'vm'
-                               })
-                               .state('catalog.tags', {
-                                       url: 'tags',
-                                       templateUrl: 'views/catalog/by_tags.html',
-                                       controller: 'CatalogTagsCtrl',
-                                       controllerAs: 'vm'
-                               })
-               })
-
-               .factory('Catalog', [ '$http', function($http) {
-                       return {
-                               loadHightlighted: function(cb, cbErr) {
-                                       $http.get('/api/catalog/highlighted')
-                                               .success(cb)
-                                               .error(cbErr);
-                               },
-
-                               loadMostRequired: function(cb, cbErr) {
-                                       $http.get('/api/catalog/required')
-                                               .success(cb)
-                                               .error(cbErr);
-                               },
-
-                               loadByTags: function(cb, cbErr) {
-                                       $http.get('/api/catalog/bytags')
-                                               .success(cb)
-                                               .error(cbErr);
-                               },
-
-                               loadStats: function(cb, cbErr) {
-                                       $http.get('/api/catalog/stats')
-                                               .success(cb)
-                                               .error(cbErr);
-                               },
-
-                               loadContributors: function(cb, cbErr) {
-                                       $http.get('/api/catalog/contributors')
-                                               .success(cb)
-                                               .error(cbErr);
-                               },
-                       }
-               }])
-
-               .controller('CatalogCtrl', function(Catalog) {
-                       var vm = this;
-
-                       Catalog.loadContributors(
-                               function(data) {
-                                       vm.contributors = data;
-                               }, function(err) {
-                                       vm.error = err;
-                               });
-
-                       Catalog.loadStats(
-                               function(data) {
-                                       vm.stats = data;
-                               }, function(err) {
-                                       vm.error = err;
-                               });
-               })
-
-               .controller('CatalogHighlightedCtrl', function(Catalog) {
-                       var vm = this;
-
-                       Catalog.loadHightlighted(
-                               function(data) {
-                                       vm.highlighted = data;
-                               }, function(err) {
-                                       vm.error = err;
-                               });
-               })
-
-               .controller('CatalogRequiredCtrl', function(Catalog) {
-                       var vm = this;
-
-                       Catalog.loadMostRequired(
-                               function(data) {
-                                       vm.required = data;
-                               }, function(err) {
-                                       vm.error = err;
-                               });
-               })
-
-               .controller('CatalogTagsCtrl', function(Catalog, $anchorScroll, $location) {
-                       var vm = this;
-
-                       Catalog.loadByTags(
-                               function(data) {
-                                       vm.bytags = data;
-                               }, function(err) {
-                                       vm.error = err;
-                               });
-
-
-                       vm.scrollTo = function(hash) {
-                               $location.hash(hash);
-                               $anchorScroll();
-                       }
-               })
-
-               .directive('contributorList', function(Model) {
-                       return {
-                               restrict: 'E',
-                               scope: {
-                                       listId: '@',
-                                       listTitle: '@',
-                                       listContributors: '='
-                               },
-                               templateUrl: '/directives/contributor-list.html'
-                       };
-               })
-})();
index 181da8e..1de3f69 100644 (file)
  */
 
 (function() {
-       angular.module('nitweb', ['ui.router', 'ngSanitize', 'angular-loading-bar', 'index', 'entities', 'docdown', 'metrics', 'users', 'grades'])
+       angular.module('nitweb', ['ui.router', 'ngSanitize', 'angular-loading-bar', 'catalog', 'entities', 'docdown', 'metrics', 'users', 'grades'])
 
        .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
                cfpLoadingBarProvider.includeSpinner = false;
        }])
 
-       .run(['$anchorScroll', function($anchorScroll) {
+       .run(function($rootScope, $anchorScroll) {
                $anchorScroll.yOffset = 80;
-       }])
+               $rootScope.$on('$stateChangeSuccess', function() {
+                 $anchorScroll();
+               });
+       })
 
        .config(function($stateProvider, $locationProvider) {
                $stateProvider
index 7fc3f8a..5327782 100644 (file)
        angular
                .module('ui', [])
 
-               .controller('SearchCtrl', function(Model, $scope, $location, $document) {
-
-                       $scope.query = '';
-
-                       $scope.reset = function() {
-                               $scope.activeItem = 0;
-                               $scope.results = [];
-                       }
-
-                       $scope.update = function(e) {
-                               if(e.keyCode == 38) {
-                                       $scope.selectUp();
-                               } else if(e.keyCode == 40) {
-                                       $scope.selectDown();
-                               } else if(e.keyCode == 27) {
-                                       $scope.selectEscape();
-                               } else if(e.keyCode == 13) {
-                                       $scope.selectEnter();
-                               }
-                       }
-
-                       $scope.selectUp = function() {
-                               if($scope.activeItem > 0) {
-                                       $scope.activeItem -= 1;
-                               }
-                       }
-
-                       $scope.selectDown = function() {
-                               if($scope.activeItem < $scope.results.length - 1) {
-                                       $scope.activeItem += 1;
-                               }
-                       }
-
-                       $scope.selectEnter = function(e) {
-                               $location.url($scope.results[$scope.activeItem].web_url);
-                               $scope.reset();
-                       }
+               /* Search */
 
-                       $scope.selectEscape = function() {
-                               $scope.reset();
-                       }
-
-                       $scope.setActive = function(index) {
-                               $scope.activeItem = index;
-                       }
+               .config(function($stateProvider, $locationProvider) {
+                       $stateProvider
+                               .state('search', {
+                                       url: '/search?q&p&n',
+                                       controller: 'SearchCtrl',
+                                       controllerAs: 'vm',
+                                       templateUrl: 'views/search.html',
+                                       resolve: {
+                                               entities: function(Model, $q, $stateParams, $state) {
+                                                       var d = $q.defer();
+                                                       var query = $stateParams.q;
+                                                       var page = $stateParams.p ? $stateParams.p : 1;
+                                                       var limit = $stateParams.n ? $stateParams.n : 10;
+                                                       Model.search(query, page, limit, d.resolve,
+                                                               function() {
+                                                                       $state.go('404', null, { location: false })
+                                                               });
+                                                       return d.promise;
+                                               }
+                                       }
+                               })
+               })
 
-                       $scope.search = function() {
-                               if(!$scope.query) {
-                                       $scope.reset();
-                                       return;
-                               }
-                               Model.search($scope.query, 10,
-                                       function(data) {
-                                               $scope.reset();
-                                               $scope.results = data;
-                                       }, function(err) {
-                                               $scope.reset();
-                                               $scope.error = err;
-                                       });
-                       }
+               .controller('SearchCtrl', function($scope, $state, $stateParams, entities) {
+                       var vm = this;
+                       vm.entities = entities;
+                       vm.query = $stateParams.q;
 
-                       $scope.reset();
+                       $scope.$on('change-page', function(e, page, limit) {
+                               $state.go('search', {q: vm.query, p: page, l: limit});
+                       })
                })
 
-               .directive('searchField', function($document) {
+               .directive('uiSearchField', function($document) {
                        return {
                                restrict: 'E',
                                replace: true,
-                               controller: 'SearchCtrl',
-                               controllerAs: 'searchCtrl',
-                               templateUrl: '/directives/search/field.html',
-                               link: function ($scope, element, attrs) {
+                               controller: function($scope, $state, $stateParams, $location, Model) {
+                                       var vm = this;
+                                       vm.search = function() {
+                                               if(!vm.query) {
+                                                       vm.reset();
+                                                       return;
+                                               }
+                                               Model.search(vm.query, 1, 8,
+                                                       function(data) {
+                                                               vm.reset();
+                                                               vm.results = data;
+                                                       }, function(err) {
+                                                               vm.reset();
+                                                               vm.error = err;
+                                                       });
+                                       }
+
+                                       vm.reset = function() {
+                                               vm.activeItem = -1;
+                                               vm.results = {
+                                                       results: []
+                                               };
+                                       }
+
+                                       vm.update = function(e) {
+                                               if(e.keyCode == 38) {
+                                                       vm.selectUp();
+                                               } else if(e.keyCode == 40) {
+                                                       vm.selectDown();
+                                               } else if(e.keyCode == 27) {
+                                                       vm.selectEscape();
+                                               } else if(e.keyCode == 13) {
+                                                       vm.selectEnter();
+                                               }
+                                       }
+
+                                       vm.selectUp = function() {
+                                               if(vm.activeItem >= 0) {
+                                                       vm.activeItem -= 1;
+                                               }
+                                       }
+
+                                       vm.selectDown = function() {
+                                               if(vm.activeItem < vm.results.results.length) {
+                                                       vm.activeItem += 1;
+                                               }
+                                       }
+
+                                       vm.selectEnter = function(e) {
+                                               if(vm.activeItem >= 0 && vm.activeItem < vm.results.results.length) {
+                                                       $location.url(vm.results.results[vm.activeItem].web_url);
+                                               } else {
+                                                       $state.go('search', {q: vm.query, p: 1});
+                                               }
+                                               vm.reset();
+                                       }
+
+                                       vm.selectEscape = function() {
+                                               vm.reset();
+                                       }
+
+                                       vm.setActive = function(index) {
+                                               vm.activeItem = index;
+                                       }
+
+                                       vm.reset();
+
+                                       $scope.$watch(function() {
+                                               return $stateParams.q;
+                                       }, function(q) {
+                                               if(q) vm.query = q;
+                                       });
+                               },
+                               controllerAs: 'vm',
+                               templateUrl: 'directives/ui/search-field.html',
+                               link: function ($scope, element, attrs, ctrl) {
                                        $document.bind('click', function (event) {
                                                var isChild = $(element).has(event.target).length > 0;
                                                var isSelf = element[0] == event.target;
                                                var isInside = isChild || isSelf;
                                                if (!isInside) {
-                                                       $scope.reset();
+                                                       ctrl.reset();
                                                        $scope.$apply();
                                                }
                                        });
                        };
                })
 
-               .directive('searchCard', function() {
-                       return {
-                               restrict: 'E',
-                               scope: {
-                                       mentity: '='
-                               },
-                               replace: true,
-                               templateUrl: '/directives/search/card.html'
-                       };
-               })
+               /* Filters */
 
                .directive('uiFilters', function() {
                        return {
                                }
                        };
                })
+
+               /* Pagination */
+
+               .directive('uiPagination', function() {
+                       return {
+                               restrict: 'E',
+                               replace: true,
+                               bindToController: {
+                                       pagination: '=',
+                                       suffix: '=?'
+                               },
+                               controller: function($scope) {
+                                       var vm = this;
+
+                                       $scope.$watch('pagination.pagination', function(pagination) {
+                                               if(!pagination) return;
+                                               vm.computePages(pagination);
+                                       })
+
+                                       vm.computePages = function(pagination) {
+                                               vm.pages = [];
+                                               var len = 11;
+                                               var page = pagination.page;
+                                               var start = page - Math.floor(len / 2);
+                                               var end = page + Math.floor(len / 2);
+
+                                               if(start < 1) {
+                                                       end = Math.min(pagination.max, end + Math.abs(start) + 1)
+                                                       start = 1
+                                               } else if(end > pagination.max) {
+                                                       start = Math.max(1, start - Math.abs(end - pagination.max))
+                                                       end = pagination.max;
+                                               }
+
+                                               for(var i = start; i <= end; i++) {
+                                                       vm.pages.push(i);
+                                               }
+                                       }
+
+                                       vm.changePage = function(page, limit) {
+                                               if(page <= 0 || page > vm.pagination.max) return;
+                                               var suffix = vm.suffix ? vm.suffix : '';
+                                               $scope.$emit('change-page' + suffix, page, limit);
+                                       }
+                               },
+                               controllerAs: 'pagination',
+                               templateUrl: 'directives/ui/pagination.html'
+                       };
+               })
 })();
index 0d39859..de16f88 100644 (file)
@@ -29,9 +29,9 @@
        display: table;
        width: 100%;
        background: #fff;
-       border: 1px solid #ccc;
+       border: 1px solid #eee;
        margin-top: 10px;
-       box-shadow: 0 -1px 0 #e5e5e5,0 0 2px rgba(0,0,0,.12),0 2px 4px rgba(0,0,0,.24);
+       box-shadow: -1px -1px 3px rgba(0,0,0,.06), 1px 1px 3px rgba(0,0,0,.12);
 }
 
 .card-body, .card-left, .card-right {
@@ -57,7 +57,7 @@
 }
 
 .card-list > .card:first-child {
-       border-top: 1px solid #ccc;
+       border-top: 1px solid #ddd;
 }
 
 .card-list > .card {
index 864c296..ccfcdd0 100644 (file)
        background: #FF8100;
 }
 
+[ng-click] {
+       cursor: pointer;
+}
+
 /* Body */
 
 body {
@@ -127,28 +131,6 @@ entity-list:hover .btn-filter {
     pointer-events: none;
 }
 
-/* search */
-
-.search-input {
-       width: 100%;
-}
-
-.search-results {
-       position: absolute;
-       margin-top: 2px;
-       right: 15px;
-       left: 15px;
-}
-
-.search-results .card.active {
-       background: #eee;
-       border-color: #eee;
-}
-
-.card-search {
-       cursor: pointer;
-}
-
 /* navs */
 
 .nav-tabs li { cursor: pointer; }
index 2f6e2db..68516dc 100644 (file)
 .navbar-fixed-top *:-moz-placeholder { color: #fff; }
 .navbar-fixed-top *::-moz-placeholder { color: #fff; }
 .navbar-fixed-top *:-ms-input-placeholder { color: #fff; }
+
+.search-input {
+       width: 100%;
+}
+
+.card-list.search-results {
+       position: absolute;
+       margin-top: 2px;
+       right: 15px;
+       left: 15px;
+       box-shadow: 1px 1px 3px rgba(0,0,0,0.12), -1px -1px 3px rgba(0,0,0,.12);
+}
+
+.search-results .card.active {
+       background: #eee;
+       border-color: #eee;
+}
diff --git a/share/nitweb/views/catalog/by_tags.html b/share/nitweb/views/catalog/by_tags.html
deleted file mode 100644 (file)
index 31ca905..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-<div>
-       <h3>Tags</h3>
-       <div class='container-fluid'>
-               <div class='col-xs-3' ng-repeat='(tag, packages) in vm.bytags'>
-                       <span class='badge'>{{packages.length}}</span>
-                       <a ng-click='vm.scrollTo(tag)'>{{tag}}</a>
-               </div>
-       </div>
-       <div ng-repeat='(tag, packages) in vm.bytags'>
-               <entity-list list-id='{{tag}}' list-title='{{tag}}'
-                       list-entities='packages'
-                       list-object-filter='{}' />
-       </div>
-</div>
diff --git a/share/nitweb/views/catalog/highlighted.html b/share/nitweb/views/catalog/highlighted.html
deleted file mode 100644 (file)
index 5607bd5..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<div>
-       <entity-list list-title='Highlighted packages'
-               list-entities='vm.highlighted'
-               list-object-filter='{}' />
-</div>
index 877db4a..2333a0a 100644 (file)
@@ -1,47 +1,35 @@
-<div class='container-fluid'>
+<div class='container'>
        <div class='page-header'>
                <h2>Welcome to NitWeb!</h2>
                <p class='text-muted'>The Nit knowledge base.</p>
        </div>
 
-       <ul class='nav nav-tabs' role='tablist'>
-               <li role='presentation' ui-sref-active='active'>
-                       <a ui-sref='catalog.highlighted'>
-                               <span class='glyphicon glyphicon-book'/> Highlighed
-                       </a>
-               </li>
-               <li role='presentation' ui-sref-active='active'>
-                       <a ui-sref='catalog.required'>
-                               <span class='glyphicon glyphicon-book'/> Most required
-                       </a>
-               </li>
-               <li role='presentation' ui-sref-active='active'>
-                       <a ui-sref='catalog.tags'>
-                               <span class='glyphicon glyphicon-book'/> By tags
-                       </a>
-               </li>
-       </ul>
-       <table class='table'>
-               <tr>
-                       <td ng-repeat='(key, value) in vm.stats'>
-                               <h5><strong>{{value}}</strong>&nbsp;<span>{{key}}</span></h5>
-                       </td>
-               </tr>
-       </table>
+       <div ng-if='vm.stats' class='container-fluid no-padding'>
+               <span ng-repeat='(key, value) in vm.stats' class='text-muted small'>
+                       <strong>{{value}}</strong>&nbsp;<span>{{key}}</span>
+                       &nbsp;
+               </span>
+       </div>
+       <hr/>
 
-       <div class='container-fluid'>
-               <div class='col-xs-9'>
-                       <div class='tab-content'>
-                               <div role='tabpanel' class='tab-pane fade in active'>
-                                       <ui-view />
-                               </div>
+       <div class='col-md-3 col-md-push-9 no-padding' ng-if='vm.tags'>
+               <h2>Tags</h2>
+               <div class='container-fluid no-padding'>
+                       <div class='col-xs-3 col-md-12' ng-repeat='(tag, packages) in vm.tags'>
+                               <span class='badge'>{{packages}}</span>
+                               <a ui-sref='tag({id: tag})'>{{tag}}</a>
                        </div>
                </div>
-               <div class='col-xs-3'>
-                       <contributor-list list-title='Maintainers'
-                                       list-contributors='vm.contributors.maintainers' />
-                       <contributor-list list-title='Contributors'
-                                       list-contributors='vm.contributors.contributors' />
+               <hr/>
+       </div>
+
+       <div class='col-md-9 col-md-pull-3 no-padding'>
+               <h2>Packages</h2>
+               <div class='card-list'>
+                       <entity-card mentity='package' ng-repeat='package in vm.packages.results' />
+               </div>
+               <div class='container text-center' ng-if='vm.packages'>
+                       <ui-pagination pagination='vm.packages'/>
                </div>
        </div>
 </div>
diff --git a/share/nitweb/views/catalog/most_required.html b/share/nitweb/views/catalog/most_required.html
deleted file mode 100644 (file)
index 93bf2e1..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<div>
-       <entity-list list-title='Most required'
-               list-entities='vm.required'
-               list-object-filter='{}' />
-</div>
diff --git a/share/nitweb/views/catalog/person.html b/share/nitweb/views/catalog/person.html
new file mode 100644 (file)
index 0000000..433b73d
--- /dev/null
@@ -0,0 +1,33 @@
+<div class='container'>
+       <div class='col-xs-2 no-padding'>
+               <img class='avatar' style='width:100%; max-width:100px' src='https://secure.gravatar.com/avatar/{{vm.person.gravatar}}?size=100&amp;default=retro' />
+       </div>
+       <div class='col-xs-10'>
+               <h1>
+                       {{vm.person.name}}<br>
+                       <small>{{vm.person.email}}</small>
+               </h1>
+       </div>
+       <hr/>
+</div>
+<br><br>
+<div class='container'>
+       <div ng-if='vm.maintaining.results.length > 0'>
+               <h3 id='maintaining'>{{vm.maintaining.total}} maintained projects</h3>
+               <div class='card-list'>
+                       <entity-card mentity='package' ng-repeat='package in vm.maintaining.results' />
+               </div>
+               <div class='container text-center' ng-if='vm.maintaining'>
+                       <ui-pagination pagination='vm.maintaining' suffix='1'/>
+               </div>
+       </div>
+       <div ng-if='vm.contributing.results.length > 0'>
+               <h3 id='contributing'>{{vm.contributing.total}} contributed projects</h3>
+               <div class='card-list'>
+                       <entity-card mentity='package' ng-repeat='package in vm.contributing.results' />
+               </div>
+               <div class='container text-center' ng-if='vm.contributing'>
+                       <ui-pagination pagination='vm.contributing' suffix='2' />
+               </div>
+       </div>
+</div>
diff --git a/share/nitweb/views/catalog/tag.html b/share/nitweb/views/catalog/tag.html
new file mode 100644 (file)
index 0000000..6c0a37e
--- /dev/null
@@ -0,0 +1,16 @@
+<div class='container'>
+       <h1>
+               {{vm.tag.tag}}
+               <small>{{vm.tag.packages.total}} packages</small>
+       </h1>
+       <hr/>
+
+       <div class='container-fluid no-padding' ng-if='vm.tag.packages.results.length > 0'>
+               <div class='card-list'>
+                       <entity-card mentity='package' ng-repeat='package in vm.tag.packages.results' />
+               </div>
+               <div class='container text-center' ng-if='vm.tag.packages'>
+                       <ui-pagination pagination='vm.tag.packages'/>
+               </div>
+       </div>
+</div>
index 1e60694..eadcf37 100644 (file)
@@ -1,8 +1,10 @@
 <div>
-       <div class='col-xs-3'>
+       <div class='col-lg-2 col-sm-3 col-xs-12'>
                <ui-summary target='#summary-content' />
        </div>
-       <div class='col-xs-9' id='summary-content'>
+       <div class='col-lg-10 col-sm-9 col-xs-12' id='summary-content' ng-class='{
+               "col-lg-8 col-sm-6 col-xs-12": vm.mentity.class_name == "MPackage"
+       }'>
                <div class='card'>
                        <div class='card-body'>
                                <div ng-if='vm.doc'>
                        list-object-filter='{is_init: "!true"}' />
 
        </div>
+
+       <div class='col-lg-2 col-sm-3 col-xs-12' ng-class='{
+               "hidden": vm.mentity.class_name != "MPackage"
+       }'>
+               <br>
+               <p ng-repeat='maintainer in vm.mentity.metadata.maintainers' class='lead'>
+                       <img class='avatar' src='https://secure.gravatar.com/avatar/{{maintainer.gravatar}}?size=20&default=retro' />
+                       <span>
+                               <a ui-sref='person({id: maintainer.name})'>{{maintainer.name}}</a>
+                       </span>
+                       <br>
+               </p>
+               <span ng-if='vm.mentity.metadata.license'>
+                       <span class='text-muted'>
+                               <a href='http://opensource.org/licenses/{{vm.mentity.metadata.license}}'>{{vm.mentity.metadata.license}}</a>
+                               license
+                       </span>
+                       <br>
+               </span>
+
+               <div ng-if='vm.mentity.metadata.homepage || vm.mentity.metadata.issues'>
+                       <h3>Links</h3>
+                       <ul class='list-unstyled'>
+                               <li ng-if='vm.mentity.metadata.homepage'>
+                                       <a href='{{vm.mentity.metadata.homepage}}'>Homepage</a>
+                               </li>
+                               <li ng-if='vm.mentity.metadata.browse'>
+                                       <a href='{{vm.mentity.metadata.browse}}'>Source Code</a>
+                               </li>
+                               <li ng-if='vm.mentity.metadata.issues'>
+                                       <a href='{{vm.mentity.metadata.issues}}'>Issues</a>
+                               </li>
+                       </ul>
+               </div>
+
+               <div ng-if='vm.mentity.metadata.git || vm.mentity.stats.commits'>
+                       <h3>Git</h3>
+                       <ul class='list-unstyled' style='white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>
+                               <li ng-if='vm.mentity.metadata.git'>
+                                       <a href='{{vm.mentity.metadata.git}}'>{{vm.mentity.metadata.git}}</a>
+                               </li>
+                               <li ng-if='vm.mentity.stats.commits' class='text-muted'>
+                                       <br><b>{{vm.mentity.stats.commits}} commits</b>
+                               </li>
+                               <li ng-if='vm.mentity.metadata.last_date'><b class='text-muted'>Last:</b> {{vm.date(vm.mentity.metadata.last_date) | date: 'medium'}}</li>
+                               <li ng-if='vm.mentity.metadata.first_date'><b class='text-muted'>First: </b>{{vm.date(vm.mentity.metadata.first_date) | date: 'medium'}}</li>
+                       </ul>
+               </div>
+
+               <div ng-if='vm.mentity.stats'>
+                       <h3>Quality</h3>
+                       <ul class='list-unstyled'>
+                               <li ng-if='vm.mentity.stats.documentation_score'>
+                                       {{vm.mentity.stats.documentation_score}}% documented
+                               </li>
+                               <li ng-if='vm.mentity.stats.errors' class='text-danger'>
+                                       {{vm.mentity.stats.errors}} errors
+                               </li>
+                               <li ng-if='vm.mentity.stats.warnings' class='text-warning'>
+                                       {{vm.mentity.stats.warnings}} warnings
+                                       ({{vm.mentity.stats.warnings_per_kloc}} / kloc)
+                               </li>
+                       </ul>
+               </div>
+
+               <div ng-if='vm.mentity.metadata.tags.length > 0'>
+                       <h3>Tags</h3>
+                       <span ng-repeat='tag in vm.mentity.metadata.tags'>
+                               <a ui-sref='tag({id: tag})'>{{tag}}</a><span ng-if='!$last'>,</span>
+                       </span>
+               </div>
+
+               <div ng-if='vm.mentity.dependencies.length > 0'>
+                       <h3>Requirements</h3>
+                       <span ng-repeat='parent in vm.mentity.dependencies'>
+                               <a ui-sref='mentity({id: parent.name})' title='{{parent.synopsis}}'>{{parent.name}}</a><span ng-if='!$last'>,</span>
+                       </span>
+               </div>
+
+               <div ng-if='vm.mentity.clients.length > 0'>
+                       <h3>Clients</h3>
+                       <span ng-repeat='client in vm.mentity.clients'>
+                               <a ui-sref='mentity({id: client.name})' title='{{client.synopsis}}'>{{client.name}}</a><span ng-if='!$last'>,</span>
+                       </span>
+               </div>
+
+               <div ng-if='vm.mentity.metadata.contributors.length > 1'>
+                       <h3>Contributors</h3>
+                       <ul class='list-unstyled'>
+                               <li ng-repeat='contributor in vm.mentity.metadata.contributors'>
+                                       <img class='avatar' src='https://secure.gravatar.com/avatar/{{contributor.gravatar}}?size=20&default=retro' />
+                                       <a ui-sref='person({id: contributor.name})'>
+                                       {{contributor.name}}</a>
+                               </li>
+                       </ul>
+               </div>
+
+               <div ng-if='vm.mentity.stats'>
+                       <h3>Stats</h3>
+                       <ul class='list-unstyled'>
+                               <li>{{vm.mentity.stats.mmodules}} modules</li>
+                               <li>{{vm.mentity.stats.mclasses}} classes</li>
+                               <li>{{vm.mentity.stats.mmethods}} methods</li>
+                               <li>{{vm.mentity.stats.loc}} loc</li>
+                       </ul>
+               </div>
+       </div>
 </div>
index 3543b9f..e6b559f 100644 (file)
                                <span class='glyphicon glyphicon-stats'/> Metrics
                        </a>
                </li>
+
+               <!-- grades -->
+               <li role='presentation' ui-sref-active='active'>
+                       <a ui-sref='.grades'>
+                               <span class='glyphicon glyphicon-star'/> Grades
+                       </a>
+               </li>
        </ul>
        <br>
        <ui-view />
diff --git a/share/nitweb/views/doc/grades.html b/share/nitweb/views/doc/grades.html
new file mode 100644 (file)
index 0000000..89fc74c
--- /dev/null
@@ -0,0 +1,5 @@
+<div class='card'>
+       <div class='card-body'>
+               <entity-rating mentity='vm.mentity' ratings='vm.ratings'>
+       </div>
+</div>
diff --git a/share/nitweb/views/search.html b/share/nitweb/views/search.html
new file mode 100644 (file)
index 0000000..6614e9c
--- /dev/null
@@ -0,0 +1,12 @@
+<div class='container'>
+       <h2>
+               {{vm.entities.total}} matches for
+               <a ui-sref='search({q: vm.query})'>{{vm.query}}</a>
+       </h2>
+       <div class='card-list'>
+               <entity-card mentity='mentity' ng-repeat='mentity in vm.entities.results' />
+       </div>
+       <div class='container text-center' ng-if='vm.entities'>
+               <ui-pagination pagination='vm.entities'/>
+       </div>
+</div>
index 92510bc..dd891ac 100644 (file)
@@ -53,18 +53,41 @@ import counter # For statistics
 import modelize # To process and count classes and methods
 
 redef class MPackage
+
+       # Metadata related to this package
+       var metadata = new MPackageMetadata(self)
+end
+
+# The metadata extracted from a MPackage
+class MPackageMetadata
+
+       # The mpacakge this metadata belongs to
+       var mpackage: MPackage
+
        # Return the associated metadata from the `ini`, if any
-       fun metadata(key: String): nullable String
-       do
-               var ini = self.ini
+       fun metadata(key: String): nullable String do
+               var ini = mpackage.ini
                if ini == null then return null
                return ini[key]
        end
 
        # The consolidated list of tags
-       var tags = new Array[String]
+       var tags: Array[String] is lazy do
+               var tags = new Array[String]
+               var string = metadata("package.tags")
+               if string == null then return tags
+               for tag in string.split(",") do
+                       tag = tag.trim
+                       if tag.is_empty then continue
+                       tags.add tag
+               end
+               if tryit != null then tags.add "tryit"
+               if apk != null then tags.add "apk"
+               if tags.is_empty then tags.add "none"
+               return tags
+       end
 
-       # The list of maintainers
+       # The list of all maintainers
        var maintainers = new Array[Person]
 
        # The list of contributors
@@ -75,6 +98,43 @@ redef class MPackage
 
        # The date of the oldest commit
        var first_date: nullable String = null
+
+       # Key: package.maintainer`
+       var maintainer: nullable String is lazy do return metadata("package.maintainer")
+
+       # Key: `package.more_contributors`
+       var more_contributors: Array[String] is lazy do
+               var res = new Array[String]
+               var string = metadata("package.more_contributors")
+               if string == null then return res
+               for c in string.split(",") do
+                       c = c.trim
+                       if c.is_empty then continue
+                       res.add c
+               end
+               return res
+       end
+
+       # Key: `package.license`
+       var license: nullable String is lazy do return metadata("package.license")
+
+       # Key: `upstream.tryit`
+       var tryit: nullable String is lazy do return metadata("upstream.tryit")
+
+       # Key: `upstream.apk`
+       var apk: nullable String is lazy do return metadata("upstream.apk")
+
+       # Key: `upstream.homepage`
+       var homepage: nullable String is lazy do return metadata("upstream.homepage")
+
+       # Key: `upstream.browse`
+       var browse: nullable String is lazy do return metadata("upstream.browse")
+
+       # Package git clone address
+       var git: nullable String is lazy do return metadata("upstream.git")
+
+       # Package issue tracker
+       var issues: nullable String is lazy do return metadata("upstream.issues")
 end
 
 redef class Int
@@ -98,6 +158,13 @@ class Person
        # Some homepage. Eg "http://example.com/~jdoe"
        var page: nullable String is writable
 
+       # Gravatar id
+       var gravatar: nullable String is lazy do
+               var email = self.email
+               if email == null then return null
+               return email.md5.to_lower
+       end
+
        # Return a full-featured link to a person
        fun to_html: String
        do
@@ -107,10 +174,9 @@ class Person
                if page != null then
                        res += "<a href=\"{page.html_escape}\">"
                end
-               var email = self.email
-               if email != null then
-                       var md5 = email.md5.to_lower
-                       res += "<img src=\"https://secure.gravatar.com/avatar/{md5}?size=20&amp;default=retro\">&nbsp;"
+               var gravatar = self.gravatar
+               if gravatar != null then
+                       res += "<img src=\"https://secure.gravatar.com/avatar/{gravatar}?size=20&amp;default=retro\">&nbsp;"
                end
                res += e
                if page != null then res += "</a>"
@@ -202,6 +268,9 @@ class Catalog
        # used to access the files and count source lines of code
        var modelbuilder: ModelBuilder
 
+       # List of all packages by their names
+       var mpackages = new HashMap[String, MPackage]
+
        # Packages by tag
        var tag2proj = new MultiHashMap[String, MPackage]
 
@@ -249,9 +318,15 @@ class Catalog
        # The score is loosely computed using other metrics
        var score = new Counter[MPackage]
 
-       # List of known people
+       # List of known people by their git string
        var persons = new HashMap[String, Person]
 
+       # Map person short names to person objects
+       var name2person = new HashMap[String, Person]
+
+       # Package statistics cache
+       var mpackages_stats = new HashMap[MPackage, MPackageStats]
+
        # Scan, register and add a contributor to a package
        fun register_contrib(person: String, mpackage: MPackage): Person
        do
@@ -268,14 +343,17 @@ class Catalog
                var projs = contrib2proj[p]
                if not projs.has(mpackage) then
                        projs.add mpackage
-                       mpackage.contributors.add p
+                       mpackage.metadata.contributors.add p
                end
+               name2person[p.name] = p
                return p
        end
 
        # Compute information for a package
        fun package_page(mpackage: MPackage)
        do
+               mpackages[mpackage.full_name] = mpackage
+
                var score = score[mpackage].to_f
 
                var mdoc = mpackage.mdoc_or_fallback
@@ -283,58 +361,45 @@ class Catalog
                        score += 100.0
                        score += mdoc.content.length.score
                end
+               var metadata = mpackage.metadata
 
-
-               var tryit = mpackage.metadata("upstream.tryit")
+               var tryit = metadata.tryit
                if tryit != null then
                        score += 1.0
                end
-               var apk = mpackage.metadata("upstream.apk")
+               var apk = metadata.apk
                if apk != null then
                        score += 1.0
                end
-
-               var homepage = mpackage.metadata("upstream.homepage")
+               var homepage = metadata.homepage
                if homepage != null then
                        score += 5.0
                end
-               var maintainer = mpackage.metadata("package.maintainer")
+               var maintainer = metadata.maintainer
                if maintainer != null then
                        score += 5.0
                        var person = register_contrib(maintainer, mpackage)
-                       mpackage.maintainers.add person
+                       mpackage.metadata.maintainers.add person
                        var projs = maint2proj[person]
                        if not projs.has(mpackage) then projs.add mpackage
                end
-               var license = mpackage.metadata("package.license")
+               var license = metadata.license
                if license != null then
                        score += 5.0
                end
-
-               var browse = mpackage.metadata("upstream.browse")
+               var browse = metadata.browse
                if browse != null then
                        score += 5.0
                end
-
-               var tags = mpackage.metadata("package.tags")
-               var ts = mpackage.tags
-               if tags != null then
-                       for t in tags.split(",") do
-                               t = t.trim
-                               if t == "" then continue
-                               ts.add t
-                       end
+               var tags = metadata.tags
+               for tag in tags do
+                       tag2proj[tag].add mpackage
                end
-               if ts.is_empty then ts.add "none"
-               if tryit != null then ts.add "tryit"
-               if apk != null then ts.add "apk"
-               for t in ts do
-                       tag2proj[t].add mpackage
+               if tags.not_empty then
+                       var cat = tags.first
+                       cat2proj[cat].add mpackage
+                       score += tags.length.score
                end
-               var cat = ts.first
-               cat2proj[cat].add mpackage
-               score += ts.length.score
-
                if deps.has(mpackage) then
                        score += deps[mpackage].greaters.length.score
                        score += deps[mpackage].direct_greaters.length.score
@@ -342,15 +407,12 @@ class Catalog
                        score += deps[mpackage].direct_smallers.length.score
                end
 
-               var contributors = mpackage.contributors
-               var more_contributors = mpackage.metadata("package.more_contributors")
-               if more_contributors != null then
-                       for c in more_contributors.split(",") do
-                               register_contrib(c.trim, mpackage)
-                       end
+               var contributors = mpackage.metadata.contributors
+               var more_contributors = metadata.more_contributors
+               for c in more_contributors do
+                       register_contrib(c, mpackage)
                end
                score += contributors.length.to_f
-
                var mmodules = 0
                var mclasses = 0
                var mmethods = 0
@@ -384,7 +446,7 @@ class Catalog
                                        end
                                end
                                var ms = gs
-                               if m.is_test_suite then ms /= 100.0
+                               if m.is_test then ms /= 100.0
                                entity_score += ms
                                if m.mdoc != null then doc_score += ms else ms /= 10.0
                                for cd in m.mclassdefs do
@@ -417,7 +479,6 @@ class Catalog
                end
                var documentation_score =  (100.0 * doc_score / entity_score).to_i
                self.documentation_score[mpackage] = documentation_score
-
                #score += mmodules.score
                score += mclasses.score
                score += mmethods.score
@@ -433,12 +494,15 @@ class Catalog
                var ini = mpackage.ini
                if ini == null then return
 
+               var root = mpackage.root
+               if root == null then return
+
                # TODO use real git info
                #var repo = ini.get_or_null("upstream.git")
                #var branch = ini.get_or_null("upstream.git.branch")
                #var directory = ini.get_or_null("upstream.git.directory")
 
-               var dirpath = mpackage.root.filepath
+               var dirpath = root.filepath
                if dirpath == null then return
 
                # Collect commits info
@@ -452,8 +516,8 @@ class Catalog
                        if s.length != 2 or s.last == "" then continue
 
                        # Collect date of last and first commit
-                       if mpackage.last_date == null then mpackage.last_date = s.first
-                       mpackage.first_date = s.first
+                       if mpackage.metadata.last_date == null then mpackage.metadata.last_date = s.first
+                       mpackage.metadata.first_date = s.first
 
                        # Count contributors
                        contributors.inc(s.last)
@@ -461,10 +525,132 @@ class Catalog
                for c in contributors.sort.reverse_iterator do
                        register_contrib(c, mpackage)
                end
+       end
+
+       # Compose package stats
+       fun mpackage_stats(mpackage: MPackage): MPackageStats do
+               var stats = new MPackageStats
+               stats.mmodules = mmodules[mpackage]
+               stats.mclasses = mclasses[mpackage]
+               stats.mmethods = mmethods[mpackage]
+               stats.loc = loc[mpackage]
+               stats.errors = errors[mpackage]
+               stats.warnings = warnings[mpackage]
+               stats.warnings_per_kloc = warnings_per_kloc[mpackage]
+               stats.documentation_score = documentation_score[mpackage]
+               stats.commits = commits[mpackage]
+               stats.score = score[mpackage]
+
+               mpackages_stats[mpackage] = stats
+               return stats
+       end
 
+       # Compose catalog stats
+       var catalog_stats: CatalogStats is lazy do
+               var stats = new CatalogStats
+               stats.packages = mpackages.length
+               stats.maintainers = maint2proj.length
+               stats.contributors = contrib2proj.length
+               stats.tags = tag2proj.length
+               stats.modules = mmodules.sum
+               stats.classes = mclasses.sum
+               stats.methods = mmethods.sum
+               stats.loc = loc.sum
+               return stats
        end
 end
 
+# Catalog statistics
+class CatalogStats
+
+       # Number of packages
+       var packages = 0
+
+       # Number of maintainers
+       var maintainers = 0
+
+       # Number of contributors
+       var contributors = 0
+
+       # Number of tags
+       var tags = 0
+
+       # Number of modules
+       var modules = 0
+
+       # Number of classes
+       var classes = 0
+
+       # Number of methods
+       var methods = 0
+
+       # Number of line of codes
+       var loc = 0
+end
+
+# MPackage statistics for the catalog
+class MPackageStats
+
+       # Number of modules
+       var mmodules = 0
+
+       # Number of classes
+       var mclasses = 0
+
+       # Number of methods
+       var mmethods = 0
+
+       # Number of lines of code
+       var loc = 0
+
+       # Number of errors
+       var errors = 0
+
+       # Number of warnings and advices
+       var warnings = 0
+
+       # Number of warnings per 1000 lines of code (w/kloc)
+       var warnings_per_kloc = 0
+
+       # Documentation score (between 0 and 100)
+       var documentation_score = 0
+
+       # Number of commits by package
+       var commits = 0
+
+       # Score by package
+       #
+       # The score is loosely computed using other metrics
+       var score = 0
+end
+
+# Sort the mpackages by their score
+class CatalogScoreSorter
+       super Comparator
+
+       # Catalog used to access scores
+       var catalog: Catalog
+
+       redef type COMPARED: MPackage
+
+       redef fun compare(a, b) do
+               if not catalog.mpackages_stats.has_key(a) then return 1
+               if not catalog.mpackages_stats.has_key(b) then return -1
+               var astats = catalog.mpackages_stats[a]
+               var bstats = catalog.mpackages_stats[b]
+               return bstats.score <=> astats.score
+       end
+end
+
+# Sort tabs alphabetically
+class CatalogTagsSorter
+       super Comparator
+
+       redef type COMPARED: String
+
+       redef fun compare(a, b) do return a <=> b
+end
+
 # Execute a git command and return the result
 fun git_run(command: String...): String
 do
index 867afcf..0fc7008 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_coloring is test_suite
+module test_coloring is test
 
-import test_suite
 import coloring
 
 class TestPOSetColorer
-       super TestSuite
+       test
 
-       fun test_ids_strictly_positive do
+       fun test_ids_strictly_positive is test do
                var poset = new POSet[String]
                poset.add_node "A"
 
index 1537704..208738b 100644 (file)
 # * `nitdoc` wikilinks like `[[doc: MEntity::name]]`
 module doc_commands
 
-# A command aimed at a documentation tool like `nitdoc` or `nitx`.
 #
-# `DocCommand` are generally of the form `command: args`.
-interface DocCommand
+class DocCommandParser
 
-       # Original command string.
-       fun string: String is abstract
+       # List of allowed command names for this parser
+       var allowed_commands: Array[String] = [ "doc", "list", "param", "return",
+               "new", "call", "code", "graph"] is writable
 
-       # Command name.
-       fun name: String is abstract
-
-       # Command arguments.
+       # Parse `string` as a DocCommand
        #
-       # FIXME: define a syntax
-       fun args: Array[String] is abstract
-
-       # Command factory.
+       # Returns `null` if the string cannot be parsed.
+       #
+       # ~~~
+       # var parser = new DocCommandParser
        #
-       # Returns a concrete instance of `DocCommand` depending on the string.
-       new(command_string: String) do
-               if command_string.has_prefix("doc:") then
-                       return new ArticleCommand(command_string)
-               else if command_string.has_prefix("comment:") then
-                       return new CommentCommand(command_string)
-               else if command_string.has_prefix("list:") then
-                       return new ListCommand(command_string)
-               else if command_string.has_prefix("param:") then
-                       return new ParamCommand(command_string)
-               else if command_string.has_prefix("return:") then
-                       return new ReturnCommand(command_string)
-               else if command_string.has_prefix("new:") then
-                       return new NewCommand(command_string)
-               else if command_string.has_prefix("call:") then
-                       return new CallCommand(command_string)
-               else if command_string.has_prefix("code:") then
-                       return new CodeCommand(command_string)
-               else if command_string.has_prefix("graph:") then
-                       return new GraphCommand(command_string)
+       # var command = parser.parse("doc: core::Array")
+       # assert command isa CommentCommand
+       # assert command.arg == "core::Array"
+       #
+       # command = parser.parse(":") # syntax error
+       # assert command == null
+       # assert parser.errors.not_empty
+       # ~~~
+       fun parse(string: String): nullable DocCommand do
+               var pos = 0
+               var tmp = new FlatBuffer
+               errors.clear
+
+               # Parse command name
+               pos = string.read_until(tmp, pos, ':')
+               var name = tmp.write_to_string.trim
+
+               # Check allowed commands
+               if name.is_empty then
+                       error("empty command name", 0)
+                       return null
+               end
+               if not allowed_commands.has(name) then
+                       error("unknown command name", 0)
+                       return null
+               end
+
+               # Build the command
+               var command = new_command(name, string)
+               if command == null then
+                       error("unknown command name", 0)
+                       return null
+               end
+
+               # Parse the argument
+               tmp.clear
+               pos = string.read_until(tmp, pos + 1, '|')
+               var arg = tmp.write_to_string.trim
+               if arg.is_empty then
+                       error("empty command arg", pos)
+                       return null
+               end
+               command.arg = arg
+
+               # Parse command options
+               while pos < string.length do
+                       # Parse option name
+                       tmp.clear
+                       pos = string.read_until(tmp, pos + 1, ':', ',')
+                       var oname = tmp.write_to_string.trim
+                       var oval = ""
+                       if oname.is_empty then break
+                       # Parse option value
+                       if pos < string.length and string[pos] == ':' then
+                               tmp.clear
+                               pos = string.read_until(tmp, pos + 1, ',')
+                               oval = tmp.write_to_string.trim
+                       end
+                       command.opts[oname] = oval
+                       # TODO Check options
                end
-               return new UnknownCommand(command_string)
+
+               return command
+       end
+
+       # Init a new DocCommand from its `name`
+       #
+       # You must redefine this method to add new custom commands.
+       fun new_command(name, string: String): nullable DocCommand do
+               if name == "doc" then return new CommentCommand(string)
+               if name == "list" then return new ListCommand(string)
+               if name == "param" then return new ParamCommand(string)
+               if name == "return" then return new ReturnCommand(string)
+               if name == "new" then return new NewCommand(string)
+               if name == "call" then return new CallCommand(string)
+               if name == "code" then return new CodeCommand(string)
+               if name == "graph" then return new GraphCommand(string)
+               return null
        end
 
-       redef fun to_s do return string
+       # Errors and warnings from last call to `parse`
+       var errors = new Array[DocMessage]
+
+       # Generate an error
+       fun error(message: String, col: nullable Int) do
+               errors.add new DocMessage(1, message, col)
+       end
+
+       # Generate a warning
+       fun warning(message: String, col: nullable Int) do
+               errors.add new DocMessage(2, message, col)
+       end
 end
 
-# Used to factorize initialization of DocCommands.
-abstract class AbstractDocCommand
-       super DocCommand
+# A message generated by the DocCommandParser
+class DocMessage
+
+       # Message severity
+       #
+       # 1- Error
+       # 2- Warning
+       var level: Int
+
+       # Message explanatory string
+       var message: String
 
-       redef var string
-       redef var name is noinit
-       redef var args = new Array[String]
+       # Related column in original string if any
+       var col: nullable Int
 
-       init do
-               # parse command
+       redef fun to_s do
                var str = new FlatBuffer
-               var i = 0
-               while i < string.length do
-                       var c = string[i]
-                       i += 1
-                       if c == ':' then break
-                       str.add c
+               if level == 1 then
+                       str.append "Error: "
+               else
+                       str.append "Warning: "
                end
-               name = str.write_to_string
-               # parse args
-               args.add string.substring_from(i).trim
+               str.append message
+               var col = self.col
+               if col != null then
+                       str.append " (col: {col})"
+               end
+               return str.write_to_string
        end
 end
 
-# A `DocCommand` not recognized by documentation tools.
-#
-# Used to provide warnings or any other behavior for unexisting commands.
-class UnknownCommand
-       super AbstractDocCommand
+redef class Text
+       # Read `self` as raw text until `nend` and append it to the `out` buffer.
+       private fun read_until(out: FlatBuffer, start: Int, nend: Char...): Int do
+               var pos = start
+               while pos < length do
+                       var c = self[pos]
+                       var end_reached = false
+                       for n in nend do
+                               if c == n then
+                                       end_reached = true
+                                       break
+                               end
+                       end
+                       if end_reached then break
+                       out.add c
+                       pos += 1
+               end
+               return pos
+       end
 end
 
-# A `DocCommand` that includes the documentation article of a `MEntity`.
+# A command aimed at a documentation tool like `nitdoc` or `nitx`.
 #
-# Syntax: `doc: MEntity::name`.
-class ArticleCommand
-       super AbstractDocCommand
+# `DocCommand` are generally of the form `command: arg | opt1: val1, opt2: val2`.
+abstract class DocCommand
+
+       # Original command string.
+       var string: String
+
+       # Command name.
+       var name: String is noinit
+
+       # Command arguments.
+       var arg: String is noinit, writable
+
+       # Command options.
+       var opts = new HashMap[String, String] is writable
+
+       redef fun to_s do
+               if opts.is_empty then
+                       return "{name}: {arg}"
+               end
+               return "{name}: {arg} | {opts.join(", ", ": ")}"
+       end
 end
 
-# A `DocCommand` that includes the MDoc of a `MEntity`.
+# A `DocCommand` that includes the documentation article of a `MEntity`.
 #
-# Syntax: `comment: MEntity::name`.
+# Syntax: `doc: MEntity::name`.
 class CommentCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "doc"
 end
 
 # A `DocCommand` that includes a list of something.
 #
 # Syntax: `list:kind: <arg>`.
 class ListCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "list"
 end
 
 # A `DocCommand` that includes the list of methods tanking a `MType` as parameter.
 #
 # Syntax: `param: MType`.
 class ParamCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "param"
 end
 
 # A `DocCommand` that includes the list of methods returning a `MType` as parameter.
 #
-# Syntax: `param: MType`.
+# Syntax: `return: MType`.
 class ReturnCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "return"
 end
 
 # A `DocCommand` that includes the list of methods creating new instances of a specific `MType`
 #
 # Syntax: `new: MType`.
 class NewCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "new"
 end
 
 # A `DocCommand` that includes the list of methods calling a specific `MProperty`.
 #
 # Syntax: `call: MEntity::name`.
 class CallCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "call"
 end
 
 # A `DocCommand` that includes the source code of a `MEntity`.
@@ -151,7 +265,9 @@ end
 # * `./src/file.nit` to include source code from a file.
 # * `./src/file.nit:1,2--3,4` to select code between positions.
 class CodeCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "code"
 end
 
 # A `DocCommand` that display an graph for a `MEntity`.
@@ -159,5 +275,7 @@ end
 # Syntax:
 # * `graph: MEntity::name`
 class GraphCommand
-       super AbstractDocCommand
+       super DocCommand
+
+       redef var name = "graph"
 end
index dbb5252..eedfdf6 100644 (file)
@@ -28,7 +28,7 @@ redef class MDoc
        var comment: String is lazy do
                var lines = content.to_a
                if not lines.is_empty then lines.shift
-               return content.join("\n")
+               return lines.join("\n")
        end
 
        # Full comment HTML escaped.
index e8cb281..6a5d045 100644 (file)
@@ -88,13 +88,27 @@ class Nitx
                prompt
        end
 
+       # Parser used to process doc commands
+       var parser: DocCommandParser is lazy do
+               var parser = new DocCommandParser
+               parser.allowed_commands = ["doc", "comment", "list", "param", "return",
+                       "new", "call", "code"]
+               return parser
+       end
+
        # Processes the query string and performs it.
        fun do_query(str: String) do
-               var query = new DocCommand(str)
-               if query isa NitxCommand then
-                       query.execute(self)
+               if str == ":q" then
+                       exit 0
+               else if str == ":h" then
+                       help
                        return
                end
+               var query = parser.parse(str)
+               if query == null then
+                       query = new CommentCommand(str)
+                       query.arg = str
+               end
                var res = query.perform(self, doc)
                var suggest = null
                if res.is_empty then
@@ -105,27 +119,14 @@ class Nitx
        end
 end
 
-redef interface DocCommand
-
-       redef new(query_string) do
-               if query_string == ":q" then
-                       return new NitxQuit
-               else if query_string == ":h" then
-                       return new NitxHelp
-               end
-               var cmd = super(query_string)
-               if cmd isa UnknownCommand then
-                       return new CommentCommand("comment: {query_string}")
-               end
-               return cmd
-       end
+redef class DocCommand
 
        # Looks up the `doc` model and returns possible matches.
        fun perform(nitx: Nitx, doc: DocModel): Array[NitxMatch] is abstract
 
        # Looks up the `doc` model and returns possible suggestions.
        fun suggest(nitx: Nitx, doc: DocModel): nullable Array[MEntity] do
-               return find_suggestions(doc, args.first)
+               return find_suggestions(doc, arg)
        end
 
        # Pretty prints the results for the console.
@@ -184,7 +185,7 @@ class MEntityMatch
 end
 
 redef class CommentCommand
-       redef fun perform(nitx, doc) do return find_mentities(doc, args.first)
+       redef fun perform(nitx, doc) do return find_mentities(doc, arg)
 
        redef fun make_results(nitx, results, suggest) do
                var len = results.length
@@ -207,7 +208,7 @@ end
 redef class ParamCommand
        redef fun perform(nitx, doc) do
                var res = new Array[NitxMatch]
-               var mtype_name = args.first
+               var mtype_name = arg
                for mproperty in doc.mproperties do
                        if not mproperty isa MMethod then continue
                        var msignature = mproperty.intro.msignature
@@ -227,7 +228,7 @@ end
 redef class ReturnCommand
        redef fun perform(nitx, doc) do
                var res = new Array[NitxMatch]
-               var mtype_name = args.first
+               var mtype_name = arg
                for mproperty in doc.mproperties do
                        if not mproperty isa MMethod then continue
                        var msignature = mproperty.intro.msignature
@@ -246,7 +247,7 @@ end
 redef class NewCommand
        redef fun perform(nitx, doc) do
                var res = new Array[NitxMatch]
-               var mtype_name = args.first
+               var mtype_name = arg
                for mpropdef in doc.mpropdefs do
                        var visitor = new TypeInitVisitor(mtype_name)
                        var npropdef = nitx.ctx.modelbuilder.mpropdef2node(mpropdef)
@@ -264,7 +265,7 @@ end
 redef class CallCommand
        redef fun perform(nitx, doc) do
                var res = new Array[NitxMatch]
-               var mprop_name = args.first
+               var mprop_name = arg
                for mpropdef in doc.mpropdefs do
                        var visitor = new MPropertyCallVisitor
                        var npropdef = nitx.ctx.modelbuilder.mpropdef2node(mpropdef)
@@ -279,38 +280,6 @@ redef class CallCommand
        end
 end
 
-# A query to search a Nitdoc documentation page by its name.
-redef class ArticleCommand
-       redef fun perform(nitx, doc) do
-               var res = new Array[NitxMatch]
-               var name = args.first
-               for page in doc.pages.values do
-                       if name == "*" then # FIXME dev only
-                               res.add new PageMatch(self, page)
-                       else if page.title == name then
-                               res.add new PageMatch(self, page)
-                       else if page isa MEntityPage and page.mentity.cs_namespace == name then
-                               res.add new PageMatch(self, page)
-                       end
-               end
-               return res
-       end
-
-       redef fun make_results(nitx, results, suggest) do
-               var len = results.length
-               # FIXME how to render the pager for one worded namespaces like "core"?
-               if len == 1 then
-                       var page = results.first.as(PageMatch).page
-                       var pager = new Pager
-                       pager.add page.write_to_string
-                       pager.render
-                       return page
-               else
-                       return super
-               end
-       end
-end
-
 # A match between a `DocPage` and a `MEntity`.
 class PageMatch
        super NitxMatch
@@ -402,7 +371,7 @@ redef class CodeCommand
        # FIXME refactor this!
        redef fun perform(nitx, doc) do
                var res = new Array[NitxMatch]
-               var name = args.first
+               var name = arg
                # if name is an existing sourcefile, opens it
                if name.file_exists then
                        var fr = new FileReader.open(name)
@@ -442,32 +411,6 @@ class CodeMatch
        redef fun make_list_item do return "* {location}"
 end
 
-
-# A query that contains a nitx command.
-#
-# These commands are prefixed with `:` and are used to control the execution of
-# `nitx` like displaying the help or quiting.
-interface NitxCommand
-       super DocCommand
-
-       # Executes the command.
-       fun execute(nitx: Nitx) is abstract
-end
-
-# Exits nitx.
-class NitxQuit
-       super NitxCommand
-
-       redef fun execute(nitx) do exit 0
-end
-
-# Displays the help message.
-class NitxHelp
-       super NitxCommand
-
-       redef fun execute(nitx) do nitx.help
-end
-
 ## exploration
 
 # Visitor looking for initialized `MType` (new T).
index c026b77..a31f107 100644 (file)
@@ -38,7 +38,8 @@ class ReadmePhase
        fun warning(location: nullable MDLocation, page: ReadmePage, message: String) do
                var loc = null
                if location != null then
-                       loc = location.to_location(page.mentity.mdoc.location.file)
+                       var mdoc = page.mentity.mdoc
+                       if mdoc != null then loc = location.to_location(mdoc.location.file)
                end
                ctx.warning(loc, "readme-warning", message)
        end
@@ -51,14 +52,15 @@ end
 
 redef class ReadmePage
        redef fun build_content(v, doc) do
-               if mentity.mdoc == null then
+               var mdoc = mentity.mdoc
+               if mdoc == null then
                        v.warning(null, self, "Empty README for group `{mentity}`")
                        return
                end
                var proc = new MarkdownProcessor
                proc.emitter = new ReadmeMdEmitter(proc, self, v)
                proc.emitter.decorator = new ReadmeDecorator
-               var md = mentity.mdoc.content.join("\n")
+               var md = mdoc.content.join("\n")
                proc.process(md)
        end
 end
@@ -91,6 +93,7 @@ class ReadmeMdEmitter
        # Called from `add_headline`.
        private fun open_section(lvl: Int, title: String) do
                var section = new ReadmeSection(title.escape_to_c, title, lvl, processor)
+               var current_section = self.current_section
                if current_section == null then
                        page.root.add_child(section)
                else
@@ -119,6 +122,7 @@ class ReadmeMdEmitter
        # This closes the current article, inserts `article` then opens a new article.
        private fun add_article(article: DocArticle) do
                close_article
+               var current_section = self.current_section
                if current_section == null then
                        page.root.add_child(article)
                else
@@ -184,15 +188,18 @@ end
 class ReadmeDecorator
        super MdDecorator
 
+       # Parser used to process doc commands
+       var parser = new DocCommandParser
+
        redef type EMITTER: ReadmeMdEmitter
 
        redef fun add_headline(v, block) do
-               var txt = block.block.first_line.value
+               var txt = block.block.first_line.as(not null).value
                var lvl = block.depth
                if not v.context.is_empty then
                        v.close_article
                        while v.current_section != null do
-                               if v.current_section.depth < lvl then break
+                               if v.current_section.as(not null).depth < lvl then break
                                v.close_section
                        end
                end
@@ -201,9 +208,9 @@ class ReadmeDecorator
        end
 
        redef fun add_wikilink(v, token) do
-               var link = token.link.to_s
-               var cmd = new DocCommand(link)
-               if cmd isa UnknownCommand then
+               var link = token.link.as(not null).to_s
+               var cmd = parser.parse(link)
+               if cmd == null then
                        # search MEntities by name
                        var res = v.find_mentities(link.to_s)
                        # no match, print warning and display wikilink as is
@@ -223,20 +230,21 @@ class ReadmeDecorator
                # TODO real link
                var link = mentity.full_name
                if name == null then name = mentity.name
-               if comment == null and mentity.mdoc != null then
-                       comment = mentity.mdoc.synopsis
+               if comment == null then
+                       var mdoc = mentity.mdoc
+                       if mdoc != null then comment = mdoc.synopsis
                end
                add_link(v, link, name, comment)
        end
 end
 
-redef interface DocCommand
+redef class DocCommand
 
        # Render the content of the doc command.
        fun render(v: ReadmeMdEmitter, token: TokenWikiLink) is abstract
 end
 
-redef class ArticleCommand
+redef class CommentCommand
        redef fun render(v, token) do
                var string = args.first
                var res = v.find_mentities(string)
diff --git a/src/doc/test_doc_commands.nit b/src/doc/test_doc_commands.nit
new file mode 100644 (file)
index 0000000..82f5e7c
--- /dev/null
@@ -0,0 +1,143 @@
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+module test_doc_commands is test
+
+import doc_commands
+
+class TestDocCommandParser
+       test
+
+       var parser: DocCommandParser
+
+       fun init_parser is before do
+               parser = new DocCommandParser
+       end
+
+       fun test_empty_string is test do
+               var command = parser.parse("")
+               assert command == null
+               assert parser.errors.length == 1
+               assert parser.errors.first.to_s == "Error: empty command name (col: 0)"
+       end
+
+       fun test_bad_string is test do
+               var command = parser.parse(":")
+               assert command == null
+               assert parser.errors.length == 1
+               assert parser.errors.first.to_s == "Error: empty command name (col: 0)"
+       end
+
+       fun test_unknown_command is test do
+               var command = parser.parse("foo: foo")
+               assert command == null
+               assert parser.errors.length == 1
+               assert parser.errors.first.to_s == "Error: unknown command name (col: 0)"
+       end
+
+       fun test_unallowed_command is test do
+               parser.allowed_commands.clear
+               var command = parser.parse("comment: core::Array")
+               assert command == null
+               assert parser.errors.length == 1
+               assert parser.errors.first.to_s == "Error: unknown command name (col: 0)"
+       end
+
+       fun test_no_arg is test do
+               var command = parser.parse("doc:")
+               assert command == null
+               assert parser.errors.length == 1
+               print parser.errors.first
+               assert parser.errors.first.to_s == "Error: empty command arg (col: 4)"
+       end
+
+       fun test_no_opts is test do
+               var command = parser.parse("doc: core::Array")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert parser.errors.is_empty
+       end
+
+       fun test_opts_empty is test do
+               var command = parser.parse("doc: core::Array | ")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert parser.errors.is_empty
+       end
+
+       fun test_1_opt is test do
+               var command = parser.parse("doc: core::Array | opt1: val1 ")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert command.opts.length == 1
+               assert command.opts["opt1"] == "val1"
+               assert parser.errors.is_empty
+       end
+
+       fun test_2_opts is test do
+               var command = parser.parse("doc: core::Array | opt1: val1 , opt2: val2,  ")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert command.opts.length == 2
+               assert command.opts["opt1"] == "val1"
+               assert command.opts["opt2"] == "val2"
+               assert parser.errors.is_empty
+       end
+
+       fun test_empty_opt_name is test do
+               var command = parser.parse("doc: core::Array | opt1: val1  , :")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert command.opts.length == 1
+               assert command.opts["opt1"] == "val1"
+               assert parser.errors.is_empty
+       end
+
+       fun test_empty_opt_value is test do
+               var command = parser.parse("doc: core::Array | opt1:  , opt2: val2,  ")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert command.opts.length == 2
+               assert command.opts["opt1"] == ""
+               assert command.opts["opt2"] == "val2"
+               assert parser.errors.is_empty
+       end
+
+       fun test_empty_opt_value2 is test do
+               var command = parser.parse("doc: core::Array | opt1")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert command.opts.length == 1
+               assert command.opts["opt1"] == ""
+               assert parser.errors.is_empty
+       end
+
+       fun test_empty_opt_value3 is test do
+               var command = parser.parse("doc: core::Array | opt1, opt2: val2")
+               assert command isa CommentCommand
+               assert command.name == "doc"
+               assert command.arg == "core::Array"
+               assert command.opts.length == 2
+               assert command.opts["opt1"] == ""
+               assert command.opts["opt2"] == "val2"
+               assert parser.errors.is_empty
+       end
+end
index 97efb63..54d9a01 100644 (file)
@@ -48,8 +48,8 @@ private class NoWarningPhase
 
                var modelbuilder = toolcontext.modelbuilder
 
-               # Disable `missing-doc` for `test_suite`
-               if source != null and not nmoduledecl.get_annotations("test_suite").is_empty then
+               # Disable `missing-doc` for `test`
+               if source != null and not nmoduledecl.get_annotations("test").is_empty then
                        toolcontext.warning_blacklist[source].add("missing-doc")
                end
 
index b2a9687..409a994 100644 (file)
@@ -106,12 +106,26 @@ end
 
 redef class MModule
        super AnnotatedMEntity
+
+       redef var is_test is lazy do return has_annotation("test")
 end
 
 redef class MClassDef
        super AnnotatedMEntity
+
+       redef var is_test is lazy do return has_annotation("test")
 end
 
 redef class MPropDef
        super AnnotatedMEntity
+
+       redef var is_test is lazy do return has_annotation("test")
+
+       redef var is_before is lazy do return has_annotation("before")
+
+       redef var is_before_all is lazy do return has_annotation("before_all")
+
+       redef var is_after is lazy do return has_annotation("after")
+
+       redef var is_after_all is lazy do return has_annotation("after_all")
 end
index 615aba9..125866a 100644 (file)
@@ -812,8 +812,6 @@ redef class ModelBuilder
                                mmodule.mdoc = mdoc
                                mdoc.original_mentity = mmodule
                        end
-                       # Is the module a test suite?
-                       mmodule.is_test_suite = not decl.get_annotations("test_suite").is_empty
                        # Is the module generated?
                        mmodule.is_generated = not decl.get_annotations("generated").is_empty
                end
index 9d1fb9c..a410236 100644 (file)
@@ -248,9 +248,6 @@ class MModule
                end
        end
 
-       # Is `self` a unit test module used by `nitunit`?
-       var is_test_suite: Bool = false is writable
-
        # Is `self` a module generated by a tool?
        #
        # This flag has no effect on the semantic.
index e9e3afb..dc9b978 100644 (file)
@@ -588,6 +588,8 @@ class MClass
        # Is `self` and abstract class?
        var is_abstract: Bool is lazy do return kind == abstract_kind
 
+       redef var is_test is lazy do return intro.is_test
+
        redef fun mdoc_or_fallback
        do
                # Don’t use `intro.mdoc_or_fallback` because it would create an infinite
@@ -2327,6 +2329,20 @@ abstract class MProperty
        end
 
        private var lookup_all_definitions_cache = new HashMap2[MModule, MType, Array[MPROPDEF]]
+
+       redef var is_test is lazy do return intro.is_test
+
+       # Does self have the `before` annotation?
+       var is_before: Bool is lazy do return intro.is_before
+
+       # Does self have the `before_all` annotation?
+       var is_before_all: Bool is lazy do return intro.is_before_all
+
+       # Does self have the `after` annotation?
+       var is_after: Bool is lazy do return intro.is_after
+
+       # Does self have the `after_all` annotation?
+       var is_after_all: Bool is lazy do return intro.is_after_all
 end
 
 # A global method
@@ -2554,6 +2570,18 @@ abstract class MPropDef
        end
 
        redef fun mdoc_or_fallback do return mdoc or else mproperty.mdoc_or_fallback
+
+       # Does self have the `before` annotation?
+       var is_before = false is writable
+
+       # Does self have the `before_all` annotation?
+       var is_before_all = false is writable
+
+       # Does self have the `after` annotation?
+       var is_after = false is writable
+
+       # Does self have the `after_all` annotation?
+       var is_after_all = false is writable
 end
 
 # A local definition of a method
index 0c136b8..0a0d8b0 100644 (file)
@@ -103,6 +103,11 @@ abstract class MEntity
        # Fictive entities are used internally but they should not be
        # exposed to the final user.
        var is_fictive: Bool = false is writable
+
+       # Is `self` created for unit testing purpose?
+       #
+       # See `nitunit`.
+       var is_test: Bool = false is writable
 end
 
 # Something that represents a concern
index 2f0eed5..8b0f122 100644 (file)
@@ -122,7 +122,7 @@ class ModelView
                v.include_fictive = self.include_fictive
                v.include_empty_doc = self.include_empty_doc
                v.include_attribute = self.include_attribute
-               v.include_test_suite = self.include_test_suite
+               v.include_test = self.include_test
        end
 
        # Searches the MEntity that matches `full_name`.
index 59d3e61..9244055 100644 (file)
@@ -104,13 +104,20 @@ abstract class ModelVisitor
        # Should we accept nitunit test suites?
        #
        # Default is `false`.
-       var include_test_suite = false is writable
+       var include_test = false is writable
 
        # Can we accept this `mentity` regarding its test suite status?
-       fun accept_test_suite(mentity: MEntity): Bool do
-               if include_test_suite then return true
-               if not mentity isa MModule then return true
-               return not mentity.is_test_suite
+       fun accept_test(mentity: MEntity): Bool do
+               if include_test then return true
+               if mentity isa MProperty then
+                       if mentity.is_before or mentity.is_before_all then return false
+                       if mentity.is_after or mentity.is_after_all then return false
+               end
+               if mentity isa MPropDef then
+                       if mentity.is_before or mentity.is_before_all then return false
+                       if mentity.is_after or mentity.is_after_all then return false
+               end
+               return not mentity.is_test
        end
 
        # Should we accept `MAttribute` instances?
@@ -131,7 +138,7 @@ abstract class ModelVisitor
                if not accept_visibility(mentity) then return false
                if not accept_fictive(mentity) then return false
                if not accept_empty_doc(mentity) then return false
-               if not accept_test_suite(mentity) then return false
+               if not accept_test(mentity) then return false
                if not accept_attribute(mentity) then return false
                return true
        end
index 897dfd5..c544446 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_model_json is test_suite
+module test_model_json is test
 
-import test_suite
 import model_json
 import frontend
 
 class TestModelSerialization
-       super TestSuite
+       test
 
        var suite_path: String = "NIT_TESTING_PATH".environ
        var lib_path: String = "{suite_path.dirname}/../../tests/test_prog"
@@ -35,7 +34,7 @@ class TestModelSerialization
                return model
        end
 
-       fun test_refs_to_full_json do
+       fun test_refs_to_full_json is test do
                var mentities = new Array[MEntity]
                mentities.add model.mpackages.first
                mentities.add model.mmodules.first
@@ -45,13 +44,13 @@ class TestModelSerialization
                end
        end
 
-       fun test_packages_to_full_json do
+       fun test_packages_to_full_json is test do
                for mentity in model.mpackages do
                        print mentity.to_pretty_full_json
                end
        end
 
-       fun test_groups_to_full_json do
+       fun test_groups_to_full_json is test do
                for mpackage in model.mpackages do
                        for mentity in mpackage.mgroups do
                                print mentity.to_pretty_full_json
@@ -59,19 +58,19 @@ class TestModelSerialization
                end
        end
 
-       fun test_modules_to_full_json do
+       fun test_modules_to_full_json is test do
                for mentity in model.mmodules do
                        print mentity.to_pretty_full_json
                end
        end
 
-       fun test_classes_to_full_json do
+       fun test_classes_to_full_json is test do
                for mentity in model.mclasses do
                        print mentity.to_pretty_full_json
                end
        end
 
-       fun test_classdefs_to_full_json do
+       fun test_classdefs_to_full_json is test do
                for mclass in model.mclasses do
                        for mentity in mclass.mclassdefs do
                                print mentity.to_pretty_full_json
@@ -79,13 +78,13 @@ class TestModelSerialization
                end
        end
 
-       fun test_props_to_full_json do
+       fun test_props_to_full_json is test do
                for mentity in model.mproperties do
                        print mentity.to_pretty_full_json
                end
        end
 
-       fun test_propdefs_to_full_json do
+       fun test_propdefs_to_full_json is test do
                for mprop in model.mproperties do
                        for mentity in mprop.mpropdefs do
                                print mentity.to_pretty_full_json
index 982e206..c116234 100644 (file)
@@ -267,12 +267,12 @@ redef class Catalog
 <div class="sidebar">
 <ul class="box">
 """
-               var tryit = mpackage.metadata("upstream.tryit")
+               var tryit = mpackage.metadata.metadata("upstream.tryit")
                if tryit != null then
                        var e = tryit.html_escape
                        res.add "<li><a href=\"{e}\">Try<span style=\"color:white\">n</span>it!</a></li>\n"
                end
-               var apk = mpackage.metadata("upstream.apk")
+               var apk = mpackage.metadata.metadata("upstream.apk")
                if apk != null then
                        var e = apk.html_escape
                        res.add "<li><a href=\"{e}\">Android apk</a></li>\n"
@@ -280,15 +280,15 @@ redef class Catalog
 
                res.add """</ul>\n<ul class="box">\n"""
 
-               var homepage = mpackage.metadata("upstream.homepage")
+               var homepage = mpackage.metadata.metadata("upstream.homepage")
                if homepage != null then
                        var e = homepage.html_escape
                        res.add "<li><a href=\"{e}\">{e}</a></li>\n"
                end
-               for maintainer in mpackage.maintainers do
+               for maintainer in mpackage.metadata.maintainers do
                        res.add "<li>{maintainer.to_html}</li>"
                end
-               var license = mpackage.metadata("package.license")
+               var license = mpackage.metadata.metadata("package.license")
                if license != null then
                        var e = license.html_escape
                        res.add "<li><a href=\"http://opensource.org/licenses/{e}\">{e}</a> license</li>\n"
@@ -296,22 +296,22 @@ redef class Catalog
                res.add "</ul>\n"
 
                res.add "<h3>Source Code</h3>\n<ul class=\"box\">\n"
-               var browse = mpackage.metadata("upstream.browse")
+               var browse = mpackage.metadata.metadata("upstream.browse")
                if browse != null then
                        var e = browse.html_escape
                        res.add "<li><a href=\"{e}\">{e}</a></li>\n"
                end
-               var git = mpackage.metadata("upstream.git")
+               var git = mpackage.metadata.metadata("upstream.git")
                if git != null then
                        var e = git.html_escape
                        res.add "<li><tt>{e}</tt></li>\n"
                end
-               var last_date = mpackage.last_date
+               var last_date = mpackage.metadata.last_date
                if last_date != null then
                        var e = last_date.html_escape
                        res.add "<li>most recent commit: {e}</li>\n"
                end
-               var first_date = mpackage.first_date
+               var first_date = mpackage.metadata.first_date
                if first_date != null then
                        var e = first_date.html_escape
                        res.add "<li>oldest commit: {e}</li>\n"
@@ -333,7 +333,7 @@ redef class Catalog
 
                res.add "<h3>Tags</h3>\n"
                var ts2 = new Array[String]
-               for t in mpackage.tags do
+               for t in mpackage.metadata.tags do
                        t = t.html_escape
                        ts2.add "<a href=\"../index.html#tag_{t}\">{t}</a>"
                end
@@ -381,7 +381,7 @@ redef class Catalog
                        end
                end
 
-               var contributors = mpackage.contributors
+               var contributors = mpackage.metadata.contributors
                if not contributors.is_empty then
                        res.add "<h3>Contributors</h3>\n<ul class=\"box\">"
                        for c in contributors do
@@ -499,9 +499,9 @@ redef class Catalog
                        res.add "<tr>"
                        res.add "<td><a href=\"p/{p.name}.html\">{p.name}</a></td>"
                        var maint = "?"
-                       if p.maintainers.not_empty then maint = p.maintainers.first.name.html_escape
+                       if p.metadata.maintainers.not_empty then maint = p.metadata.maintainers.first.name.html_escape
                        res.add "<td>{maint}</td>"
-                       res.add "<td>{p.contributors.length}</td>"
+                       res.add "<td>{p.metadata.contributors.length}</td>"
                        if deps.not_empty then
                                res.add "<td>{deps[p].greaters.length-1}</td>"
                                res.add "<td>{deps[p].direct_greaters.length}</td>"
index 772ec38..a0addf1 100644 (file)
@@ -49,20 +49,19 @@ To test a method you have to instanciate its class:
 
 TestSuites are Nit files that define a set of TestCase for a particular module.
 
-The test suite module must be declared using the `test_suite` annotation.
+The test suite module must be declared using the `test` annotation.
 The structure of a test suite is the following:
 
        # test suite for module `foo`
-       module test_foo is test_suite
+       module test_foo is test
 
-       import test_suite # import the `TestSuite` class and the `test_suite` annotation
        import foo # can be intrude to test private things
 
        class TestFoo
-               super TestSuite
+               test
 
                # test case for `foo::Foo::baz`
-               fun test_baz do
+               fun baz is test do
                        var subject = new Foo
                        assert subject.baz(1, 2) == 3
                end
@@ -79,18 +78,18 @@ Otherwise, you can use the `-t` option to specify the test suite module name:
 
        $ nitunit foo.nit -t my_test_suite.nit
 
-`nitunit` will execute a test for each method named `test_*` in a class named `Test*`
+`nitunit` will execute a test for each method annotated with `test` in a class also annotated with `test`
 so multiple tests can be executed for a single method:
 
        class TestFoo
-               super TestSuite
+               test
 
-               fun test_baz_1 do
+               fun baz_1 is test do
                        var subject = new Foo
                        assert subject.baz(1, 2) == 3
                end
 
-               fun test_baz_2 do
+               fun baz_2 is test do
                        var subject = new Foo
                        assert subject.baz(1, -2) == -1
                end
@@ -98,51 +97,50 @@ so multiple tests can be executed for a single method:
 
 `TestSuites` also provide methods to configure the test run:
 
-`before_test` and `after_test`: methods called before/after each test case.
+`before` and `after` annotations can be added to methods that must be called before/after each test case.
 They can be used to factorize repetitive tasks:
 
        class TestFoo
-               super TestSuite
+               test
 
                var subject: Foo is noinit
 
                # Method executed before each test
-               redef fun before_test do
+               redef fun set_up is before do
                        subject = new Foo
                end
 
-               fun test_baz_1 do
+               fun baz_1 is test do
                        assert subject.baz(1, 2) == 3
                end
 
-               fun test_baz_2 do
+               fun baz_2 is test do
                        assert subject.baz(1, -2) == -1
                end
        end
 
 When using custom test attributes, a empty init must be declared to allow automatic test running.
 
-`before_module` and `after_module`: methods called before/after each test suite.
+`before_all` and `after_all` annotations can be set on methods that must be called before/after each test suite.
 They have to be declared at top level:
 
        module test_bdd_connector
 
-       import test_suite
        import bdd_connector
 
        # Testing the bdd_connector
        class TestConnector
-               super TestSuite
+               test
                # test cases using a server
        end
 
        # Method executed before testing the module
-       redef fun before_module do
+       fun before_module is before_all do
                # start server before all test cases
        end
 
        # Method executed after testing the module
-       redef fun after_module do
+       fun after_module is after_all do
                # stop server after all test cases
        end
 
index 2564c5e..a444bee 100644 (file)
@@ -27,9 +27,8 @@ class NitUnitGenerator
        fun gen_unit(mmodule: MModule, test_file: String): Template do
                var with_private = toolcontext.opt_gen_private.value
                var tpl = new Template
-               tpl.addn "module test_{mmodule.name} is test_suite"
+               tpl.addn "module test_{mmodule.name} is test"
                tpl.addn ""
-               tpl.addn "import test_suite"
                if with_private then
                        tpl.addn "intrude import {mmodule.name}"
                else
@@ -39,7 +38,7 @@ class NitUnitGenerator
                        if mclassdef.mclass.kind != concrete_kind then continue
                        tpl.addn ""
                        tpl.addn "class Test{mclassdef.name}"
-                       tpl.addn "\tsuper TestSuite"
+                       tpl.addn "\ttest"
                        for mpropdef in mclassdef.mpropdefs do
                                if not mpropdef isa MMethodDef then continue
                                var mproperty = mpropdef.mproperty
@@ -48,7 +47,7 @@ class NitUnitGenerator
                                if not with_private and mproperty.visibility <= protected_visibility then continue
                                var case_name = case_name(mpropdef)
                                tpl.addn ""
-                               tpl.addn "\tfun {case_name} do"
+                               tpl.addn "\tfun {case_name} is test do"
                                tpl.addn "\t\tassert not_implemented: false # TODO remove once implemented"
                                tpl.addn ""
                                tpl.addn gen_init(mclassdef)
index 295598b..43ac8f5 100644 (file)
@@ -17,7 +17,7 @@ module testing_suite
 
 import testing_base
 import html
-private import annotation
+private import parse_annotations
 private import realtime
 
 redef class ToolContext
@@ -38,29 +38,33 @@ class NitUnitTester
                var toolcontext = mbuilder.toolcontext
                var suite = new TestSuite(mmodule, toolcontext)
                # method to execute before all tests in the module
-               var before_module = mmodule.before_test
-               if before_module != null then
+               for mmethod in mmodule.before_all do
                        toolcontext.modelbuilder.total_tests += 1
-                       suite.before_module = new TestCase(suite, before_module, toolcontext)
+                       suite.before_all.add new TestCase(suite, mmethod, toolcontext)
                end
                # generate all test cases
                for mclassdef in mmodule.mclassdefs do
                        if not mclassdef.is_test then continue
                        if not suite_match_pattern(mclassdef) then continue
                        toolcontext.modelbuilder.total_classes += 1
+
+                       var before = mclassdef.before
+                       var after = mclassdef.after
+
                        for mpropdef in mclassdef.mpropdefs do
                                if not mpropdef isa MMethodDef or not mpropdef.is_test then continue
                                if not case_match_pattern(mpropdef) then continue
                                toolcontext.modelbuilder.total_tests += 1
                                var test = new TestCase(suite, mpropdef, toolcontext)
-                               suite.add_test test
+                               test.before = before
+                               test.after = after
+                               suite.test_cases.add test
                        end
                end
                # method to execute after all tests in the module
-               var after_module = mmodule.after_test
-               if after_module != null then
+               for mmethod in mmodule.after_all do
                        toolcontext.modelbuilder.total_tests += 1
-                       suite.after_module = new TestCase(suite, after_module, toolcontext)
+                       suite.after_all.add new TestCase(suite, mmethod, toolcontext)
                end
                suite.run
                return suite
@@ -113,20 +117,17 @@ class TestSuite
        # List of `TestCase` to be executed in this suite.
        var test_cases = new Array[TestCase]
 
-       # Add a `TestCase` to the suite.
-       fun add_test(case: TestCase) do test_cases.add case
-
-       # Test to be executed before the whole test suite.
-       var before_module: nullable TestCase = null
+       # Tests to be executed before the whole test suite.
+       var before_all = new Array[TestCase]
 
-       # Test to be executed after the whole test suite.
-       var after_module: nullable TestCase = null
+       # Tests to be executed after the whole test suite.
+       var after_all = new Array[TestCase]
 
        # Display test suite status in std-out.
        fun show_status do
                var test_cases = self.test_cases.to_a
-               if before_module != null then test_cases.add before_module.as(not null)
-               if after_module != null then test_cases.add after_module.as(not null)
+               test_cases.add_all before_all
+               test_cases.add_all after_all
                toolcontext.show_unit_status("Test-suite of module " + mmodule.full_name, test_cases)
        end
 
@@ -152,10 +153,7 @@ class TestSuite
                end
                toolcontext.info("Execute test-suite {mmodule.name}", 1)
 
-               var before_module = self.before_module
-               var after_module = self.after_module
-
-               if before_module != null then
+               for before_module in before_all do
                        before_module.run
                        toolcontext.clear_progress_bar
                        toolcontext.show_unit(before_module)
@@ -165,7 +163,7 @@ class TestSuite
                                        toolcontext.clear_progress_bar
                                        toolcontext.show_unit(case)
                                end
-                               if after_module != null then
+                               for after_module in after_all do
                                        after_module.fail "Nitunit Error: before_module test failed"
                                        toolcontext.clear_progress_bar
                                        toolcontext.show_unit(after_module)
@@ -183,7 +181,7 @@ class TestSuite
                        show_status
                end
 
-               if not after_module == null then
+               for after_module in after_all do
                        after_module.run
                        toolcontext.clear_progress_bar
                        toolcontext.show_unit(after_module)
@@ -197,18 +195,16 @@ class TestSuite
        # Write the test unit for `self` in a nit compilable file.
        fun write_to_nit do
                var file = new Template
-               file.addn "intrude import test_suite"
+               file.addn "intrude import core"
                file.addn "import {mmodule.name}\n"
                file.addn "var name = args.first"
-               var before_module = self.before_module
-               if before_module != null then
+               for before_module in before_all do
                        before_module.write_to_nit(file)
                end
                for case in test_cases do
                        case.write_to_nit(file)
                end
-               var after_module = self.after_module
-               if after_module != null then
+               for after_module in after_all do
                        after_module.write_to_nit(file)
                end
                file.write_to_file("{test_file}.nit")
@@ -272,6 +268,12 @@ class TestCase
        # Test method to be compiled and tested.
        var test_method: MMethodDef
 
+       # Cases to execute before this one
+       var before = new Array[MMethodDef]
+
+       # Cases to execute after this one
+       var after = new Array[MMethodDef]
+
        redef fun full_name do return test_method.full_name
 
        redef fun location do return test_method.location
@@ -286,10 +288,14 @@ class TestCase
                if test_method.mproperty.is_toplevel then
                        file.addn "\t{name}"
                else
-                       file.addn "\tvar subject = new {test_method.mclassdef.name}.nitunit"
-                       file.addn "\tsubject.before_test"
+                       file.addn "\tvar subject = new {test_method.mclassdef.name}.intern"
+                       for mmethod in before do
+                               file.addn "\tsubject.{mmethod.name}"
+                       end
                        file.addn "\tsubject.{name}"
-                       file.addn "\tsubject.after_test"
+                       for mmethod in after do
+                               file.addn "\tsubject.{mmethod.name}"
+                       end
                end
                file.addn "end"
        end
@@ -374,54 +380,87 @@ class TestCase
        end
 end
 
-redef class MMethodDef
-       # TODO use annotations?
-
-       # Is the method a test_method?
-       # i.e. begins with "test_"
-       private fun is_test: Bool do return name.has_prefix("test_")
+redef class MClassDef
+       # Methods tagged with `before` in this class definition
+       private fun before: Array[MMethodDef] do
+               var res = new Array[MMethodDef]
+               for mpropdef in mpropdefs do
+                       if mpropdef isa MMethodDef and mpropdef.is_before then
+                               res.add mpropdef
+                       end
+               end
+               var in_hierarchy = self.in_hierarchy
+               if in_hierarchy == null then return res
+               for mclassdef in in_hierarchy.direct_greaters do
+                       res.add_all mclassdef.before
+               end
+               return res
+       end
 
-       # Is the method a "before_module"?
-       private fun is_before_module: Bool do return name == "before_module"
+       # Methods tagged with `before_all` in this class definition
+       private fun before_all: Array[MMethodDef] do
+               var res = new Array[MMethodDef]
+               for mpropdef in mpropdefs do
+                       if mpropdef isa MMethodDef and mpropdef.is_before_all then
+                               res.add mpropdef
+                       end
+               end
+               var in_hierarchy = self.in_hierarchy
+               if in_hierarchy == null then return res
+               for mclassdef in in_hierarchy.direct_greaters do
+                       res.add_all mclassdef.before_all
+               end
+               return res
+       end
 
-       # Is the method a "after_module"?
-       private fun is_after_module: Bool do return name == "after_module"
-end
+       # Methods tagged with `after` in this class definition
+       private fun after: Array[MMethodDef] do
+               var res = new Array[MMethodDef]
+               for mpropdef in mpropdefs do
+                       if mpropdef isa MMethodDef and mpropdef.is_after then
+                               res.add mpropdef
+                       end
+               end
+               var in_hierarchy = self.in_hierarchy
+               if in_hierarchy == null then return res
+               for mclassdef in in_hierarchy.direct_greaters do
+                       res.add_all mclassdef.after
+               end
+               return res
+       end
 
-redef class MClassDef
-       # Is the class a TestClass?
-       # i.e. is a subclass of `TestSuite`
-       private fun is_test: Bool do
+       # Methods tagged with `after_all` in this class definition
+       private fun after_all: Array[MMethodDef] do
+               var res = new Array[MMethodDef]
+               for mpropdef in mpropdefs do
+                       if mpropdef isa MMethodDef and mpropdef.is_after_all then
+                               res.add mpropdef
+                       end
+               end
                var in_hierarchy = self.in_hierarchy
-               if in_hierarchy == null then return false
-               for sup in in_hierarchy.greaters do
-                       if sup.name == "TestSuite" then return true
+               if in_hierarchy == null then return res
+               for mclassdef in in_hierarchy.direct_greaters do
+                       res.add_all mclassdef.after_all
                end
-               return false
+               return res
        end
 end
 
 redef class MModule
-       # "before_module" method for this module.
-       private fun before_test: nullable MMethodDef do
+       # Methods tagged with `before_all` at the module level (in `Sys`)
+       private fun before_all: Array[MMethodDef] do
                for mclassdef in mclassdefs do
-                       if not mclassdef.name == "Sys" then continue
-                       for mpropdef in mclassdef.mpropdefs do
-                               if mpropdef isa MMethodDef and mpropdef.is_before_module then return mpropdef
-                       end
+                       if mclassdef.name == "Sys" then return mclassdef.before_all
                end
-               return null
+               return new Array[MMethodDef]
        end
 
-       # "after_module" method for this module.
-       private fun after_test: nullable MMethodDef do
+       # Methods tagged with `after_all` at the module level (in `Sys`)
+       private fun after_all: Array[MMethodDef] do
                for mclassdef in mclassdefs do
-                       if not mclassdef.name == "Sys" then continue
-                       for mpropdef in mclassdef.mpropdefs do
-                               if mpropdef isa MMethodDef and mpropdef.is_after_module then return mpropdef
-                       end
+                       if mclassdef.name == "Sys" then return mclassdef.after_all
                end
-               return null
+               return new Array[MMethodDef]
        end
 end
 
@@ -438,7 +477,7 @@ redef class ModelBuilder
        # Run NitUnit test suite for `mmodule` (if it is one).
        fun test_unit(mmodule: MModule): nullable HTMLTag do
                # is the module a test_suite?
-               if get_mmodule_annotation("test_suite", mmodule) == null then return null
+               if not mmodule.is_test then return null
                toolcontext.info("nitunit: test-suite {mmodule}", 2)
 
                var tester = new NitUnitTester(self)
index 678f514..4d4eac9 100644 (file)
@@ -14,7 +14,7 @@
 
 module api_catalog
 
-import web_base
+import api_model
 import catalog
 
 redef class NitwebConfig
@@ -26,126 +26,400 @@ redef class NitwebConfig
        #
        # This method should be called at nitweb startup.
        fun build_catalog do
-               var catalog = new Catalog(modelbuilder)
-               for mpackage in model.mpackages do
-                       catalog.deps.add_node(mpackage)
-                       for mgroup in mpackage.mgroups do
-                               for mmodule in mgroup.mmodules do
-                                       for imported in mmodule.in_importation.direct_greaters do
-                                               var ip = imported.mpackage
-                                               if ip == null or ip == mpackage then continue
-                                               catalog.deps.add_edge(mpackage, ip)
-                                       end
-                               end
-                       end
-                       catalog.git_info(mpackage)
-                       catalog.package_page(mpackage)
-               end
-               self.catalog = catalog
+               self.catalog = new Catalog(modelbuilder)
+               self.catalog.build_catalog(model.mpackages)
        end
 end
 
 redef class APIRouter
        redef init do
                super
-               use("/catalog/highlighted", new APICatalogHighLighted(config))
-               use("/catalog/required", new APICatalogMostRequired(config))
-               use("/catalog/bytags", new APICatalogByTags(config))
-               use("/catalog/contributors", new APICatalogContributors(config))
+               use("/catalog/packages/", new APICatalogPackages(config))
                use("/catalog/stats", new APICatalogStats(config))
+
+               use("/catalog/tags", new APICatalogTags(config))
+               use("/catalog/tag/:tid", new APICatalogTag(config))
+
+               use("/catalog/person/:pid", new APICatalogPerson(config))
+               use("/catalog/person/:pid/maintaining", new APICatalogMaintaining(config))
+               use("/catalog/person/:pid/contributing", new APICatalogContributing(config))
        end
 end
 
 abstract class APICatalogHandler
        super APIHandler
 
-       # List the 10 best packages from `cpt`
-       fun list_best(cpt: Counter[MPackage]): JsonArray do
-               var res = new JsonArray
-               var best = cpt.sort
-               for i in [1..10] do
-                       if i > best.length then break
-                       res.add best[best.length-i]
-               end
-               return res
-       end
+       # Sorter used to sort packages
+       #
+       # Sorting is based on mpackage score.
+       var mpackages_sorter = new CatalogScoreSorter(config.catalog) is lazy
+end
 
-       # List packages by group.
-       fun list_by(map: MultiHashMap[Object, MPackage]): JsonObject do
-               var res = new JsonObject
-               var keys = map.keys.to_a
-               alpha_comparator.sort(keys)
-               for k in keys do
-                       var projs = map[k].to_a
-                       alpha_comparator.sort(projs)
-                       res[k.to_s.html_escape] = new JsonArray.from(projs)
-               end
-               return res
+# Get all the packages from the catalog using pagination
+#
+# `GET /packages?p=1&n=10`: get the list of catalog by page
+class APICatalogPackages
+       super APICatalogHandler
+
+       redef fun get(req, res) do
+               var page = req.int_arg("p")
+               var limit = req.int_arg("n")
+               var mpackages = config.catalog.mpackages.values.to_a
+               mpackages_sorter.sort(mpackages)
+               var response = new JsonArray.from(mpackages)
+               res.json paginate(response, response.length, page, limit)
        end
 end
 
+# Get the catalog statistics
+#
+# `GET /stats`: return the catalog statistics
 class APICatalogStats
        super APICatalogHandler
 
        redef fun get(req, res) do
-               var obj = new JsonObject
-               obj["packages"] = config.model.mpackages.length
-               obj["maintainers"] = config.catalog.maint2proj.length
-               obj["contributors"] = config.catalog.contrib2proj.length
-               obj["modules"] = config.catalog.mmodules.sum
-               obj["classes"] = config.catalog.mclasses.sum
-               obj["methods"] = config.catalog.mmethods.sum
-               obj["loc"] = config.catalog.loc.sum
-               res.json obj
+               res.json config.catalog.catalog_stats
        end
 end
 
-class APICatalogHighLighted
+# Get all the tags from the catalog
+#
+# `GET /tags`: the list of tags associated with their number of packages
+class APICatalogTags
        super APICatalogHandler
 
-       redef fun get(req, res) do res.json list_best(config.catalog.score)
+       # Sorter to sort tags alphabetically
+       var tags_sorter = new CatalogTagsSorter
+
+       redef fun get(req, res) do
+               var obj = new JsonObject
+
+               var tags = config.catalog.tag2proj.keys.to_a
+               tags_sorter.sort(tags)
+
+               for tag in tags do
+                       if not config.catalog.tag2proj.has_key(tag) then continue
+                       obj[tag] = config.catalog.tag2proj[tag].length
+               end
+               res.json obj
+       end
 end
 
-class APICatalogMostRequired
+# Get the packages related to a tag
+#
+# `GET /tag/:tid?p=1&n=10`: return a paginated list of packages
+class APICatalogTag
        super APICatalogHandler
 
        redef fun get(req, res) do
-               if config.catalog.deps.not_empty then
-                       var reqs = new Counter[MPackage]
-                       for p in config.model.mpackages do
-                               reqs[p] = config.catalog.deps[p].smallers.length - 1
-                       end
-                       res.json list_best(reqs)
+               var page = req.int_arg("p")
+               var limit = req.int_arg("n")
+               var id = req.param("tid")
+               if id == null then
+                       res.api_error(400, "Missing tag")
+                       return
+               end
+               id = id.from_percent_encoding
+               if not config.catalog.tag2proj.has_key(id) then
+                       res.api_error(404, "Tag not found")
                        return
                end
-               res.json new JsonArray
+               var obj = new JsonObject
+               obj["tag"] = id
+               var mpackages = config.catalog.tag2proj[id]
+               mpackages_sorter.sort(mpackages)
+               var response = new JsonArray.from(mpackages)
+               obj["packages"] = paginate(response, response.length, page, limit)
+               res.json obj
        end
 end
 
-class APICatalogByTags
+# Get a person existing in the catalog
+#
+# `GET /person/:pid`: get the person with `pid`
+class APICatalogPerson
        super APICatalogHandler
 
-       redef fun get(req, res) do res.json list_by(config.catalog.tag2proj)
+       # Get the person with `:pid` or throw a 404 error
+       fun get_person(req: HttpRequest, res: HttpResponse): nullable Person do
+               var id = req.param("pid")
+               if id == null then
+                       res.api_error(400, "Missing package full_name")
+                       return null
+               end
+               id = id.from_percent_encoding
+               if not config.catalog.name2person.has_key(id) then
+                       res.api_error(404, "Person not found")
+                       return null
+               end
+               return config.catalog.name2person[id]
+       end
+
+       redef fun get(req, res) do
+               var person = get_person(req, res)
+               if person == null then return
+               res.json person
+       end
 end
 
-class APICatalogContributors
-       super APICatalogHandler
+# Get the list of mpackages maintained by a person
+#
+# `GET /person/:pid/maintaining?p=1&n=10`: return a paginated list of packages
+class APICatalogMaintaining
+       super APICatalogPerson
 
        redef fun get(req, res) do
-               var obj = new JsonObject
-               obj["maintainers"] = new JsonArray.from(config.catalog.maint2proj.keys)
-               obj["contributors"] = new JsonArray.from(config.catalog.contrib2proj.keys)
-               res.json obj
+               var person = get_person(req, res)
+               if person == null then return
+
+               var page = req.int_arg("p")
+               var limit = req.int_arg("n")
+               var array = new Array[MPackage]
+               if config.catalog.maint2proj.has_key(person) then
+                       array = config.catalog.maint2proj[person].to_a
+               end
+               mpackages_sorter.sort(array)
+               var response = new JsonArray.from(array)
+               res.json paginate(response, response.length, page, limit)
+       end
+end
+
+# Get the list of mpackages contributed by a person
+#
+# `GET /person/:pid/contributing?p=1&n=10`: return a paginated list of packages
+class APICatalogContributing
+       super APICatalogPerson
+
+       redef fun get(req, res) do
+               var person = get_person(req, res)
+               if person == null then return
+
+               var page = req.int_arg("p")
+               var limit = req.int_arg("n")
+               var array = new Array[MPackage]
+               if config.catalog.contrib2proj.has_key(person) then
+                       array = config.catalog.contrib2proj[person].to_a
+               end
+               mpackages_sorter.sort(array)
+               var response = new JsonArray.from(array)
+               res.json paginate(response, response.length, page, limit)
+       end
+end
+
+redef class APIEntity
+       redef fun get(req, res) do
+               var mentity = mentity_from_uri(req, res)
+               if mentity == null then return
+
+               # Special case for packages (catalog view)
+               if mentity isa MPackage then
+                       res.raw_json mentity.to_full_catalog_json(plain=true, config.catalog)
+               else
+                       res.raw_json mentity.to_full_json
+               end
+       end
+end
+
+redef class APISearch
+       super APICatalogHandler
+
+       redef fun search(query, limit) do
+               var index = config.view.index
+
+               # lookup by name prefix
+               var matches = index.find_by_name_prefix(query).uniq.
+                       sort(lname_sorter, name_sorter, kind_sorter)
+               matches = matches.rerank.sort(vis_sorter, score_sorter)
+
+               # lookup by tags
+               var malus = matches.length
+               if config.catalog.tag2proj.has_key(query) then
+                       for mpackage in config.catalog.tag2proj[query] do
+                               matches.add new IndexMatch(mpackage, malus)
+                               malus += 1
+                       end
+                       matches = matches.uniq.rerank.sort(vis_sorter, score_sorter)
+               end
+
+               # lookup by full_name prefix
+               malus = matches.length
+               var full_matches = new IndexMatches
+               for match in index.find_by_full_name_prefix(query).
+                       sort(lfname_sorter, fname_sorter) do
+                       match.score += 1
+                       full_matches.add match
+               end
+               matches = matches.uniq
+
+               # lookup by similarity
+               malus = matches.length
+               var sim_matches = new IndexMatches
+               for match in index.find_by_similarity(query).sort(score_sorter, lname_sorter, name_sorter) do
+                       if match.score > query.length then break
+                       match.score += 1
+                       sim_matches.add match
+               end
+               matches.add_all sim_matches
+               matches = matches.uniq
+               return matches.rerank.sort(vis_sorter, score_sorter).mentities
+       end
+
+       private var score_sorter = new ScoreComparator
+       private var vis_sorter = new VisibilityComparator
+       private var name_sorter = new NameComparator
+       private var lname_sorter = new NameLengthComparator
+       private var fname_sorter = new FullNameComparator
+       private var lfname_sorter = new FullNameLengthComparator
+       private var kind_sorter = new MEntityComparator
+end
+
+redef class Catalog
+
+       # Build the catalog from `mpackages`
+       fun build_catalog(mpackages: Array[MPackage]) do
+               # Compute the poset
+               for p in mpackages do
+                       var g = p.root
+                       assert g != null
+                       modelbuilder.scan_group(g)
+
+                       deps.add_node(p)
+                       for gg in p.mgroups do for m in gg.mmodules do
+                               for im in m.in_importation.direct_greaters do
+                                       var ip = im.mpackage
+                                       if ip == null or ip == p then continue
+                                       deps.add_edge(p, ip)
+                               end
+                       end
+               end
+               # Build the catalog
+               for mpackage in mpackages do
+                       package_page(mpackage)
+                       git_info(mpackage)
+                       mpackage_stats(mpackage)
+               end
+       end
+end
+
+redef class MPackageMetadata
+       serialize
+
+       redef fun core_serialize_to(v) do
+               super
+               v.serialize_attribute("license", license)
+               v.serialize_attribute("maintainers", maintainers)
+               v.serialize_attribute("contributors", contributors)
+               v.serialize_attribute("tags", tags)
+               v.serialize_attribute("tryit", tryit)
+               v.serialize_attribute("apk", apk)
+               v.serialize_attribute("homepage", homepage)
+               v.serialize_attribute("browse", browse)
+               v.serialize_attribute("git", git)
+               v.serialize_attribute("issues", issues)
+               v.serialize_attribute("first_date", first_date)
+               v.serialize_attribute("last_date", last_date)
+       end
+end
+
+# Catalog statistics
+redef class CatalogStats
+       serialize
+
+       redef fun core_serialize_to(v) do
+               super
+               v.serialize_attribute("packages", packages)
+               v.serialize_attribute("maintainers", maintainers)
+               v.serialize_attribute("contributors", contributors)
+               v.serialize_attribute("tags", tags)
+               v.serialize_attribute("modules", modules)
+               v.serialize_attribute("classes", classes)
+               v.serialize_attribute("methods", methods)
+               v.serialize_attribute("loc", loc)
+       end
+end
+
+# MPackage statistics for the catalog
+redef class MPackageStats
+       serialize
+
+       redef fun core_serialize_to(v) do
+               super
+               v.serialize_attribute("mmodules", mmodules)
+               v.serialize_attribute("mclasses", mclasses)
+               v.serialize_attribute("mmethods", mmethods)
+               v.serialize_attribute("loc", loc)
+               v.serialize_attribute("errors", errors)
+               v.serialize_attribute("warnings", warnings)
+               v.serialize_attribute("warnings_per_kloc", warnings_per_kloc)
+               v.serialize_attribute("documentation_score", documentation_score)
+               v.serialize_attribute("commits", commits)
+               v.serialize_attribute("score", score)
        end
 end
 
 redef class Person
-       super Serializable
+       serialize
 
        redef fun core_serialize_to(v) do
+               super
                v.serialize_attribute("name", name)
                v.serialize_attribute("email", email)
-               v.serialize_attribute("page", page)
-               v.serialize_attribute("hash", (email or else "").md5.to_lower)
+               v.serialize_attribute("gravatar", gravatar)
+       end
+end
+
+redef class MPackage
+       # Serialize the full catalog version of `self` to JSON
+       #
+       # See: `FullCatalogSerializer`
+       fun to_full_catalog_json(catalog: Catalog, plain, pretty: nullable Bool): String do
+               var stream = new StringWriter
+               var serializer = new FullCatalogSerializer(stream, catalog)
+               serializer.plain_json = plain or else false
+               serializer.pretty_json = pretty or else false
+               serializer.serialize self
+               stream.close
+               return stream.to_s
+       end
+
+       redef fun core_serialize_to(v) do
+               super
+               v.serialize_attribute("metadata", metadata)
+               if v isa FullCatalogSerializer then
+                       v.serialize_attribute("stats", v.catalog.mpackages_stats[self])
+
+                       var parents = v.catalog.deps[self].direct_greaters.to_a
+                       v.serialize_attribute("dependencies", v.deps_to_json(parents))
+                       var children = v.catalog.deps[self].direct_smallers.to_a
+                       v.serialize_attribute("clients", v.deps_to_json(children))
+               end
+       end
+end
+
+# CatalogSerializer decorate the Package JSON with full catalog metadata
+#
+# See MEntity::to_full_catalog_json.
+class FullCatalogSerializer
+       super FullJsonSerializer
+
+       # Catalog used to decorate the MPackages
+       var catalog: Catalog
+
+       private fun deps_to_json(mpackages: Array[MPackage]): JsonArray do
+               var res = new JsonArray
+               for mpackage in mpackages do
+                       res.add dep_to_json(mpackage)
+               end
+               return res
+       end
+
+       private fun dep_to_json(mpackage: MPackage): JsonObject do
+               var obj = new JsonObject
+               obj["name"] = mpackage.name
+               var mdoc = mpackage.mdoc_or_fallback
+               if mdoc != null then
+                       obj["synopsis"] = mdoc.synopsis.write_to_string
+               end
+               return obj
        end
 end
index bbdc9db..a5ca012 100644 (file)
@@ -87,10 +87,7 @@ class NitwebDecorator
        end
 
        redef fun add_wikilink(v, token) do
-               var link = token.link
-               if link == null then return
-               var cmd = new DocCommand(link.write_to_string)
-               cmd.render(v, token, view)
+               v.render_wikilink(token, view)
        end
 end
 
@@ -105,20 +102,51 @@ class NitwebInlineDecorator
        var modelbuilder: ModelBuilder
 
        redef fun add_wikilink(v, token) do
-               var link = token.link
-               if link == null then return
-               var cmd = new DocCommand(link.write_to_string)
-               cmd.render(v, token, view)
+               v.render_wikilink(token, view)
        end
 end
 
 redef class MarkdownEmitter
+
+       # Parser used to process doc commands
+       var parser = new DocCommandParser
+
+       # Render a wikilink
+       fun render_wikilink(token: TokenWikiLink, model: ModelView) do
+               var link = token.link
+               if link == null then return
+               var name = token.name
+               if name != null then link = "{name} | {link}"
+               var cmd = parser.parse(link.write_to_string)
+               if cmd == null then
+                       var full_name = if token.link != null then token.link.as(not null).write_to_string.trim else null
+                       if full_name == null or full_name.is_empty then
+                               write_error("empty wikilink")
+                               return
+                       end
+                       var mentity = find_mentity(model, full_name)
+                       if mentity == null then return
+                       name = if token.name != null then token.name.as(not null).to_s else null
+                       write_mentity_link(mentity, name)
+                       return
+               else
+                       for message in parser.errors do
+                               if message.level == 1 then
+                                       write_error(message.message)
+                               else if message.level > 1 then
+                                       write_warning(message.message)
+                               end
+                       end
+               end
+               cmd.render(self, token, model)
+       end
+
        # Find the MEntity that matches `name`.
        #
        # Write an error if the entity is not found
        fun find_mentity(model: ModelView, name: nullable String): nullable MEntity do
                if name == null then
-                       write_error("No MEntity found")
+                       write_error("no MEntity found")
                        return null
                end
                # Lookup by full name
@@ -129,7 +157,7 @@ redef class MarkdownEmitter
                if mentities.is_empty then
                        var suggest = model.find(name, 3)
                        var msg = new Buffer
-                       msg.append "No MEntity found for name `{name}`"
+                       msg.append "no MEntity found for name `{name}`"
                        if suggest.not_empty then
                                msg.append " (suggestions: "
                                var i = 0
@@ -144,7 +172,7 @@ redef class MarkdownEmitter
                        return null
                else if mentities.length > 1 then
                        var msg = new Buffer
-                       msg.append "Conflicts for name `{name}`"
+                       msg.append "conflicts for name `{name}`"
                        msg.append " (conflicts: "
                        var i = 0
                        for s in mentities do
@@ -195,76 +223,44 @@ redef class MarkdownEmitter
        end
 end
 
-redef interface DocCommand
+redef class DocCommand
 
        # Emit the HTML related to the execution of this doc command
        fun render(v: MarkdownEmitter, token: TokenWikiLink, model: ModelView) do
-               v.write_error("Not yet implemented command `{token.link or else "null"}`")
-       end
-end
-
-redef class UnknownCommand
-       redef fun render(v, token, model) do
-               var link = token.link
-               if link == null then
-                       v.write_error("Empty command")
-                       return
-               end
-               var full_name = link.write_to_string
-               var mentity = v.find_mentity(model, full_name)
-               if mentity == null then return
-               v.write_mentity_link(mentity)
+               v.write_error("not yet implemented command `{token.link or else "null"}`")
        end
 end
 
-redef class ArticleCommand
+redef class CommentCommand
        redef fun render(v, token, model) do
-               if args.is_empty then
-                       v.write_error("Expected one arg: the MEntity name")
-                       return
-               end
-               var name = args.first
+               var name = arg
                var mentity = v.find_mentity(model, name)
                if mentity == null then return
                var mdoc = mentity.mdoc_or_fallback
                if mdoc == null then
-                       v.write_warning("No MDoc for mentity `{name}`")
+                       v.write_warning("no MDoc for mentity `{name}`")
                        return
                end
                v.add "<h3>"
-               v.write_mentity_link(mentity)
-               v.add " - "
-               v.emit_text mdoc.synopsis
-               v.add "</h3>"
-               v.add v.processor.process(mdoc.comment).write_to_string
-       end
-end
-
-redef class CommentCommand
-       redef fun render(v, token, model) do
-               if args.is_empty then
-                       v.write_error("Expected one arg: the MEntity name")
-                       return
+               if not opts.has_key("no-link") then
+                       v.write_mentity_link(mentity)
                end
-               var name = args.first
-               var mentity = v.find_mentity(model, name)
-               if mentity == null then return
-               var mdoc = mentity.mdoc_or_fallback
-               if mdoc == null then
-                       v.write_warning("No MDoc for mentity `{name}`")
-                       return
+               if not opts.has_key("no-link") and not opts.has_key("no-synopsis") then
+                       v.add " - "
+               end
+               if not opts.has_key("no-synopsis") then
+                       v.emit_text mdoc.html_synopsis.write_to_string
+               end
+               v.add "</h3>"
+               if not opts.has_key("no-comment") then
+                       v.add v.processor.process(mdoc.comment).write_to_string
                end
-               v.add v.processor.process(mdoc.comment).write_to_string
        end
 end
 
 redef class ListCommand
        redef fun render(v, token, model) do
-               if args.is_empty then
-                       v.write_error("Expected one arg: the MEntity name")
-                       return
-               end
-               var name = args.first
+               var name = arg
                var mentity = v.find_mentity(model, name)
                if mentity == null then return
                if mentity isa MPackage then
@@ -283,25 +279,21 @@ redef class ListCommand
                else if mentity isa MProperty then
                        v.write_mentity_list(mentity.mpropdefs)
                else
-                       v.write_error("No list found for name `{name}`")
+                       v.write_error("no list found for name `{name}`")
                end
        end
 end
 
 redef class CodeCommand
        redef fun render(v, token, model) do
-               if args.is_empty then
-                       v.write_error("Expected one arg: the MEntity name")
-                       return
-               end
-               var name = args.first
+               var name = arg
                var mentity = v.find_mentity(model, name)
                if mentity == null then return
                if mentity isa MClass then mentity = mentity.intro
                if mentity isa MProperty then mentity = mentity.intro
                var source = render_source(mentity, v.decorator.as(NitwebDecorator).modelbuilder)
                if source == null then
-                       v.write_error("No source for MEntity `{name}`")
+                       v.write_error("no source for MEntity `{name}`")
                        return
                end
                v.add "<pre>"
@@ -321,15 +313,15 @@ end
 
 redef class GraphCommand
        redef fun render(v, token, model) do
-               if args.is_empty then
-                       v.write_error("Expected one arg: the MEntity name")
-                       return
-               end
-               var name = args.first
+               var name = arg
                var mentity = v.find_mentity(model, name)
                if mentity == null then return
                var g = new InheritanceGraph(mentity, model)
-               v.add g.draw(3, 3).to_svg
+               var pdepth = if opts.has_key("pdepth") and opts["pdepth"].is_int then
+                       opts["pdepth"].to_i else 3
+               var cdepth = if opts.has_key("cdepth") and opts["cdepth"].is_int then
+                       opts["cdepth"].to_i else 3
+               v.add g.draw(pdepth, cdepth).to_svg
        end
 end
 
index 4f1a148..328eff9 100644 (file)
@@ -104,13 +104,19 @@ class APISearch
        super APIList
 
        redef fun get(req, res) do
-               var q = req.string_arg("q")
-               if q == null then
-                       res.json new JsonArray
+               var query = req.string_arg("q")
+               if query == null then
+                       res.api_error(400, "Missing search string")
                        return
                end
-               var n = req.int_arg("n")
-               res.json new JsonArray.from(config.view.find(q, n))
+               var page = req.int_arg("p")
+               var limit = req.int_arg("n")
+               var response = new JsonArray.from(search(query, limit))
+               res.json paginate(response, response.length, page, limit)
+       end
+
+       fun search(query: String, limit: nullable Int): Array[MEntity] do
+               return config.view.find(query)
        end
 end
 
index c863061..ac63f53 100644 (file)
@@ -47,7 +47,7 @@ class NitwebConfig
                view.include_fictive = true
                view.include_empty_doc = true
                view.include_attribute = true
-               view.include_test_suite = true
+               view.include_test = true
                return view
        end
 end
@@ -82,6 +82,46 @@ abstract class APIHandler
                end
                return mentity
        end
+
+       # Paginate a json array
+       #
+       # Returns only a subset of `results` depending on the current `page` and the
+       # number of elements to return set by `limit`.
+       #
+       # Transforms the json array into an object:
+       # ~~~json
+       # {
+       #       "page": 2,
+       #       "limit": 10,
+       #       "results: [ ... ],
+       #       "max": 5,
+       #       "total": 49
+       # }
+       # ~~~
+       fun paginate(results: JsonArray, count: Int, page, limit: nullable Int): JsonObject do
+               if page == null or page <= 0 then page = 1
+               if limit == null or limit <= 0 then limit = 20
+
+               var max = count / limit
+               if max == 0 then
+                       page = 1
+                       max = 1
+               else if page > max then
+                       page = max
+               end
+
+               var lstart = (page - 1) * limit
+               var lend = limit
+               if lstart + lend > count then lend = count - lstart
+
+               var res = new JsonObject
+               res["page"] = page
+               res["limit"] = limit
+               res["results"] = new JsonArray.from(results.subarray(lstart, lend))
+               res["max"] = max
+               res["total"] = count
+               return res
+       end
 end
 
 # A Rooter dedicated to APIHandlers.
diff --git a/tests/sav/example_vsm.res b/tests/sav/example_vsm.res
new file mode 100644 (file)
index 0000000..0e44311
--- /dev/null
@@ -0,0 +1,4 @@
+usage: example_vsm <files>
+  -h, --help             Show this help message
+  -w, --whitelist-exts   Allowed file extensions (default is [])
+  -b, --blacklist-exts   Allowed file extensions (default is [])
index a71e35b..dcddc6a 100644 (file)
@@ -16,9 +16,9 @@
 ==== Test-suite of module test_test_nitunit::test_test_nitunit | tests: 3
 [OK] test_test_nitunit$TestX$test_foo
 [KO] test_test_nitunit$TestX$test_foo1
-     test_test_nitunit.nit:36,2--40,4: Runtime Error in file nitunit.out/gen_test_test_nitunit.nit
+     test_test_nitunit.nit:35,2--39,4: Runtime Error in file nitunit.out/gen_test_test_nitunit.nit
      Output
-       Runtime error: Assert failed (test_test_nitunit.nit:39)
+       Runtime error: Assert failed (test_test_nitunit.nit:38)
 
 [OK] test_test_nitunit$TestX$test_foo2
 
@@ -32,5 +32,5 @@ Test suites: Classes: 1; Test Cases: 3; Failures: 1
 </system-out></testcase><testcase classname="nitunit.test_nitunit.X" name="foo" time="0.0"><failure message="Compilation error in nitunit.out&#47;test_nitunit-3.nit">nitunit.out&#47;test_nitunit-3.nit:5,8--27: Error: method or variable `undefined_identifier` unknown in `Sys`.
 </failure><system-out>assert undefined_identifier
 </system-out></testcase><testcase classname="nitunit.test_nitunit.X" name="foo1" time="0.0"><failure message="Syntax Error: unexpected operator &#39;!&#39;."></failure><system-out>assert !@#$%^&amp;*()
-</system-out></testcase></testsuite><testsuite package="test_test_nitunit::test_test_nitunit"></testsuite><testsuite package="test_test_nitunit"><testcase classname="nitunit.test_test_nitunit.TestX" name="test_foo" time="0.0"><system-err></system-err></testcase><testcase classname="nitunit.test_test_nitunit.TestX" name="test_foo1" time="0.0"><error message="Runtime Error in file nitunit.out&#47;gen_test_test_nitunit.nit">Runtime error: Assert failed (test_test_nitunit.nit:39)
+</system-out></testcase></testsuite><testsuite package="test_test_nitunit::test_test_nitunit"></testsuite><testsuite package="test_test_nitunit"><testcase classname="nitunit.test_test_nitunit.TestX" name="test_foo" time="0.0"><system-err></system-err></testcase><testcase classname="nitunit.test_test_nitunit.TestX" name="test_foo1" time="0.0"><error message="Runtime Error in file nitunit.out&#47;gen_test_test_nitunit.nit">Runtime error: Assert failed (test_test_nitunit.nit:38)
 </error></testcase><testcase classname="nitunit.test_test_nitunit.TestX" name="test_foo2" time="0.0"><system-err></system-err></testcase></testsuite></testsuites>
\ No newline at end of file
index 0a8b785..42ee33e 100644 (file)
@@ -1,13 +1,13 @@
 ==== Test-suite of module test_nitunit6::test_nitunit6 | tests: 3
 [KO] test_nitunit6::test_nitunit6$core::Sys$before_module
-     test_nitunit6.nit:27,1--29,3: Runtime Error in file nitunit.out/gen_test_nitunit6.nit
+     test_nitunit6.nit:25,1--27,3: Runtime Error in file nitunit.out/gen_test_nitunit6.nit
      Output
-       Runtime error: Assert failed (test_nitunit6.nit:28)
+       Runtime error: Assert failed (test_nitunit6.nit:26)
 
 [KO] test_nitunit6$TestNitunit6$test_foo
-     test_nitunit6.nit:22,2--24,4: Nitunit Error: before_module test failed
+     test_nitunit6.nit:20,2--22,4: Nitunit Error: before_module test failed
 [KO] test_nitunit6::test_nitunit6$core::Sys$after_module
-     test_nitunit6.nit:31,1--33,3: Nitunit Error: before_module test failed
+     test_nitunit6.nit:29,1--31,3: Nitunit Error: before_module test failed
 
 Docunits: Entities: 5; Documented ones: 0; With nitunits: 0
 Test suites: Classes: 1; Test Cases: 3; Failures: 3
index aa79730..9015b4a 100644 (file)
@@ -2,9 +2,9 @@
 [OK] test_nitunit7::test_nitunit7$core::Sys$before_module
 [OK] test_nitunit7$TestNitunit7$test_foo
 [KO] test_nitunit7::test_nitunit7$core::Sys$after_module
-     test_nitunit7.nit:31,1--33,3: Runtime Error in file nitunit.out/gen_test_nitunit7.nit
+     test_nitunit7.nit:29,1--31,3: Runtime Error in file nitunit.out/gen_test_nitunit7.nit
      Output
-       Runtime error: Assert failed (test_nitunit7.nit:32)
+       Runtime error: Assert failed (test_nitunit7.nit:30)
 
 
 Docunits: Entities: 5; Documented ones: 0; With nitunits: 0
index bc00752..06ef822 100644 (file)
@@ -1,19 +1,18 @@
-module test_test_nitunit is test_suite
+module test_test_nitunit is test
 
-import test_suite
 import test_nitunit
 
 class TestX
-       super TestSuite
+       test
 
-       fun test_foo do
+       fun test_foo is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
                subject.foo
        end
 
-       fun test_foo1 do
+       fun test_foo1 is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
@@ -22,7 +21,7 @@ class TestX
                subject.foo1(a, b)
        end
 
-       fun test_foo3 do
+       fun test_foo3 is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
@@ -33,9 +32,9 @@ class TestX
 end
 
 class TestY
-       super TestSuite
+       test
 
-       fun test_bra do
+       fun test_bra is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -45,7 +44,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_bra_assign do
+       fun test_bra_assign is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -54,7 +53,7 @@ class TestY
                subject[e] = i
        end
 
-       fun test_plus do
+       fun test_plus is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -64,7 +63,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_minus do
+       fun test_minus is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -74,7 +73,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_star do
+       fun test_star is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -84,7 +83,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_slash do
+       fun test_slash is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -94,7 +93,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_percent do
+       fun test_percent is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -104,7 +103,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_unary_minus do
+       fun test_unary_minus is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -113,7 +112,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_equals do
+       fun test_equals is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -123,7 +122,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_not_equals do
+       fun test_not_equals is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -133,7 +132,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_lt do
+       fun test_lt is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -143,7 +142,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_le do
+       fun test_le is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -153,7 +152,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_compare do
+       fun test_compare is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -163,7 +162,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_ge do
+       fun test_ge is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -173,7 +172,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_gt do
+       fun test_gt is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -185,9 +184,9 @@ class TestY
 end
 
 class TestZ
-       super TestSuite
+       test
 
-       fun test_bra do
+       fun test_bra is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
@@ -198,7 +197,7 @@ class TestZ
                assert exp == res
        end
 
-       fun test_bra_assign do
+       fun test_bra_assign is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
@@ -208,7 +207,7 @@ class TestZ
                subject[i, j] = k
        end
 
-       fun test_foo= do
+       fun test_foo= is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
@@ -217,7 +216,7 @@ class TestZ
                subject.foo(i) = j
        end
 
-       fun test_bar= do
+       fun test_bar= is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
index e93c6ca..586af7d 100644 (file)
@@ -1,19 +1,18 @@
-module test_test_nitunit is test_suite
+module test_test_nitunit is test
 
-import test_suite
 intrude import test_nitunit
 
 class TestX
-       super TestSuite
+       test
 
-       fun test_foo do
+       fun test_foo is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
                subject.foo
        end
 
-       fun test_foo1 do
+       fun test_foo1 is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
@@ -22,7 +21,7 @@ class TestX
                subject.foo1(a, b)
        end
 
-       fun test_foo2 do
+       fun test_foo2 is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
@@ -31,7 +30,7 @@ class TestX
                assert exp == res
        end
 
-       fun test_foo3 do
+       fun test_foo3 is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
@@ -40,7 +39,7 @@ class TestX
                assert exp == res
        end
 
-       fun test_foo3= do
+       fun test_foo3= is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: X
@@ -50,9 +49,9 @@ class TestX
 end
 
 class TestY
-       super TestSuite
+       test
 
-       fun test_bra do
+       fun test_bra is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -62,7 +61,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_bra_assign do
+       fun test_bra_assign is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -71,7 +70,7 @@ class TestY
                subject[e] = i
        end
 
-       fun test_plus do
+       fun test_plus is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -81,7 +80,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_minus do
+       fun test_minus is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -91,7 +90,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_star do
+       fun test_star is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -101,7 +100,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_slash do
+       fun test_slash is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -111,7 +110,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_percent do
+       fun test_percent is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -121,7 +120,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_unary_minus do
+       fun test_unary_minus is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -130,7 +129,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_equals do
+       fun test_equals is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -140,7 +139,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_not_equals do
+       fun test_not_equals is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -150,7 +149,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_lt do
+       fun test_lt is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -160,7 +159,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_le do
+       fun test_le is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -170,7 +169,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_compare do
+       fun test_compare is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -180,7 +179,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_ge do
+       fun test_ge is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -190,7 +189,7 @@ class TestY
                assert exp == res
        end
 
-       fun test_gt do
+       fun test_gt is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Y[X]
@@ -202,9 +201,9 @@ class TestY
 end
 
 class TestZ
-       super TestSuite
+       test
 
-       fun test_bra do
+       fun test_bra is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
@@ -215,7 +214,7 @@ class TestZ
                assert exp == res
        end
 
-       fun test_bra_assign do
+       fun test_bra_assign is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
@@ -225,7 +224,7 @@ class TestZ
                subject[i, j] = k
        end
 
-       fun test_foo= do
+       fun test_foo= is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
@@ -234,7 +233,7 @@ class TestZ
                subject.foo(i) = j
        end
 
-       fun test_bar= do
+       fun test_bar= is test do
                assert not_implemented: false # TODO remove once implemented
 
                var subject: Z
index bb114f6..18de7be 100644 (file)
@@ -1,41 +1,41 @@
-test_nitunit4/test_bad_comp.nit:27,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
-test_nitunit4/test_bad_comp2.nit:19,7--22: Error: a class named `test_nitunit4::TestSuiteBadComp` is already defined in module `test_bad_comp` at test_nitunit4/test_bad_comp.nit:19,1--29,3.
+test_nitunit4/test_bad_comp.nit:25,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
+test_nitunit4/test_bad_comp2.nit:17,7--22: Error: a class named `test_nitunit4::TestSuiteBadComp` is already defined in module `test_bad_comp` at test_nitunit4/test_bad_comp.nit:17,1--27,3.
 ==== Test-suite of module test_nitunit4::test_bad_comp | tests: 2
 [KO] test_nitunit4$TestSuiteBadComp$test_good
-     test_nitunit4/test_bad_comp.nit:22,2--24,4: Compilation Error
+     test_nitunit4/test_bad_comp.nit:20,2--22,4: Compilation Error
      Output
-       test_nitunit4/test_bad_comp.nit:27,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
+       test_nitunit4/test_bad_comp.nit:25,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
 
 [KO] test_nitunit4$TestSuiteBadComp$test_bad
-     test_nitunit4/test_bad_comp.nit:26,2--28,4: Compilation Error
+     test_nitunit4/test_bad_comp.nit:24,2--26,4: Compilation Error
      Output
-       test_nitunit4/test_bad_comp.nit:27,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
+       test_nitunit4/test_bad_comp.nit:25,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
 
 
 ==== Test-suite of module test_nitunit4::test_bad_comp2 | tests: 2
 [KO] test_nitunit4$TestSuiteBadComp$test_good
-     test_nitunit4/test_bad_comp2.nit:22,2--24,4: Compilation Error
+     test_nitunit4/test_bad_comp2.nit:20,2--22,4: Compilation Error
      Output
-       nitunit.out/gen_test_bad_comp2.nit:14,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
+       nitunit.out/gen_test_bad_comp2.nit:11,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
 
 [KO] test_nitunit4$TestSuiteBadComp$test_bad
-     test_nitunit4/test_bad_comp2.nit:26,2--28,4: Compilation Error
+     test_nitunit4/test_bad_comp2.nit:24,2--26,4: Compilation Error
      Output
-       nitunit.out/gen_test_bad_comp2.nit:14,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
+       nitunit.out/gen_test_bad_comp2.nit:11,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
 
 
 ==== Test-suite of module test_nitunit4::test_nitunit4 | tests: 4
 [KO] test_nitunit4$TestTestSuite$test_foo
-     test_nitunit4/test_nitunit4.nit:22,2--26,4: Runtime Error in file nitunit.out/gen_test_nitunit4.nit
+     test_nitunit4/test_nitunit4.nit:23,2--27,4: Runtime Error in file nitunit.out/gen_test_nitunit4.nit
      Output
        Before Test
        Tested method
        After Test
-       Runtime error: Assert failed (test_nitunit4/test_nitunit4_base.nit:31)
+       Runtime error: Assert failed (test_nitunit4/test_nitunit4_base.nit:28)
 
 [OK] test_nitunit4$TestTestSuite$test_bar
 [KO] test_nitunit4$TestTestSuite$test_baz
-     test_nitunit4/test_nitunit4.nit:32,2--34,4: Difference with expected output: diff -u test_nitunit4/test_baz.res nitunit.out/gen_test_nitunit4_test_baz.out1
+     test_nitunit4/test_nitunit4.nit:33,2--35,4: Difference with expected output: diff -u test_nitunit4/test_baz.res nitunit.out/gen_test_nitunit4_test_baz.out1
      Output
        Diff
        --- expected:test_nitunit4/test_baz.res
@@ -47,28 +47,25 @@ test_nitunit4/test_bad_comp2.nit:19,7--22: Error: a class named `test_nitunit4::
        +After Test
 
 [KO] test_nitunit4$TestTestSuite$test_sav_conflict
-     test_nitunit4/test_nitunit4.nit:36,2--38,4: Conflicting expected output: test_nitunit4/test_nitunit4.sav/test_sav_conflict.res, test_nitunit4/sav/test_sav_conflict.res and test_nitunit4/test_sav_conflict.res all exist
+     test_nitunit4/test_nitunit4.nit:37,2--39,4: Conflicting expected output: test_nitunit4/test_nitunit4.sav/test_sav_conflict.res, test_nitunit4/sav/test_sav_conflict.res and test_nitunit4/test_sav_conflict.res all exist
      Output
        Before Test
        Tested method
        After Test
 
 
-==== Test-suite of module test_nitunit4::test_nitunit4_base | tests: 0
-==== Test-suite of module test_nitunit4::test_nitunit4_base | tests: 0
-
 Docunits: Entities: 21; Documented ones: 0; With nitunits: 0
-Test suites: Classes: 4; Test Cases: 8; Failures: 7
+Test suites: Classes: 3; Test Cases: 8; Failures: 7
 [FAILURE] 7/8 tests failed.
 `nitunit.out` is not removed for investigation.
-<testsuites><testsuite package="test_nitunit4&gt;"></testsuite><testsuite package="test_nitunit4::nitunit4"></testsuite><testsuite package="test_nitunit4::test_bad_comp"></testsuite><testsuite package="test_bad_comp"><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_good" time="0.0"><failure message="Compilation Error">test_nitunit4&#47;test_bad_comp.nit:27,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
-</failure></testcase><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_bad" time="0.0"><failure message="Compilation Error">test_nitunit4&#47;test_bad_comp.nit:27,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
-</failure></testcase></testsuite><testsuite package="test_nitunit4::test_bad_comp2"></testsuite><testsuite package="test_bad_comp2"><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_good" time="0.0"><failure message="Compilation Error">nitunit.out&#47;gen_test_bad_comp2.nit:14,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
-</failure></testcase><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_bad" time="0.0"><failure message="Compilation Error">nitunit.out&#47;gen_test_bad_comp2.nit:14,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
+<testsuites><testsuite package="test_nitunit4&gt;"></testsuite><testsuite package="test_nitunit4::nitunit4"></testsuite><testsuite package="test_nitunit4::test_bad_comp"></testsuite><testsuite package="test_bad_comp"><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_good" time="0.0"><failure message="Compilation Error">test_nitunit4&#47;test_bad_comp.nit:25,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
+</failure></testcase><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_bad" time="0.0"><failure message="Compilation Error">test_nitunit4&#47;test_bad_comp.nit:25,10--19: Error: method or variable `bad_method` unknown in `TestSuiteBadComp`.
+</failure></testcase></testsuite><testsuite package="test_nitunit4::test_bad_comp2"></testsuite><testsuite package="test_bad_comp2"><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_good" time="0.0"><failure message="Compilation Error">nitunit.out&#47;gen_test_bad_comp2.nit:11,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
+</failure></testcase><testcase classname="nitunit.test_nitunit4.TestSuiteBadComp" name="test_bad" time="0.0"><failure message="Compilation Error">nitunit.out&#47;gen_test_bad_comp2.nit:11,10--17: Error: expected 1 argument(s) for `test_bad(param: Bool)`; got 0. See introduction at `test_nitunit4::TestSuiteBadComp::test_bad`.
 </failure></testcase></testsuite><testsuite package="test_nitunit4::test_nitunit4"></testsuite><testsuite package="test_nitunit4"><testcase classname="nitunit.test_nitunit4.TestTestSuite" name="test_foo" time="0.0"><error message="Runtime Error in file nitunit.out&#47;gen_test_nitunit4.nit">Before Test
 Tested method
 After Test
-Runtime error: Assert failed (test_nitunit4&#47;test_nitunit4_base.nit:31)
+Runtime error: Assert failed (test_nitunit4&#47;test_nitunit4_base.nit:28)
 </error></testcase><testcase classname="nitunit.test_nitunit4.TestTestSuite" name="test_bar" time="0.0"><system-err>Before Test
 Tested method
 After Test
@@ -83,4 +80,4 @@ After Test
 </error></testcase><testcase classname="nitunit.test_nitunit4.TestTestSuite" name="test_sav_conflict" time="0.0"><error message="Conflicting expected output: test_nitunit4&#47;test_nitunit4.sav&#47;test_sav_conflict.res, test_nitunit4&#47;sav&#47;test_sav_conflict.res and test_nitunit4&#47;test_sav_conflict.res all exist">Before Test
 Tested method
 After Test
-</error></testcase></testsuite><testsuite package="test_nitunit4::test_nitunit4_base"></testsuite><testsuite package="test_nitunit4_base"></testsuite></testsuites>
\ No newline at end of file
+</error></testcase></testsuite><testsuite package="test_nitunit4::test_nitunit4_base"></testsuite></testsuites>
\ No newline at end of file
index 26fb54f..52e9594 100644 (file)
@@ -1,10 +1,8 @@
 syntax_annotations3.nit:16,2--20: Warning: unknown annotation `invariant`.
 syntax_annotations3.nit:19,3--12: Warning: unknown annotation `pre`.
 syntax_annotations3.nit:20,3--22: Warning: unknown annotation `post`.
-syntax_annotations3.nit:21,3--19: Warning: unknown annotation `test`.
 syntax_annotations3.nit:28,3--7: Warning: unknown annotation `inter`.
 syntax_annotations3.nit:33,16--18: Warning: unknown annotation `u32`.
-syntax_annotations3.nit:34,19--36: Warning: unknown annotation `after`.
 syntax_annotations3.nit:34,12--36: Warning: unknown annotation `daemon`.
 syntax_annotations3.nit:34,3--37: Warning: unknown annotation `ondebug`.
 syntax_annotations3.nit:35,3--7: Warning: unknown annotation `final`.
index f8d9b87..04354d0 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_bad_comp is test_suite
-
-import test_suite
+module test_bad_comp is test
 
 class TestSuiteBadComp
-       super TestSuite
+       test
 
-       fun test_good do
+       fun test_good is test do
                assert true
        end
 
-       fun test_bad do
+       fun test_bad is test do
                assert bad_method
        end
 end
index aac1a09..c274df6 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_bad_comp2 is test_suite
-
-import test_suite
+module test_bad_comp2 is test
 
 class TestSuiteBadComp
-       super TestSuite
+       test
 
-       fun test_good do
+       fun test_good is test do
                assert true
        end
 
-       fun test_bad(param: Bool) do
+       fun test_bad(param: Bool) is test do
                assert param
        end
 end
index 8864263..dfb5e32 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_nitunit4 is test_suite
+module test_nitunit4 is test
 
 import test_nitunit4_base
 
 class TestTestSuite
        super SuperTestSuite
+       test
 
-       fun test_foo do
+       fun test_foo is test do
                print "Tested method"
                assert before
                before = false
        end
 
-       fun test_bar do
+       fun test_bar is test do
                print "Tested method"
        end
 
-       fun test_baz do
+       fun test_baz is test do
                print "Tested method"
        end
 
-       fun test_sav_conflict do
+       fun test_sav_conflict is test do
                print "Tested method"
        end
 end
index af21e73..3fe9e16 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_nitunit4_base is test_suite
-
-import test_suite
+module test_nitunit4_base
 
 class SuperTestSuite
-       super TestSuite
 
        var before = false
 
-       redef fun before_test do
+       fun before_test is before do
                print "Before Test"
                before = true
        end
 
-       redef fun after_test do
+       fun after_test is after do
                print "After Test"
                assert before
        end
index 602648b..fc327aa 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_nitunit5 is test_suite
-
-import test_suite
+module test_nitunit5 is test
 
 class TestNitunit5
-       super TestSuite
+       test
 
-       fun test_path_is_set do
+       fun test_path_is_set is test do
                assert "NIT_TESTING_PATH".environ != ""
        end
 
-       fun test_path_is_suite_path do
+       fun test_path_is_suite_path is test do
                assert "NIT_TESTING_PATH".environ.basename == "test_nitunit5.nit"
        end
 end
index 97eca0a..f5f4e67 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_nitunit6 is test_suite
-
-import test_suite
+module test_nitunit6 is test
 
 class TestNitunit6
-       super TestSuite
+       test
 
-       fun test_foo do
+       fun test_foo is test do
                assert true
        end
 end
 
-redef fun before_module do
+fun before_module is before_all do
        assert false
 end
 
-redef fun after_module do
+fun after_module is after_all do
        assert false
 end
index 63f47ea..3c79772 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-module test_nitunit7 is test_suite
-
-import test_suite
+module test_nitunit7 is test
 
 class TestNitunit7
-       super TestSuite
+       test
 
-       fun test_foo do
+       fun test_foo is test do
                assert true
        end
 end
 
-redef fun before_module do
+fun before_module is before_all do
        assert true
 end
 
-redef fun after_module do
+fun after_module is after_all do
        assert false
 end
index 71ce971..b04e567 100644 (file)
 # limitations under the License.
 
 # NitUnit file for test_nitunit module.
-module test_test_nitunit is test_suite
+module test_test_nitunit is test
 
-import test_suite
 intrude import test_nitunit
 
 class TestX
-       super TestSuite
+       test
 
        var subject: X is noinit
 
-       redef fun before_test do
+       fun before_test is before do
                subject = new X
        end
 
-       fun test_foo do
+       fun test_foo is test do
                subject.foo
        end
 
        # will fail
-       fun test_foo1 do
+       fun test_foo1 is test do
                subject.foo1(10, 20)
                assert false
        end
 
-       fun test_foo2 do
+       fun test_foo2 is test do
                assert subject.foo2
        end
 end