Codebase list python-faraday / master tests / test_api_hosts.py
master

Tree @master (Download .tar.gz)

test_api_hosts.py @masterraw · history · blame

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
'''
Faraday Penetration Test IDE
Copyright (C) 2013  Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information

'''
import operator
from io import BytesIO
from posixpath import join

import pytz

from urllib.parse import urlencode, urljoin
from random import choice
from sqlalchemy.orm.util import was_deleted
from hypothesis import given, strategies as st

import pytest

from tests import factories
from tests.test_api_workspaced_base import (
    API_PREFIX,
    ReadWriteAPITests,
    PaginationTestsMixin,
    BulkUpdateTestsMixin,
    BulkDeleteTestsMixin
)
from faraday.server.models import db, Host, Hostname
from faraday.server.api.modules.hosts import HostsView
from tests.factories import HostFactory, EmptyCommandFactory, WorkspaceFactory, HostnameFactory

HOSTS_COUNT = 5
SERVICE_COUNT = [10, 5]  # 10 services to the first host, 5 to the second


@pytest.mark.usefixtures('database', 'logged_user')
class TestHostAPI:

    @pytest.fixture(autouse=True)
    def load_workspace_with_hosts(self, database, session, workspace, host_factory):
        self.hosts = host_factory.create_batch(HOSTS_COUNT,
                                               workspace=workspace)
        self.first_host = self.hosts[0]
        session.commit()
        assert workspace.id is not None
        assert workspace.hosts[0].id is not None
        self.workspace = workspace
        return workspace

    @pytest.fixture
    def host_services(self, session, service_factory):
        """
        Add some services to the first len(SERVICE_COUNT) hosts.

        Return a dictionary mapping hosts to a list of services
        """
        ret = {}
        for (count, host) in zip(SERVICE_COUNT, self.hosts):
            ret[host] = service_factory.create_batch(
                count, host=host, workspace=host.workspace, status='open')
        session.commit()
        return ret

    def url(self, host=None, workspace=None):
        workspace = workspace or self.workspace
        url = join(API_PREFIX + workspace.name, 'hosts')
        if host is not None:
            url = join(url, str(host.id))
        return url

    def services_url(self, host, workspace=None):
        return join(self.url(host, workspace), 'services')

    def compare_results(self, hosts, response):
        """
        Compare is the hosts in response are the same that in hosts.
        It only compares the IDs of each one, not other fields"""
        hosts_in_list = {host.id for host in hosts}
        hosts_in_response = {host['id'] for host in response.json['rows']}
        assert hosts_in_list == hosts_in_response

    def test_list_retrieves_all_items_from_workspace(self, test_client,
                                                     second_workspace,
                                                     session,
                                                     host_factory):
        other_host = host_factory.create(workspace=second_workspace)
        session.commit()
        res = test_client.get(self.url())
        assert res.status_code == 200
        assert len(res.json['rows']) == HOSTS_COUNT

    def test_retrieve_one_host(self, test_client, database):
        host = self.workspace.hosts[0]
        assert host.id is not None
        res = test_client.get(self.url(host))
        assert res.status_code == 200
        assert res.json['name'] == host.ip

    def test_retrieve_fails_with_host_of_another_workspace(self,
                                                           test_client,
                                                           session,
                                                           workspace_factory):
        new = workspace_factory.create()
        session.commit()
        res = test_client.get(self.url(self.workspace.hosts[0], new))
        assert res.status_code == 404

    def test_create_a_host_succeeds(self, test_client):
        res = test_client.post(self.url(), data={
            "ip": "127.0.0.1",
            "description": "aaaaa",
            # os is not required
        })
        assert res.status_code == 201
        assert Host.query.count() == HOSTS_COUNT + 1
        host_id = res.json['id']
        host = Host.query.get(host_id)
        assert host.ip == "127.0.0.1"
        assert host.description == "aaaaa"
        assert host.os == ''
        assert host.workspace == self.workspace

    def test_create_a_host_with_rev_succeeds(self, test_client):
        res = test_client.post(self.url(), data={
            "ip": "127.0.0.1",
            "description": "aaaaa",
            "_rev": "saraza"
            # os is not required
        })
        assert res.status_code == 201
        assert Host.query.count() == HOSTS_COUNT + 1
        host_id = res.json['id']
        host = Host.query.get(host_id)
        assert host.ip == "127.0.0.1"
        assert host.description == "aaaaa"
        assert host.os == ''
        assert host.workspace == self.workspace

    def test_create_a_host_fails_with_missing_desc(self, test_client):
        res = test_client.post(self.url(), data={
            "ip": "127.0.0.1",
        })
        assert res.status_code == 400

    def test_create_a_host_fails_with_existing_ip(self, session,
                                                  test_client, host):
        session.add(host)
        session.commit()
        assert Host.query.count() == HOSTS_COUNT + 1

        res = test_client.post(self.url(), data={
            "ip": host.ip,
            "description": "aaaaa",
        })
        assert res.status_code == 409
        assert Host.query.count() == HOSTS_COUNT + 1

    def test_create_a_host_with_ip_of_other_workspace(self, test_client,
                                                      session,
                                                      second_workspace, host):
        session.add(host)
        session.commit()

        res = test_client.post(self.url(workspace=second_workspace), data={
            "ip": host.ip,
            "description": "aaaaa",
        })
        assert res.status_code == 201
        # It should create two hosts, one for each workspace
        assert Host.query.count() == HOSTS_COUNT + 2

    def test_update_a_host(self, test_client):
        host = self.workspace.hosts[0]
        res = test_client.put(self.url(host), data={
            "ip": host.ip,
            "description": "bbbbb",
        })
        assert res.status_code == 200
        assert res.json['description'] == 'bbbbb'
        assert Host.query.get(res.json['id']).description == 'bbbbb'
        assert Host.query.count() == HOSTS_COUNT

    def test_update_a_host_fails_with_existing_ip(self, test_client, session):
        host = self.workspace.hosts[0]
        original_ip = host.ip
        original_desc = host.description
        res = test_client.put(self.url(host), data={
            "ip": self.workspace.hosts[1].ip,  # Existing IP
            "description": "bbbbb",
        })
        assert res.status_code == 409
        session.refresh(host)
        assert host.ip == original_ip
        assert host.description == original_desc  # It shouldn't do a partial update

    def test_update_a_host_fails_with_missing_fields(self, test_client):
        """To do this the user should use a PATCH request"""
        host = self.workspace.hosts[0]
        res = test_client.put(self.url(host), data={
            "ip": "1.2.3.4",  # Existing IP
        })
        assert res.status_code == 400

    def test_delete_a_host(self, test_client):
        host = self.workspace.hosts[0]
        res = test_client.delete(self.url(host))
        assert res.status_code == 204  # No content
        assert was_deleted(host)

    def test_delete_host_from_other_workspace_fails(self, test_client,
                                                    second_workspace):
        host = self.workspace.hosts[0]
        res = test_client.delete(self.url(host, workspace=second_workspace))
        assert res.status_code == 404  # No content
        assert not was_deleted(host)

    def test_get_host_services(self, test_client, session,
                               service_factory):
        # Create the services that must be shown
        real = service_factory.create_batch(
            SERVICE_COUNT[0],
            host=self.first_host,
            workspace=self.first_host.workspace)

        # Create a service of other host, must not be shown
        other_host = service_factory.create(
            host=self.hosts[1],
            workspace=self.hosts[1].workspace)

        session.commit()
        ids_expected = {host.id for host in real}

        res = test_client.get(self.services_url(self.first_host))
        assert res.status_code == 200
        ids_returned = {host['id'] for host in res.json}
        assert other_host.id not in ids_returned
        assert ids_expected == ids_returned

    def test_retrieve_shows_service_count(self, test_client, session,
                                          host_services, service_factory):
        for (host, services) in host_services.items():
            # Adding closed and filtered services shouldn't impact on the
            # service count since it should only count opened services
            service_factory.create_batch(3, status='closed', host=host,
                                         workspace=host.workspace)
            service_factory.create_batch(2, status='filtered', host=host,
                                         workspace=host.workspace)
            session.commit()
            res = test_client.get(self.url(host))
            assert res.json['services'] == len(services)

    def test_index_shows_service_count(self, test_client, session,
                                       host_services, service_factory):
        ids_map = {host.id: services
                   for (host, services) in host_services.items()}

        # Adding closed and filtered services shouldn't impact on the
        # service count since it should only count opened services
        for host in host_services.keys():
            service_factory.create_batch(3, status='closed', host=host,
                                         workspace=host.workspace)
            service_factory.create_batch(2, status='filtered', host=host,
                                         workspace=host.workspace)

        session.commit()
        res = test_client.get(self.url())
        assert len(res.json['rows']) >= len(ids_map)  # Some hosts can have no services
        for host in res.json['rows']:
            if host['id'] in ids_map:
                assert host['value']['services'] == len(ids_map[host['id']])

    def test_filter_by_os_exact(self, test_client, session, workspace,
                                second_workspace, host_factory):
        # The hosts that should be shown
        hosts = host_factory.create_batch(10, workspace=workspace, os='Unix')

        # Search should be case sensitive so this shouln't be shown
        host_factory.create_batch(1, workspace=workspace, os='UNIX')

        # This shouldn't be shown, they are from other workspace
        host_factory.create_batch(5, workspace=second_workspace, os='Unix')

        session.commit()
        url = urljoin(self.url(), '?os=Unix')
        res = test_client.get(url)
        assert res.status_code == 200
        self.compare_results(hosts, res)

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_by_os_exact(self, test_client, session, workspace,
                                         second_workspace, host_factory):
        # The hosts that should be shown
        hosts = host_factory.create_batch(10, workspace=workspace, os='Unix')

        # Search should be case sensitive so this shouln't be shown
        host_factory.create_batch(1, workspace=workspace, os='UNIX')

        # This shouldn't be shown, they are from other workspace
        host_factory.create_batch(5, workspace=second_workspace, os='Unix')

        session.commit()
        res = test_client.get(join(self.url(), 'filter?q={"filters":[{"name": "os", "op":"eq", "val":"Unix"}]}'))
        assert res.status_code == 200
        self.compare_results(hosts, res)

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_count(self, test_client, session, workspace,
                                   second_workspace, host_factory):
        # The hosts that should be shown
        hosts = host_factory.create_batch(30, workspace=workspace, os='Unix')

        # This shouldn't be shown, they are from other workspace
        host_factory.create_batch(5, workspace=second_workspace, os='Unix')

        session.commit()
        res = test_client.get(join(self.url(), 'filter?q={"filters":[{"name": "os", "op":"eq", "val":"Unix"}],'
                                                  '"offset":0, "limit":20}'))
        assert res.status_code == 200
        assert res.json['count'] == 30

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_filter_and_group_by_os(self, test_client, session, workspace, host_factory):
        host_factory.create_batch(10, workspace=workspace, os='Unix')
        host_factory.create_batch(1, workspace=workspace, os='unix')
        session.commit()
        res = test_client.get(join(self.url(), 'filter?q={"filters":[{"name": "os", "op": "like", "val": "%nix"}], '
                                                  '"group_by":[{"field": "os"}], "order_by":[{"field": "os", "direction": "desc"}]}'))
        assert res.status_code == 200
        assert len(res.json['rows']) == 2
        assert res.json['count'] == 2
        assert 'unix' in [row['value']['os'] for row in res.json['rows']]
        assert 'Unix' in [row['value']['os'] for row in res.json['rows']]

    def test_filter_by_os_like_ilike(self, test_client, session, workspace,
                                     second_workspace, host_factory):
        # The hosts that should be shown
        hosts = host_factory.create_batch(5, workspace=workspace, os='Unix 1')
        hosts += host_factory.create_batch(5, workspace=workspace, os='Unix 2')

        # This should only be shown when using ilike, not when using like
        case_insensitive_host = host_factory.create(
            workspace=workspace, os='UNIX 3')

        # This doesn't match the like expression
        host_factory.create(workspace=workspace, os="Test Unix 1")

        # This shouldn't be shown anywhere, they are from other workspace
        host_factory.create_batch(5, workspace=second_workspace, os='Unix')

        session.commit()
        res = test_client.get(urljoin(self.url(), '?os__like=Unix %'))
        assert res.status_code == 200
        self.compare_results(hosts, res)

        res = test_client.get(urljoin(self.url(), '?os__ilike=Unix %'))
        assert res.status_code == 200
        self.compare_results(hosts + [case_insensitive_host], res)

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_by_os_like_ilike(self, test_client, session, workspace,
                                              second_workspace, host_factory):
        # The hosts that should be shown
        hosts = host_factory.create_batch(5, workspace=workspace, os='Unix 1')
        hosts += host_factory.create_batch(5, workspace=workspace, os='Unix 2')

        # This should only be shown when using ilike, not when using like
        case_insensitive_host = host_factory.create(
            workspace=workspace, os='UNIX 3')

        # This doesn't match the like expression
        host_factory.create(workspace=workspace, os="Test Unix 1")

        # This shouldn't be shown anywhere, they are from other workspace
        host_factory.create_batch(5, workspace=second_workspace, os='Unix')

        session.commit()
        res = test_client.get(join(
            self.url(),
            'filter?q={"filters":[{"name": "os", "op":"like", "val":"Unix %"}]}'
        )
        )
        assert res.status_code == 200
        self.compare_results(hosts, res)

        res = test_client.get(join(
            self.url(),
            'filter?q={"filters":[{"name": "os", "op":"ilike", "val":"Unix %"}]}'
        )
        )
        assert res.status_code == 200
        self.compare_results(hosts + [case_insensitive_host], res)

    def test_filter_by_service(self, test_client, session, workspace,
                               service_factory, host_factory):
        services = service_factory.create_batch(10, workspace=workspace,
                                                name="IRC")
        hosts = [service.host for service in services]

        # Hosts that shouldn't be shown
        host_factory.create_batch(5, workspace=workspace)

        session.commit()
        res = test_client.get(urljoin(self.url(), '?service=IRC'))
        assert res.status_code == 200
        shown_hosts_ids = {obj['id'] for obj in res.json['rows']}
        expected_host_ids = {host.id for host in hosts}
        assert shown_hosts_ids == expected_host_ids

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_by_service_name(self, test_client, session, workspace,
                                             service_factory, host_factory):
        services = service_factory.create_batch(10, workspace=workspace,
                                                name="IRC")
        hosts = [service.host for service in services]

        # Hosts that shouldn't be shown
        host_factory.create_batch(5, workspace=workspace)

        session.commit()

        res = test_client.get(
            join(
                self.url(),
                'filter?q={"filters":[{"name": "services__name", "op":"any", "val":"IRC"}]}'
            )
        )
        assert res.status_code == 200
        shown_hosts_ids = {obj['id'] for obj in res.json['rows']}
        expected_host_ids = {host.id for host in hosts}
        assert shown_hosts_ids == expected_host_ids

    def test_filter_by_service_port(self, test_client, session, workspace,
                                    service_factory, host_factory):
        services = service_factory.create_batch(10, workspace=workspace, port=25)
        hosts = [service.host for service in services]

        # Hosts that shouldn't be shown
        host_factory.create_batch(5, workspace=workspace)

        session.commit()
        res = test_client.get(urljoin(self.url(), '?port=25'))
        assert res.status_code == 200
        shown_hosts_ids = {obj['id'] for obj in res.json['rows']}
        expected_host_ids = {host.id for host in hosts}
        assert shown_hosts_ids == expected_host_ids

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_by_service_port(self, test_client, session, workspace,
                                             service_factory, host_factory):
        services = service_factory.create_batch(10, workspace=workspace, port=25)
        hosts = [service.host for service in services]

        # Hosts that shouldn't be shown
        host_factory.create_batch(5, workspace=workspace)

        session.commit()
        res = test_client.get(
            join(
                self.url(),
                'filter?q={"filters":[{"name": "services__port", "op":"any", "val":"25"}]}'
            )
        )
        assert res.status_code == 200
        shown_hosts_ids = {obj['id'] for obj in res.json['rows']}
        expected_host_ids = {host.id for host in hosts}
        assert shown_hosts_ids == expected_host_ids

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_verify_severity_counts(self, test_client, session, workspace, host_factory, vulnerability_factory):
        host = host_factory.create(workspace=workspace)
        vulnerability_factory.create(service=None, host=host, workspace=workspace, severity='critical')
        vulnerability_factory.create(service=None, host=host, workspace=workspace, severity='critical')
        vulnerability_factory.create(service=None, host=host, workspace=workspace, severity='high')
        vulnerability_factory.create(service=None, host=host, workspace=workspace, severity='low')
        vulnerability_factory.create(service=None, host=host, workspace=workspace, severity='informational')

        host2 = host_factory.create(workspace=workspace)
        vulnerability_factory.create(service=None, host=host2, workspace=workspace, severity='critical')
        vulnerability_factory.create(service=None, host=host2, workspace=workspace, severity='critical')

        session.commit()

        res = test_client.get(
            join(
                self.url(),
                f'filter?q={{"filters":[{{"name": "ip", "op":"eq", "val":"{host.ip}"}}]}}'
            )
        )

        assert res.status_code == 200

        severities = res.json['rows'][0]['value']['severity_counts']
        assert severities['info'] == 1
        assert severities['critical'] == 2
        assert severities['high'] == 1
        assert severities['med'] == 0
        assert severities['low'] == 1
        assert severities['unclassified'] == 0
        assert severities['total'] == 5

    def test_filter_by_invalid_service_port(self, test_client, session, workspace,
                                            service_factory, host_factory):
        services = service_factory.create_batch(10, workspace=workspace, port=25)
        hosts = [service.host for service in services]

        # Hosts that shouldn't be shown
        host_factory.create_batch(5, workspace=workspace)

        session.commit()
        res = test_client.get(urljoin(self.url(), '?port=invalid_port'))
        assert res.status_code == 200
        assert res.json['count'] == 0

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_by_invalid_service_port(self, test_client, session, workspace,
                                                     service_factory, host_factory):
        services = service_factory.create_batch(10, workspace=workspace, port=25)
        hosts = [service.host for service in services]

        # Hosts that shouldn't be shown
        host_factory.create_batch(5, workspace=workspace)

        session.commit()
        res = test_client.get(
            join(
                self.url(),
                'filter?q={"filters":[{"name": "services__port", "op":"any", "val":"sarasa"}]}'
            )
        )
        assert res.status_code == 400

    def test_filter_restless_by_invalid_field(self, test_client):
        res = test_client.get(
            join(
                self.url(),
                'filter?q={"filters":[{"name": "severity", "op":"any", "val":"sarasa"}]}'
            )
        )
        assert res.status_code == 400

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_with_no_q_param(self, test_client, session, workspace, host_factory):
        res = test_client.get(join(self.url(), 'filter'))
        assert res.status_code == 200
        assert len(res.json['rows']) == HOSTS_COUNT

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_filter_restless_with_empty_q_param(self, test_client, session, workspace, host_factory):
        res = test_client.get(join(self.url(), 'filter?q'))
        assert res.status_code == 400

    def test_search_ip(self, test_client, session, workspace, host_factory):
        host = host_factory.create(ip="longname",
                                   workspace=workspace)
        session.commit()
        res = test_client.get(urljoin(self.url(), '?search=ONGNAM'))
        assert res.status_code == 200
        assert len(res.json['rows']) == 1
        assert res.json['rows'][0]['id'] == host.id

    @pytest.mark.usefixtures('host_services')
    def test_search_service_name(self, test_client, session, workspace,
                                 service_factory):
        expected_hosts = [self.hosts[2], self.hosts[4]]
        for host in expected_hosts:
            service_factory.create(host=host, name="GOPHER 5",
                                   workspace=workspace)
        session.commit()
        res = test_client.get(urljoin(self.url(), '?search=gopher'))
        assert res.status_code == 200
        shown_hosts_ids = {obj['id'] for obj in res.json['rows']}
        expected_host_ids = {host.id for host in expected_hosts}
        assert shown_hosts_ids == expected_host_ids

    @pytest.mark.usefixtures('host_with_hostnames')
    def test_search_by_hostname(self, test_client, session, workspace):
        expected_hosts = [self.hosts[2], self.hosts[4]]
        for host in expected_hosts:
            host.set_hostnames(['staging.twitter.com'])
        session.commit()
        res = test_client.get(urljoin(self.url(), '?search=twitter'))
        assert res.status_code == 200
        shown_hosts_ids = {obj['id'] for obj in res.json['rows']}
        expected_host_ids = {host.id for host in expected_hosts}
        assert shown_hosts_ids == expected_host_ids

    def test_host_with_open_vuln_count_verification(self, test_client, session,
                                                    workspace, host_factory,
                                                    vulnerability_factory,
                                                    service_factory):

        host = host_factory.create(workspace=workspace)
        service = service_factory.create(host=host, workspace=workspace)
        vulnerability_factory.create(service=service, host=None, workspace=workspace, severity="low")
        vulnerability_factory.create(service=None, host=host, workspace=workspace, severity="critical")

        session.commit()

        res = test_client.get(self.url())
        assert res.status_code == 200
        json_host = list(filter(lambda json_host: json_host['value']['id'] == host.id, res.json['rows']))[0]
        # the host has one vuln associated. another one via service.
        assert json_host['value']['vulns'] == 2
        assert json_host['value']['severity_counts']['critical'] == 1
        assert json_host['value']['severity_counts']['low'] == 1
        assert json_host['value']['severity_counts']['info'] == 0
        assert json_host['value']['severity_counts']['unclassified'] == 0
        assert json_host['value']['severity_counts']['med'] == 0
        assert json_host['value']['severity_counts']['high'] == 0

    def test_host_services_vuln_count_verification(self, test_client, session,
                                                   workspace, host_factory, vulnerability_factory,
                                                   service_factory):
        host = host_factory.create(workspace=workspace)
        service = service_factory.create(host=host, workspace=workspace)
        vulnerability_factory.create(service=service, host=None, workspace=workspace)
        session.commit()

        res = test_client.get(join(self.url(host), 'services'))
        assert res.status_code == 200
        assert res.json[0]['vulns'] == 1

    def test_create_host_with_hostnames(self, test_client):
        raw_data = {
            "ip": "192.168.0.21",
            "hostnames": ["google.com"],
            "mac": "00:00:00:00:00:00",
            "description": "",
            "os": "",
            "owned": False,
            "owner": ""
        }
        res = test_client.post(self.url(), data=raw_data)
        assert res.status_code == 201
        assert res.json['hostnames'] == ['google.com']
        host = Host.query.get(res.json['id'])
        assert len(host.hostnames) == 1
        assert host.hostnames[0].name == 'google.com'

    def test_update_host_with_hostnames(self, test_client, session,
                                        host_with_hostnames):
        session.commit()
        data = {
            "ip": "192.168.0.21",
            "hostnames": ["other.com", "test.com"],
            "mac": "00:00:00:00:00:00",
            "description": "",
            "os": "",
            "owned": False,
            "owner": ""
        }
        res = test_client.put(self.url(host_with_hostnames), data=data)
        assert res.status_code == 200
        expected = {"other.com", "test.com"}
        assert set(res.json['hostnames']) == expected
        assert {hn.name for hn in host_with_hostnames.hostnames} == expected

    def test_create_host_with_default_gateway(self, test_client):
        raw_data = {
            "ip": "192.168.0.21",
            "default_gateway": "192.168.0.1",
            "mac": "00:00:00:00:00:00", "description": "",
            "os": "", "owned": False, "owner": ""
        }
        res = test_client.post(self.url(), data=raw_data)
        assert res.status_code == 201
        assert res.json['default_gateway'] == '192.168.0.1'

    def test_update_host(self, test_client, session):
        host = HostFactory.create()
        session.commit()
        raw_data = {
            "metadata":
                {
                    "update_time": 1510688312.431,
                    "update_user": "UI Web",
                    "update_action": 0,
                    "creator": "",
                    "create_time": 1510673388000,
                    "update_controller_action": "",
                    "owner": "leonardo",
                    "command_id": None},
            "name": "10.31.112.21",
            "ip": "10.31.112.21",
            "_rev": "",
            "description": "",
            "default_gateway": None,
            "owned": False,
            "services": 12,
            "hostnames": [],
            "vulns": 43,
            "owner": "leonardo",
            "credentials": 0,
            "_id": 4000,
            "os": "Microsoft Windows Server 2008 R2 Standard Service Pack 1",
            "id": 4000,
            "icon": "windows",
            "versions": [],
            "important": False,
        }

        res = test_client.put(self.url(host, workspace=host.workspace), data=raw_data)
        assert res.status_code == 200
        updated_host = Host.query.filter_by(id=host.id).first()
        assert res.json == {
            '_id': host.id,
            'type': 'Host',
            '_rev': '',
            'credentials': 0,
            'default_gateway': '',
            'description': '',
            'hostnames': [],
            'id': host.id,
            'ip': '10.31.112.21',
            'mac': '',
            'metadata': {
                'command_id': None,
                'create_time': pytz.UTC.localize(updated_host.create_date).isoformat(),
                'creator': '',
                'owner': host.creator.username,
                'update_action': 0,
                'update_controller_action': '',
                'update_time': pytz.UTC.localize(updated_host.update_date).isoformat(),
                'update_user': None},
            'name': '10.31.112.21',
            'os': 'Microsoft Windows Server 2008 R2 Standard Service Pack 1',
            'owned': False,
            'owner': host.creator.username,
            'services': 0,
            'service_summaries': [],
            'vulns': 0,
            "versions": [],
            'important': False,
            'severity_counts': {
                'critical': None,
                'high': None,
                'host_id': host.id,
                'info': None,
                'med': None,
                'low': None,
                'total': None,
                'unclassified': None
            }
        }

    def test_add_hosts_from_csv(self, session, test_client, csrf_token):
        ws = WorkspaceFactory.create(name='abc')
        session.add(ws)
        session.commit()
        expected_created_hosts = 2
        file_contents = b"""ip,description,os,hostnames\n
10.10.10.10,test_host,linux,\"['localhost','test_host']\"\n
10.10.10.11,test_host,linux,\"['localhost','test_host_1']"
"""
        data = {
            'file': (BytesIO(file_contents), 'hosts.csv'),
            'csrf_token': csrf_token
        }
        headers = {'Content-type': 'multipart/form-data'}
        res = test_client.post(f'/v3/ws/{ws.name}/hosts/bulk_create',
                               data=data, headers=headers, use_json_data=False)
        assert res.status_code == 200
        assert res.json['hosts_created'] == expected_created_hosts
        assert res.json['hosts_with_errors'] == 0
        assert session.query(Host).filter_by(description="test_host").count() == expected_created_hosts

    def test_bulk_delete_hosts(self, test_client, session):
        host_1 = HostFactory.create(workspace=self.workspace)
        host_2 = HostFactory.create(workspace=self.workspace)
        session.commit()
        hosts_ids = [host_1.id, host_2.id]
        request_data = {'ids': hosts_ids}

        delete_response = test_client.delete(self.url(), data=request_data)

        deleted_hosts = delete_response.json['deleted']
        host_count_after_delete = db.session.query(Host).filter(
            Host.id.in_(hosts_ids),
            Host.workspace_id == self.workspace.id).count()

        assert delete_response.status_code == 200
        assert deleted_hosts == len(hosts_ids)
        assert host_count_after_delete == 0

    def test_bulk_delete_hosts_without_hosts_ids(self, test_client):
        request_data = {'hosts_ids': []}

        delete_response = test_client.delete(self.url(), data=request_data)

        assert delete_response.status_code == 400

    def test_bulk_delete_hosts_from_another_workspace(self, test_client, session):
        workspace_1 = WorkspaceFactory.create(name='workspace_1')
        host_of_ws_1 = HostFactory.create(workspace=workspace_1)
        workspace_2 = WorkspaceFactory.create(name='workspace_2')
        host_of_ws_2 = HostFactory.create(workspace=workspace_2)
        session.commit()

        # Try to delete workspace_2's host from workspace_1
        request_data = {'ids': [host_of_ws_2.id]}
        url = f'/v3/ws/{workspace_1.name}/hosts'
        delete_response = test_client.delete(url, data=request_data)

        assert delete_response.status_code == 200
        assert delete_response.json['deleted'] == 0

    def test_bulk_delete_hosts_invalid_characters_in_request(self, test_client):
        ws = WorkspaceFactory.create(name="abc")
        request_data = {'ids': [-1, 'test']}
        delete_response = test_client.delete(f'/v3/ws/{ws.name}/hosts', data=request_data)

        assert delete_response.json['deleted'] == 0

    def test_bulk_delete_hosts_wrong_content_type(self, test_client, session):
        ws = WorkspaceFactory.create(name="abc")
        host_1 = HostFactory.create(workspace=ws)
        host_2 = HostFactory.create(workspace=ws)
        session.commit()
        hosts_ids = [host_1.id, host_2.id]

        request_data = {'ids': hosts_ids}
        headers = [('content-type', 'text/xml')]

        delete_response = test_client.delete(
            f'/v3/ws/{ws.name}/hosts',
            data=request_data,
            headers=headers)

        assert delete_response.status_code == 400

    def test_bulk_delete_with_references(self, test_client, session, workspace, host_factory, vulnerability_factory,
                                         service_factory, credential_factory):
        host_1 = host_factory.create(workspace=workspace)
        service_factory.create(host=host_1, workspace=workspace)
        vulnerability_factory.create(service=None, host=host_1, workspace=workspace)
        host_1.hostnames.append(HostnameFactory.create(name='pepe1', workspace=workspace, host=host_1))
        credential_factory.create(workspace=workspace, host=host_1)

        host_2 = host_factory.create(workspace=workspace)
        service_factory.create(host=host_2, workspace=workspace)
        vulnerability_factory.create(service=None, host=host_2, workspace=workspace)
        host_1.hostnames.append(HostnameFactory.create(name='pepe2', workspace=workspace, host=host_2))
        credential_factory.create(workspace=workspace, host=host_2)

        session.commit()

        hosts_ids = [host_1.id, host_2.id]
        request_data = {'ids': hosts_ids}
        url = f'/v3/ws/{workspace.name}/hosts'
        delete_response = test_client.delete(url, data=request_data)

        assert delete_response.status_code == 200
        assert delete_response.json['deleted'] == 2


class TestHostAPIGeneric(ReadWriteAPITests, PaginationTestsMixin, BulkUpdateTestsMixin, BulkDeleteTestsMixin):
    model = Host
    factory = factories.HostFactory
    api_endpoint = 'hosts'
    unique_fields = ['ip']
    update_fields = ['ip', 'description', 'os']
    patchable_fields = update_fields
    view_class = HostsView

    @pytest.mark.usefixtures("mock_envelope_list")
    def test_sort_by_description(self, test_client, session):
        for host in Host.query.all():
            # I don't want to test case sensitive sorting
            host.description = host.description.lower()
        session.commit()
        expected_ids = [host.id for host in
                        sorted(Host.query.all(),
                               key=operator.attrgetter('description'))]
        res = test_client.get(urljoin(self.url(), '?sort=description&sort_dir=asc'))
        assert res.status_code == 200
        assert [host['_id'] for host in res.json['data']] == expected_ids

        expected_ids.reverse()  # In place list reverse
        res = test_client.get(urljoin(self.url(), '?sort=description&sort_dir=desc'))
        assert res.status_code == 200
        assert [host['_id'] for host in res.json['data']] == expected_ids

    @pytest.mark.usefixtures("mock_envelope_list")
    def test_sort_by_services(self, test_client, session, second_workspace,
                              host_factory, service_factory):
        expected_ids = []
        for i in range(10):
            host = host_factory.create(workspace=second_workspace)
            service_factory.create_batch(
                i, host=host, workspace=second_workspace, status='open')
            session.flush()
            expected_ids.append(host.id)
        session.commit()
        res = test_client.get(urljoin(self.url(workspace=second_workspace),
                                      '?sort=services&sort_dir=asc'))
        assert res.status_code == 200
        assert [h['_id'] for h in res.json['data']] == expected_ids

    @pytest.mark.usefixtures("mock_envelope_list")
    def test_sort_by_update_time(self, test_client, session, second_workspace,
                                 host_factory):
        """
        This test doesn't test only the hosts view, but all the ones that
        expose a object with metadata.
        Think twice if you are thinking in removing it
        """
        expected = host_factory.create_batch(10, workspace=second_workspace)
        session.commit()
        for i in range(len(expected)):
            if i % 2 == 0:  # Only update some hosts
                host = expected.pop(0)
                host.description = 'i was updated'
                session.add(host)
                session.commit()
                expected.append(host)  # Put it on the end
        res = test_client.get(urljoin(self.url(workspace=second_workspace),
                              '?sort=metadata.update_time&sort_dir=asc'))
        assert res.status_code == 200, res.data
        assert [h['_id'] for h in res.json['data']] == [h.id for h in expected]

    def test_create_a_host_twice_returns_conflict(self, test_client):
        res = test_client.post(self.url(), data={
            "ip": "127.0.0.1",
            "description": "aaaaa",
        })
        assert res.status_code == 201
        assert Host.query.count() == HOSTS_COUNT + 1
        host_id = res.json['id']
        host = Host.query.get(host_id)
        assert host.ip == "127.0.0.1"
        assert host.description == "aaaaa"
        assert host.os == ''
        assert host.workspace == self.workspace
        res = test_client.post(self.url(), data={
            "ip": "127.0.0.1",
            "description": "aaaaa",
        })
        assert res.status_code == 409
        assert res.json['object']['_id'] == host_id

    def test_create_host_from_command(self, test_client, session):
        command = EmptyCommandFactory.create()
        session.commit()
        assert len(command.command_objects) == 0
        url = urljoin(self.url(workspace=command.workspace), f"?{urlencode({'command_id': command.id})}")

        res = test_client.post(url, data={
            "ip": "127.0.0.1",
            "description": "aaaaa",
        })

        assert res.status_code == 201
        assert len(command.command_objects) == 1
        cmd_obj = command.command_objects[0]
        assert cmd_obj.object_type == 'host'
        assert cmd_obj.object_id == res.json['id']

    def test_create_host_cant_assign_command_from_another_workspace(self, test_client, session):
        command = EmptyCommandFactory.create()
        new_workspace = WorkspaceFactory.create()
        session.commit()
        assert len(command.command_objects) == 0
        url = urljoin(self.url(workspace=new_workspace), f"?{urlencode({'command_id': command.id})}")

        res = test_client.post(url, data={
            "ip": "127.0.0.1",
            "description": "aaaaa",
        })

        assert res.status_code == 400
        assert res.json == {'message': 'Command not found.'}
        assert len(command.command_objects) == 0

    def test_service_summaries(self, test_client, session, service_factory):
        service_factory.create(name='http', protocol='tcp', port=80,
                               host=self.first_object, status='open',
                               version='nginx',
                               workspace=self.workspace)
        service_factory.create(name='https', protocol='tcp', port=443,
                               host=self.first_object, status='open',
                               version=None,
                               workspace=self.workspace)
        service_factory.create(name='dns', protocol='udp', port=5353,
                               host=self.first_object, status='open',
                               version=None,
                               workspace=self.workspace)
        service_factory.create(name='smtp', protocol='tcp', port=25,
                               host=self.first_object, status='filtered',
                               version=None,
                               workspace=self.workspace)
        service_factory.create(name='dns', protocol='udp', port=53,
                               host=self.first_object, status='open',
                               version=None,
                               workspace=self.workspace)
        service_factory.create(name='other', protocol='udp', port=1234,
                               host=self.first_object, status='closed',
                               version=None,
                               workspace=self.workspace)
        session.commit()
        res = test_client.get(self.url(self.first_object))
        assert res.status_code == 200
        service_summaries = res.json['service_summaries']
        assert service_summaries == [
            '(80/tcp) http (nginx)',
            '(443/tcp) https',
            '(53/udp) dns',
            '(5353/udp) dns',
        ]

    def test_delete_host_with_blank_ip(self, session, test_client):
        """
            Bug found while deleting data from workspaces.
            If we don't allow blank in name we should delete this test.
        """
        host = self.factory.create(ip='')
        session.add(host)
        session.commit()

        res = test_client.delete(self.url(host, workspace=host.workspace))
        assert res.status_code == 204

    def test_update_hostname(self, session, test_client):
        host = HostFactory.create()
        session.add(host)
        session.commit()
        data = {
            "description": "",
            "default_gateway": "",
            "ip": "127.0.0.1",
            "owned": False,
            "name": "127.0.0.1",
            "mac": "",
            "hostnames": ["dasdas"],
            "owner": "faraday",
            "os": "Unknown",
        }

        res = test_client.put(self.url(host, workspace=host.workspace), data=data)
        assert res.status_code == 200

        assert session.query(Hostname).filter_by(host=host).count() == 1
        assert session.query(Hostname).all()[0].name == 'dasdas'

    @pytest.mark.skip  # TODO unskip
    def test_hosts_ordered_by_vulns_severity(self, session, test_client, service_factory,
                                             vulnerability_factory, vulnerability_web_factory):
        ws = WorkspaceFactory.create()
        session.add(ws)
        hosts_list = []
        for i in range(0, 10):
            host = HostFactory.create(workspace=ws)
            session.add(host)
            service = service_factory.create(workspace=ws, host=host)
            session.add(service)
            hosts_list.append(host)
        session.commit()

        severities = ['critical', 'high', 'medium', 'low', 'informational', 'unclassified']
        # Vulns counter by severity in host
        vulns_by_severity = {host.id: [0, 0, 0, 0, 0, 0] for host in hosts_list}

        for host in hosts_list:
            # Each host has 10 vulns
            for i in range(0, 10):
                vuln_web = choice([True, False])
                severity = choice(severities)

                if vuln_web:
                    vuln = vulnerability_web_factory.create(
                        workspace=ws, service=host.services[0], severity=severity
                    )
                else:
                    vuln = vulnerability_factory.create(
                        host=None, service=host.services[0],
                        workspace=host.workspace, severity=severity
                    )
                session.add(vuln)

                # Increase 1 to number of vulns by severity in the host
                vulns_by_severity[host.id][severities.index(severity)] += 1
        session.commit()

        # Sort vulns_by_severity by number of vulns by severity in every host
        sorted_hosts = sorted(
            vulns_by_severity.items(),
            key=lambda host: [vuln_count for vuln_count in host[1]],
            reverse=True
        )

        res = test_client.get(self.url(workspace=ws))
        assert res.status_code == 200

        response_hosts = res.json['rows']
        for host in response_hosts:
            # sorted_hosts and response_hosts have the same order so the index
            # of host in sorted_host is the same as the
            # index of host in response_hosts
            index_in_sorted_host = [host_tuple[0] for host_tuple in sorted_hosts].index(host['id'])
            index_in_response_hosts = response_hosts.index(host)

            assert index_in_sorted_host == index_in_response_hosts

    def test_hosts_order_without_vulns(self, session, test_client):
        # If a host has no vulns, it should be ordered by IP in ascending order
        ws = WorkspaceFactory.create()
        session.add(ws)
        hosts_ids = []
        for i in range(0, 10):
            host = HostFactory.create(workspace=ws, ip=f'127.0.0.{i}')
            session.add(host)
            session.commit()
            hosts_ids.append(host.id)

        res = test_client.get(self.url(workspace=ws))
        assert res.status_code == 200

        response_hosts = res.json['rows']
        for host in response_hosts:
            # hosts_ids and response_hosts have the same order so the index
            # of host in hosts_ids is the same as the
            # index of host in response_hosts
            index_in_hosts_ids = hosts_ids.index(host['id'])
            index_in_response_hosts = response_hosts.index(host)

            assert index_in_hosts_ids == index_in_response_hosts

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_bulk_update_host_with_hostnames(self, test_client, session,
                                        host_with_hostnames):
        session.commit()
        data = {
            "ids": [host_with_hostnames.id, self.first_object.id],
            "hostnames": ["other.com", "test.com"],
        }
        res = test_client.patch(self.url(), data=data)
        assert res.status_code == 200
        assert res.json["updated"] == 2
        expected = {"other.com", "test.com"}
        assert {hn.name for hn in host_with_hostnames.hostnames} == expected
        assert {hn.name for hn in self.first_object.hostnames} == expected

    @pytest.mark.usefixtures('ignore_nplusone')
    def test_bulk_update_host_without_hostnames(self, test_client, session,
                                                host_with_hostnames):
        session.commit()
        expected = {hn.name for hn in host_with_hostnames.hostnames}
        data = {
            "ids": [host_with_hostnames.id],
            "os": "NotAnOS"
        }
        res = test_client.patch(self.url(), data=data)
        assert res.status_code == 200
        assert res.json["updated"] == 1
        assert {hn.name for hn in host_with_hostnames.hostnames} == expected


def host_json():
    return st.fixed_dictionaries(
        {
            "metadata":
                st.fixed_dictionaries({
                    "update_time": st.floats(),
                    "update_user": st.one_of(st.none(), st.text()),
                    "update_action": st.integers(),
                    "creator": st.text(),
                    "create_time": st.integers(),
                    "update_controller_action": st.text(),
                    "owner": st.one_of(st.none(), st.text()),
                    "command_id": st.one_of(st.none(), st.text(), st.integers()), }),
            "name": st.one_of(st.none(), st.text()),
            "ip": st.one_of(st.none(), st.text()),
            "_rev": st.one_of(st.none(), st.text()),
            "description": st.one_of(st.none(), st.text()),
            "default_gateway": st.one_of(st.none(), st.text()),
            "owned": st.booleans(),
            "services": st.one_of(st.none(), st.integers()),
            "hostnames": st.lists(st.text()),
            "vulns": st.one_of(st.none(), st.integers()),
            "owner": st.one_of(st.none(), st.text()),
            "credentials": st.one_of(st.none(), st.integers()),
            "_id": st.one_of(st.none(), st.integers()),
            "os": st.one_of(st.none(), st.text()),
            "id": st.one_of(st.none(), st.integers()),
            "icon": st.one_of(st.none(), st.text())}
    )


@pytest.mark.usefixtures('logged_user')
@pytest.mark.hypothesis
def test_hypothesis(host_with_hostnames, test_client, session):
    session.commit()
    HostData = host_json()

    @given(HostData)
    def send_api_request(raw_data):
        ws_name = host_with_hostnames.workspace.name
        res = test_client.post(f'/v3/ws/{ws_name}/vulns',
                               data=raw_data)
        assert res.status_code in [201, 400, 409]

    send_api_request()