|
| 1 | +# coding: utf-8 |
| 2 | +from unittest import TestCase |
| 3 | +import os |
| 4 | +import watson_developer_cloud |
| 5 | +import pytest |
| 6 | +import json |
| 7 | +import time |
| 8 | + |
| 9 | +FIVE_SECONDS = 5 |
| 10 | + |
| 11 | +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') |
| 12 | +class TestNaturalLanguageClassifierV1(TestCase): |
| 13 | + def setUp(self): |
| 14 | + self.natural_language_classifier = watson_developer_cloud.NaturalLanguageClassifierV1( |
| 15 | + username='YOUR SERVICE USERNAME', |
| 16 | + password='YOUR SERVICE PASSWORD') |
| 17 | + self.natural_language_classifier.set_default_headers({ |
| 18 | + 'X-Watson-Learning-Opt-Out': '1', |
| 19 | + 'X-Watson-Test': '1' |
| 20 | + }) |
| 21 | + |
| 22 | + # Create a classifier |
| 23 | + with open(os.path.join(os.path.dirname(__file__), '../../resources/weather_data_train.csv'), 'rb') as training_data: |
| 24 | + metadata = json.dumps({'name': 'my-classifier', 'language': 'en'}) |
| 25 | + classifier = self.natural_language_classifier.create_classifier( |
| 26 | + metadata=metadata, |
| 27 | + training_data=training_data |
| 28 | + ) |
| 29 | + self.classifier_id = classifier['classifier_id'] |
| 30 | + |
| 31 | + def tearDown(self): |
| 32 | + self.natural_language_classifier.delete_classifier(self.classifier_id) |
| 33 | + |
| 34 | + def test_list_classifier(self): |
| 35 | + list_classifiers = self.natural_language_classifier.list_classifiers() |
| 36 | + assert list_classifiers is not None |
| 37 | + |
| 38 | + @pytest.mark.skip(reason="The classifier takes more than a minute") |
| 39 | + def test_classify_text(self): |
| 40 | + iterations = 0 |
| 41 | + while iterations < 15: |
| 42 | + status = self.natural_language_classifier.get_classifier(self.classifier_id) |
| 43 | + iterations += 1 |
| 44 | + if status['status'] != 'Available': |
| 45 | + time.sleep(FIVE_SECONDS) |
| 46 | + |
| 47 | + if status['status'] != 'Available': |
| 48 | + assert False, 'Classifier is not available' |
| 49 | + |
| 50 | + classes = self.natural_language_classifier.classify(self.classifier_id, 'How hot will it be tomorrow?') |
| 51 | + assert classes is not None |
| 52 | + |
| 53 | + collection = ['{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}'] |
| 54 | + classes = self.natural_language_classifier.classify_collection( |
| 55 | + self.classifier_id, collection) |
| 56 | + assert classes is not None |
0 commit comments